blob: b15f6ab98440f0ff1167f72563a7abebadd76517 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Douglas Gregoraa57e862009-02-18 21:56:37 +000029/// \brief Determine whether the use of this declaration is valid, and
30/// emit any corresponding diagnostics.
31///
32/// This routine diagnoses various problems with referencing
33/// declarations that can occur when using a declaration. For example,
34/// it might warn if a deprecated or unavailable declaration is being
35/// used, or produce an error (and return true) if a C++0x deleted
36/// function is being used.
37///
38/// \returns true if there was an error (this declaration cannot be
39/// referenced), false otherwise.
40bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000041 // See if the decl is deprecated.
42 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000043 // Implementing deprecated stuff requires referencing deprecated
44 // stuff. Don't warn if we are implementing a deprecated
45 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000046 bool isSilenced = false;
47
48 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
49 // If this reference happens *in* a deprecated function or method, don't
50 // warn.
51 isSilenced = ND->getAttr<DeprecatedAttr>();
52
53 // If this is an Objective-C method implementation, check to see if the
54 // method was deprecated on the declaration, not the definition.
55 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
56 // The semantic decl context of a ObjCMethodDecl is the
57 // ObjCImplementationDecl.
58 if (ObjCImplementationDecl *Impl
59 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
60
61 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
62 MD->isInstanceMethod());
63 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
64 }
65 }
66 }
67
68 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000069 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
70 }
71
Douglas Gregoraa57e862009-02-18 21:56:37 +000072 // See if this is a deleted function.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000073 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000074 if (FD->isDeleted()) {
75 Diag(Loc, diag::err_deleted_function_use);
76 Diag(D->getLocation(), diag::note_unavailable_here) << true;
77 return true;
78 }
Douglas Gregor6f8c3682009-02-24 04:26:15 +000079 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000080
81 // See if the decl is unavailable
82 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000083 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000084 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
85 }
86
Douglas Gregoraa57e862009-02-18 21:56:37 +000087 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000088}
89
Douglas Gregor3bb30002009-02-26 21:00:50 +000090SourceRange Sema::getExprRange(ExprTy *E) const {
91 Expr *Ex = (Expr *)E;
92 return Ex? Ex->getSourceRange() : SourceRange();
93}
94
Chris Lattner299b8842008-07-25 21:10:04 +000095//===----------------------------------------------------------------------===//
96// Standard Promotions and Conversions
97//===----------------------------------------------------------------------===//
98
Chris Lattner299b8842008-07-25 21:10:04 +000099/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
100void Sema::DefaultFunctionArrayConversion(Expr *&E) {
101 QualType Ty = E->getType();
102 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
103
Chris Lattner299b8842008-07-25 21:10:04 +0000104 if (Ty->isFunctionType())
105 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000106 else if (Ty->isArrayType()) {
107 // In C90 mode, arrays only promote to pointers if the array expression is
108 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
109 // type 'array of type' is converted to an expression that has type 'pointer
110 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
111 // that has type 'array of type' ...". The relevant change is "an lvalue"
112 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000113 //
114 // C++ 4.2p1:
115 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
116 // T" can be converted to an rvalue of type "pointer to T".
117 //
118 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
119 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +0000120 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
121 }
Chris Lattner299b8842008-07-25 21:10:04 +0000122}
123
124/// UsualUnaryConversions - Performs various conversions that are common to most
125/// operators (C99 6.3). The conversions of array and function types are
126/// sometimes surpressed. For example, the array->pointer conversion doesn't
127/// apply if the array is an argument to the sizeof or address (&) operators.
128/// In these instances, this routine should *not* be called.
129Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
130 QualType Ty = Expr->getType();
131 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
132
Chris Lattner299b8842008-07-25 21:10:04 +0000133 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
134 ImpCastExprToType(Expr, Context.IntTy);
135 else
136 DefaultFunctionArrayConversion(Expr);
137
138 return Expr;
139}
140
Chris Lattner9305c3d2008-07-25 22:25:12 +0000141/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
142/// do not have a prototype. Arguments that have type float are promoted to
143/// double. All other argument types are converted by UsualUnaryConversions().
144void Sema::DefaultArgumentPromotion(Expr *&Expr) {
145 QualType Ty = Expr->getType();
146 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
147
148 // If this is a 'float' (CVR qualified or typedef) promote to double.
149 if (const BuiltinType *BT = Ty->getAsBuiltinType())
150 if (BT->getKind() == BuiltinType::Float)
151 return ImpCastExprToType(Expr, Context.DoubleTy);
152
153 UsualUnaryConversions(Expr);
154}
155
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000156// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
157// will warn if the resulting type is not a POD type.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000158void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000159 DefaultArgumentPromotion(Expr);
160
161 if (!Expr->getType()->isPODType()) {
162 Diag(Expr->getLocStart(),
163 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
164 Expr->getType() << CT;
165 }
166}
167
168
Chris Lattner299b8842008-07-25 21:10:04 +0000169/// UsualArithmeticConversions - Performs various conversions that are common to
170/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
171/// routine returns the first non-arithmetic type found. The client is
172/// responsible for emitting appropriate error diagnostics.
173/// FIXME: verify the conversion rules for "complex int" are consistent with
174/// GCC.
175QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
176 bool isCompAssign) {
177 if (!isCompAssign) {
178 UsualUnaryConversions(lhsExpr);
179 UsualUnaryConversions(rhsExpr);
180 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000181
Chris Lattner299b8842008-07-25 21:10:04 +0000182 // For conversion purposes, we ignore any qualifiers.
183 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000184 QualType lhs =
185 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
186 QualType rhs =
187 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000188
189 // If both types are identical, no conversion is needed.
190 if (lhs == rhs)
191 return lhs;
192
193 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
194 // The caller can deal with this (e.g. pointer + int).
195 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
196 return lhs;
197
198 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
199 if (!isCompAssign) {
200 ImpCastExprToType(lhsExpr, destType);
201 ImpCastExprToType(rhsExpr, destType);
202 }
203 return destType;
204}
205
206QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
207 // Perform the usual unary conversions. We do this early so that
208 // integral promotions to "int" can allow us to exit early, in the
209 // lhs == rhs check. Also, for conversion purposes, we ignore any
210 // qualifiers. For example, "const float" and "float" are
211 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000212 if (lhs->isPromotableIntegerType())
213 lhs = Context.IntTy;
214 else
215 lhs = lhs.getUnqualifiedType();
216 if (rhs->isPromotableIntegerType())
217 rhs = Context.IntTy;
218 else
219 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000220
Chris Lattner299b8842008-07-25 21:10:04 +0000221 // If both types are identical, no conversion is needed.
222 if (lhs == rhs)
223 return lhs;
224
225 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
226 // The caller can deal with this (e.g. pointer + int).
227 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
228 return lhs;
229
230 // At this point, we have two different arithmetic types.
231
232 // Handle complex types first (C99 6.3.1.8p1).
233 if (lhs->isComplexType() || rhs->isComplexType()) {
234 // if we have an integer operand, the result is the complex type.
235 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
236 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000237 return lhs;
238 }
239 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
240 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000241 return rhs;
242 }
243 // This handles complex/complex, complex/float, or float/complex.
244 // When both operands are complex, the shorter operand is converted to the
245 // type of the longer, and that is the type of the result. This corresponds
246 // to what is done when combining two real floating-point operands.
247 // The fun begins when size promotion occur across type domains.
248 // From H&S 6.3.4: When one operand is complex and the other is a real
249 // floating-point type, the less precise type is converted, within it's
250 // real or complex domain, to the precision of the other type. For example,
251 // when combining a "long double" with a "double _Complex", the
252 // "double _Complex" is promoted to "long double _Complex".
253 int result = Context.getFloatingTypeOrder(lhs, rhs);
254
255 if (result > 0) { // The left side is bigger, convert rhs.
256 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000257 } else if (result < 0) { // The right side is bigger, convert lhs.
258 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000259 }
260 // At this point, lhs and rhs have the same rank/size. Now, make sure the
261 // domains match. This is a requirement for our implementation, C99
262 // does not require this promotion.
263 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
264 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000265 return rhs;
266 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000267 return lhs;
268 }
269 }
270 return lhs; // The domain/size match exactly.
271 }
272 // Now handle "real" floating types (i.e. float, double, long double).
273 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
274 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000275 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000276 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000277 return lhs;
278 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000279 if (rhs->isComplexIntegerType()) {
280 // convert rhs to the complex floating point type.
281 return Context.getComplexType(lhs);
282 }
283 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000284 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000285 return rhs;
286 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000287 if (lhs->isComplexIntegerType()) {
288 // convert lhs to the complex floating point type.
289 return Context.getComplexType(rhs);
290 }
Chris Lattner299b8842008-07-25 21:10:04 +0000291 // We have two real floating types, float/complex combos were handled above.
292 // Convert the smaller operand to the bigger result.
293 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000294 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000295 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000296 assert(result < 0 && "illegal float comparison");
297 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000298 }
299 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
300 // Handle GCC complex int extension.
301 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
302 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
303
304 if (lhsComplexInt && rhsComplexInt) {
305 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000306 rhsComplexInt->getElementType()) >= 0)
307 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000308 return rhs;
309 } else if (lhsComplexInt && rhs->isIntegerType()) {
310 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000311 return lhs;
312 } else if (rhsComplexInt && lhs->isIntegerType()) {
313 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000314 return rhs;
315 }
316 }
317 // Finally, we have two differing integer types.
318 // The rules for this case are in C99 6.3.1.8
319 int compare = Context.getIntegerTypeOrder(lhs, rhs);
320 bool lhsSigned = lhs->isSignedIntegerType(),
321 rhsSigned = rhs->isSignedIntegerType();
322 QualType destType;
323 if (lhsSigned == rhsSigned) {
324 // Same signedness; use the higher-ranked type
325 destType = compare >= 0 ? lhs : rhs;
326 } else if (compare != (lhsSigned ? 1 : -1)) {
327 // The unsigned type has greater than or equal rank to the
328 // signed type, so use the unsigned type
329 destType = lhsSigned ? rhs : lhs;
330 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
331 // The two types are different widths; if we are here, that
332 // means the signed type is larger than the unsigned type, so
333 // use the signed type.
334 destType = lhsSigned ? lhs : rhs;
335 } else {
336 // The signed type is higher-ranked than the unsigned type,
337 // but isn't actually any bigger (like unsigned int and long
338 // on most 32-bit systems). Use the unsigned type corresponding
339 // to the signed type.
340 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
341 }
Chris Lattner299b8842008-07-25 21:10:04 +0000342 return destType;
343}
344
345//===----------------------------------------------------------------------===//
346// Semantic Analysis for various Expression Types
347//===----------------------------------------------------------------------===//
348
349
Steve Naroff87d58b42007-09-16 03:34:24 +0000350/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000351/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
352/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
353/// multiple tokens. However, the common case is that StringToks points to one
354/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000355///
356Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000357Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000358 assert(NumStringToks && "Must have at least one string!");
359
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000360 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000361 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000362 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000363
364 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
365 for (unsigned i = 0; i != NumStringToks; ++i)
366 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000367
Chris Lattnera6dcce32008-02-11 00:02:17 +0000368 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000369 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000370 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000371
372 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
373 if (getLangOptions().CPlusPlus)
374 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000375
Chris Lattnera6dcce32008-02-11 00:02:17 +0000376 // Get an array type for the string, according to C99 6.4.5. This includes
377 // the nul terminator character as well as the string length for pascal
378 // strings.
379 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000380 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000381 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000382
Chris Lattner4b009652007-07-25 00:24:17 +0000383 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000384 return Owned(StringLiteral::Create(Context, Literal.GetString(),
385 Literal.GetStringLength(),
386 Literal.AnyWide, StrTy,
387 &StringTokLocs[0],
388 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000389}
390
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000391/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
392/// CurBlock to VD should cause it to be snapshotted (as we do for auto
393/// variables defined outside the block) or false if this is not needed (e.g.
394/// for values inside the block or for globals).
395///
396/// FIXME: This will create BlockDeclRefExprs for global variables,
397/// function references, etc which is suboptimal :) and breaks
398/// things like "integer constant expression" tests.
399static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
400 ValueDecl *VD) {
401 // If the value is defined inside the block, we couldn't snapshot it even if
402 // we wanted to.
403 if (CurBlock->TheDecl == VD->getDeclContext())
404 return false;
405
406 // If this is an enum constant or function, it is constant, don't snapshot.
407 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
408 return false;
409
410 // If this is a reference to an extern, static, or global variable, no need to
411 // snapshot it.
412 // FIXME: What about 'const' variables in C++?
413 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
414 return Var->hasLocalStorage();
415
416 return true;
417}
418
419
420
Steve Naroff0acc9c92007-09-15 18:49:24 +0000421/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000422/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000423/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000424/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000425/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000426Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
427 IdentifierInfo &II,
428 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000429 const CXXScopeSpec *SS,
430 bool isAddressOfOperand) {
431 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000432 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000433}
434
Douglas Gregor566782a2009-01-06 05:10:23 +0000435/// BuildDeclRefExpr - Build either a DeclRefExpr or a
436/// QualifiedDeclRefExpr based on whether or not SS is a
437/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000438DeclRefExpr *
439Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
440 bool TypeDependent, bool ValueDependent,
441 const CXXScopeSpec *SS) {
Douglas Gregor7e508262009-03-19 03:51:16 +0000442 if (SS && !SS->isEmpty()) {
443 llvm::SmallVector<NestedNameSpecifier, 16> Specs;
444 for (CXXScopeSpec::iterator Spec = SS->begin(), SpecEnd = SS->end();
445 Spec != SpecEnd; ++Spec)
446 Specs.push_back(NestedNameSpecifier::getFromOpaquePtr(*Spec));
447 return QualifiedDeclRefExpr::Create(Context, D, Ty, Loc, TypeDependent,
448 ValueDependent, SS->getRange(),
449 &Specs[0], Specs.size());
450 } else
Steve Naroff774e4152009-01-21 00:14:39 +0000451 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000452}
453
Douglas Gregor723d3332009-01-07 00:43:41 +0000454/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
455/// variable corresponding to the anonymous union or struct whose type
456/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000457static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000458 assert(Record->isAnonymousStructOrUnion() &&
459 "Record must be an anonymous struct or union!");
460
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000461 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000462 // be an O(1) operation rather than a slow walk through DeclContext's
463 // vector (which itself will be eliminated). DeclGroups might make
464 // this even better.
465 DeclContext *Ctx = Record->getDeclContext();
466 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
467 DEnd = Ctx->decls_end();
468 D != DEnd; ++D) {
469 if (*D == Record) {
470 // The object for the anonymous struct/union directly
471 // follows its type in the list of declarations.
472 ++D;
473 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000474 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000475 return *D;
476 }
477 }
478
479 assert(false && "Missing object for anonymous record");
480 return 0;
481}
482
Sebastian Redlcd883f72009-01-18 18:53:16 +0000483Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000484Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
485 FieldDecl *Field,
486 Expr *BaseObjectExpr,
487 SourceLocation OpLoc) {
488 assert(Field->getDeclContext()->isRecord() &&
489 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
490 && "Field must be stored inside an anonymous struct or union");
491
492 // Construct the sequence of field member references
493 // we'll have to perform to get to the field in the anonymous
494 // union/struct. The list of members is built from the field
495 // outward, so traverse it backwards to go from an object in
496 // the current context to the field we found.
497 llvm::SmallVector<FieldDecl *, 4> AnonFields;
498 AnonFields.push_back(Field);
499 VarDecl *BaseObject = 0;
500 DeclContext *Ctx = Field->getDeclContext();
501 do {
502 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000503 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000504 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
505 AnonFields.push_back(AnonField);
506 else {
507 BaseObject = cast<VarDecl>(AnonObject);
508 break;
509 }
510 Ctx = Ctx->getParent();
511 } while (Ctx->isRecord() &&
512 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
513
514 // Build the expression that refers to the base object, from
515 // which we will build a sequence of member references to each
516 // of the anonymous union objects and, eventually, the field we
517 // found via name lookup.
518 bool BaseObjectIsPointer = false;
519 unsigned ExtraQuals = 0;
520 if (BaseObject) {
521 // BaseObject is an anonymous struct/union variable (and is,
522 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000523 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000524 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000525 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000526 ExtraQuals
527 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
528 } else if (BaseObjectExpr) {
529 // The caller provided the base object expression. Determine
530 // whether its a pointer and whether it adds any qualifiers to the
531 // anonymous struct/union fields we're looking into.
532 QualType ObjectType = BaseObjectExpr->getType();
533 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
534 BaseObjectIsPointer = true;
535 ObjectType = ObjectPtr->getPointeeType();
536 }
537 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
538 } else {
539 // We've found a member of an anonymous struct/union that is
540 // inside a non-anonymous struct/union, so in a well-formed
541 // program our base object expression is "this".
542 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
543 if (!MD->isStatic()) {
544 QualType AnonFieldType
545 = Context.getTagDeclType(
546 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
547 QualType ThisType = Context.getTagDeclType(MD->getParent());
548 if ((Context.getCanonicalType(AnonFieldType)
549 == Context.getCanonicalType(ThisType)) ||
550 IsDerivedFrom(ThisType, AnonFieldType)) {
551 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000552 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000553 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000554 BaseObjectIsPointer = true;
555 }
556 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000557 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
558 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000559 }
560 ExtraQuals = MD->getTypeQualifiers();
561 }
562
563 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000564 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
565 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000566 }
567
568 // Build the implicit member references to the field of the
569 // anonymous struct/union.
570 Expr *Result = BaseObjectExpr;
571 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
572 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
573 FI != FIEnd; ++FI) {
574 QualType MemberType = (*FI)->getType();
575 if (!(*FI)->isMutable()) {
576 unsigned combinedQualifiers
577 = MemberType.getCVRQualifiers() | ExtraQuals;
578 MemberType = MemberType.getQualifiedType(combinedQualifiers);
579 }
Steve Naroff774e4152009-01-21 00:14:39 +0000580 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
581 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000582 BaseObjectIsPointer = false;
583 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000584 }
585
Sebastian Redlcd883f72009-01-18 18:53:16 +0000586 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000587}
588
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000589/// ActOnDeclarationNameExpr - The parser has read some kind of name
590/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
591/// performs lookup on that name and returns an expression that refers
592/// to that name. This routine isn't directly called from the parser,
593/// because the parser doesn't know about DeclarationName. Rather,
594/// this routine is called by ActOnIdentifierExpr,
595/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
596/// which form the DeclarationName from the corresponding syntactic
597/// forms.
598///
599/// HasTrailingLParen indicates whether this identifier is used in a
600/// function call context. LookupCtx is only used for a C++
601/// qualified-id (foo::bar) to indicate the class or namespace that
602/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000603///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000604/// isAddressOfOperand means that this expression is the direct operand
605/// of an address-of operator. This matters because this is the only
606/// situation where a qualified name referencing a non-static member may
607/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000608Sema::OwningExprResult
609Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
610 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000611 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000612 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000613 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000614 if (SS && SS->isInvalid())
615 return ExprError();
Douglas Gregor411889e2009-02-13 23:20:09 +0000616 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
617 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000618
Douglas Gregor09be81b2009-02-04 17:27:36 +0000619 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000620 if (Lookup.isAmbiguous()) {
621 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
622 SS && SS->isSet() ? SS->getRange()
623 : SourceRange());
624 return ExprError();
625 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000626 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000627
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000628 // If this reference is in an Objective-C method, then ivar lookup happens as
629 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000630 IdentifierInfo *II = Name.getAsIdentifierInfo();
631 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000632 // There are two cases to handle here. 1) scoped lookup could have failed,
633 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000634 // found a decl, but that decl is outside the current instance method (i.e.
635 // a global variable). In these two cases, we do a lookup for an ivar with
636 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000637 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000638 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000639 ObjCInterfaceDecl *ClassDeclared;
640 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000641 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000642 if (DiagnoseUseOfDecl(IV, Loc))
643 return ExprError();
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000644 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
645 // If a class method attemps to use a free standing ivar, this is
646 // an error.
647 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
648 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
649 << IV->getDeclName());
650 // If a class method uses a global variable, even if an ivar with
651 // same name exists, use the global.
652 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000653 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
654 ClassDeclared != IFace)
655 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000656 // FIXME: This should use a new expr for a direct reference, don't turn
657 // this into Self->ivar, just return a BareIVarExpr or something.
658 IdentifierInfo &II = Context.Idents.get("self");
659 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
660 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
661 Loc, static_cast<Expr*>(SelfExpr.release()),
662 true, true);
663 Context.setFieldDecl(IFace, IV, MRef);
664 return Owned(MRef);
665 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000666 }
667 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000668 else if (getCurMethodDecl()->isInstanceMethod()) {
669 // We should warn if a local variable hides an ivar.
670 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000671 ObjCInterfaceDecl *ClassDeclared;
672 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
673 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
674 IFace == ClassDeclared)
675 Diag(Loc, diag::warn_ivar_use_hidden)<<IV->getDeclName();
676 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000677 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000678 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000679 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000680 QualType T;
681
682 if (getCurMethodDecl()->isInstanceMethod())
683 T = Context.getPointerType(Context.getObjCInterfaceType(
684 getCurMethodDecl()->getClassInterface()));
685 else
686 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000687 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000688 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000689 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000690
Douglas Gregoraa57e862009-02-18 21:56:37 +0000691 // Determine whether this name might be a candidate for
692 // argument-dependent lookup.
693 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
694 HasTrailingLParen;
695
696 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000697 // We've seen something of the form
698 //
699 // identifier(
700 //
701 // and we did not find any entity by the name
702 // "identifier". However, this identifier is still subject to
703 // argument-dependent lookup, so keep track of the name.
704 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
705 Context.OverloadTy,
706 Loc));
707 }
708
Chris Lattner4b009652007-07-25 00:24:17 +0000709 if (D == 0) {
710 // Otherwise, this could be an implicitly declared function reference (legal
711 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000712 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000713 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000714 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000715 else {
716 // If this name wasn't predeclared and if this is not a function call,
717 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000718 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000719 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
720 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000721 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
722 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000723 return ExprError(Diag(Loc, diag::err_undeclared_use)
724 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000725 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000726 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000727 }
728 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000729
Sebastian Redl0c9da212009-02-03 20:19:35 +0000730 // If this is an expression of the form &Class::member, don't build an
731 // implicit member ref, because we want a pointer to the member in general,
732 // not any specific instance's member.
733 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000734 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000735 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000736 QualType DType;
737 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
738 DType = FD->getType().getNonReferenceType();
739 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
740 DType = Method->getType();
741 } else if (isa<OverloadedFunctionDecl>(D)) {
742 DType = Context.OverloadTy;
743 }
744 // Could be an inner type. That's diagnosed below, so ignore it here.
745 if (!DType.isNull()) {
746 // The pointer is type- and value-dependent if it points into something
747 // dependent.
748 bool Dependent = false;
749 for (; DC; DC = DC->getParent()) {
750 // FIXME: could stop early at namespace scope.
751 if (DC->isRecord()) {
752 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
753 if (Context.getTypeDeclType(Record)->isDependentType()) {
754 Dependent = true;
755 break;
756 }
757 }
758 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000759 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000760 }
761 }
762 }
763
Douglas Gregor723d3332009-01-07 00:43:41 +0000764 // We may have found a field within an anonymous union or struct
765 // (C++ [class.union]).
766 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
767 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
768 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000769
Douglas Gregor3257fb52008-12-22 05:46:06 +0000770 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
771 if (!MD->isStatic()) {
772 // C++ [class.mfct.nonstatic]p2:
773 // [...] if name lookup (3.4.1) resolves the name in the
774 // id-expression to a nonstatic nontype member of class X or of
775 // a base class of X, the id-expression is transformed into a
776 // class member access expression (5.2.5) using (*this) (9.3.2)
777 // as the postfix-expression to the left of the '.' operator.
778 DeclContext *Ctx = 0;
779 QualType MemberType;
780 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
781 Ctx = FD->getDeclContext();
782 MemberType = FD->getType();
783
784 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
785 MemberType = RefType->getPointeeType();
786 else if (!FD->isMutable()) {
787 unsigned combinedQualifiers
788 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
789 MemberType = MemberType.getQualifiedType(combinedQualifiers);
790 }
791 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
792 if (!Method->isStatic()) {
793 Ctx = Method->getParent();
794 MemberType = Method->getType();
795 }
796 } else if (OverloadedFunctionDecl *Ovl
797 = dyn_cast<OverloadedFunctionDecl>(D)) {
798 for (OverloadedFunctionDecl::function_iterator
799 Func = Ovl->function_begin(),
800 FuncEnd = Ovl->function_end();
801 Func != FuncEnd; ++Func) {
802 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
803 if (!DMethod->isStatic()) {
804 Ctx = Ovl->getDeclContext();
805 MemberType = Context.OverloadTy;
806 break;
807 }
808 }
809 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000810
811 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000812 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
813 QualType ThisType = Context.getTagDeclType(MD->getParent());
814 if ((Context.getCanonicalType(CtxType)
815 == Context.getCanonicalType(ThisType)) ||
816 IsDerivedFrom(ThisType, CtxType)) {
817 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000818 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000819 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000820 return Owned(new (Context) MemberExpr(This, true, D,
Mike Stump9afab102009-02-19 03:04:26 +0000821 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000822 }
823 }
824 }
825 }
826
Douglas Gregor8acb7272008-12-11 16:49:14 +0000827 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000828 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
829 if (MD->isStatic())
830 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000831 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
832 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000833 }
834
Douglas Gregor3257fb52008-12-22 05:46:06 +0000835 // Any other ways we could have found the field in a well-formed
836 // program would have been turned into implicit member expressions
837 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000838 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
839 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000840 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000841
Chris Lattner4b009652007-07-25 00:24:17 +0000842 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000843 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000844 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000845 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000846 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000847 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000848
Steve Naroffd6163f32008-09-05 22:11:13 +0000849 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000850 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000851 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
852 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000853 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
854 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
855 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000856 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000857
Douglas Gregoraa57e862009-02-18 21:56:37 +0000858 // Check whether this declaration can be used. Note that we suppress
859 // this check when we're going to perform argument-dependent lookup
860 // on this function name, because this might not be the function
861 // that overload resolution actually selects.
862 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
863 return ExprError();
864
Douglas Gregor48840c72008-12-10 23:01:14 +0000865 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000866 // Warn about constructs like:
867 // if (void *X = foo()) { ... } else { X }.
868 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000869 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
870 Scope *CheckS = S;
871 while (CheckS) {
872 if (CheckS->isWithinElse() &&
873 CheckS->getControlParent()->isDeclScope(Var)) {
874 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000875 ExprError(Diag(Loc, diag::warn_value_always_false)
876 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000877 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000878 ExprError(Diag(Loc, diag::warn_value_always_zero)
879 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000880 break;
881 }
882
883 // Move up one more control parent to check again.
884 CheckS = CheckS->getControlParent();
885 if (CheckS)
886 CheckS = CheckS->getParent();
887 }
888 }
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000889 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
890 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
891 // C99 DR 316 says that, if a function type comes from a
892 // function definition (without a prototype), that type is only
893 // used for checking compatibility. Therefore, when referencing
894 // the function, we pretend that we don't have the full function
895 // type.
896 QualType T = Func->getType();
897 QualType NoProtoType = T;
Douglas Gregor4fa58902009-02-26 23:50:07 +0000898 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
899 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000900 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
901 }
Douglas Gregor48840c72008-12-10 23:01:14 +0000902 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000903
904 // Only create DeclRefExpr's for valid Decl's.
905 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000906 return ExprError();
907
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000908 // If the identifier reference is inside a block, and it refers to a value
909 // that is outside the block, create a BlockDeclRefExpr instead of a
910 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
911 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000912 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000913 // We do not do this for things like enum constants, global variables, etc,
914 // as they do not get snapshotted.
915 //
916 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stumpae93d652009-02-19 22:01:56 +0000917 // Blocks that have these can't be constant.
918 CurBlock->hasBlockDeclRefExprs = true;
919
Steve Naroff52059382008-10-10 01:28:17 +0000920 // The BlocksAttr indicates the variable is bound by-reference.
921 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000922 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000923 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000924
Steve Naroff52059382008-10-10 01:28:17 +0000925 // Variable will be bound by-copy, make it const within the closure.
926 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000927 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000928 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000929 }
930 // If this reference is not in a block or if the referenced variable is
931 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000932
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000933 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000934 bool ValueDependent = false;
935 if (getLangOptions().CPlusPlus) {
936 // C++ [temp.dep.expr]p3:
937 // An id-expression is type-dependent if it contains:
938 // - an identifier that was declared with a dependent type,
939 if (VD->getType()->isDependentType())
940 TypeDependent = true;
941 // - FIXME: a template-id that is dependent,
942 // - a conversion-function-id that specifies a dependent type,
943 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
944 Name.getCXXNameType()->isDependentType())
945 TypeDependent = true;
946 // - a nested-name-specifier that contains a class-name that
947 // names a dependent type.
948 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000949 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +0000950 DC; DC = DC->getParent()) {
951 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000952 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000953 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
954 if (Context.getTypeDeclType(Record)->isDependentType()) {
955 TypeDependent = true;
956 break;
957 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000958 }
959 }
960 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000961
Douglas Gregora5d84612008-12-10 20:57:37 +0000962 // C++ [temp.dep.constexpr]p2:
963 //
964 // An identifier is value-dependent if it is:
965 // - a name declared with a dependent type,
966 if (TypeDependent)
967 ValueDependent = true;
968 // - the name of a non-type template parameter,
969 else if (isa<NonTypeTemplateParmDecl>(VD))
970 ValueDependent = true;
971 // - a constant with integral or enumeration type and is
972 // initialized with an expression that is value-dependent
973 // (FIXME!).
974 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000975
Sebastian Redlcd883f72009-01-18 18:53:16 +0000976 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
977 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000978}
979
Sebastian Redlcd883f72009-01-18 18:53:16 +0000980Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
981 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000982 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000983
Chris Lattner4b009652007-07-25 00:24:17 +0000984 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000985 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000986 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
987 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
988 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000989 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000990
Chris Lattner7e637512008-01-12 08:14:25 +0000991 // Pre-defined identifiers are of type char[x], where x is the length of the
992 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000993 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000994 if (FunctionDecl *FD = getCurFunctionDecl())
995 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000996 else if (ObjCMethodDecl *MD = getCurMethodDecl())
997 Length = MD->getSynthesizedMethodSize();
998 else {
999 Diag(Loc, diag::ext_predef_outside_function);
1000 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1001 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1002 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001003
1004
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001005 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001006 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001007 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001008 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001009}
1010
Sebastian Redlcd883f72009-01-18 18:53:16 +00001011Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001012 llvm::SmallString<16> CharBuffer;
1013 CharBuffer.resize(Tok.getLength());
1014 const char *ThisTokBegin = &CharBuffer[0];
1015 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001016
Chris Lattner4b009652007-07-25 00:24:17 +00001017 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1018 Tok.getLocation(), PP);
1019 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001020 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001021
1022 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1023
Sebastian Redl75324932009-01-20 22:23:13 +00001024 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1025 Literal.isWide(),
1026 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001027}
1028
Sebastian Redlcd883f72009-01-18 18:53:16 +00001029Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1030 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001031 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1032 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001033 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001034 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001035 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001036 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001037 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001038
Chris Lattner4b009652007-07-25 00:24:17 +00001039 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001040 // Add padding so that NumericLiteralParser can overread by one character.
1041 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001042 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001043
Chris Lattner4b009652007-07-25 00:24:17 +00001044 // Get the spelling of the token, which eliminates trigraphs, etc.
1045 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001046
Chris Lattner4b009652007-07-25 00:24:17 +00001047 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1048 Tok.getLocation(), PP);
1049 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001050 return ExprError();
1051
Chris Lattner1de66eb2007-08-26 03:42:43 +00001052 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001053
Chris Lattner1de66eb2007-08-26 03:42:43 +00001054 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001055 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001056 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001057 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001058 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001059 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001060 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001061 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001062
1063 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1064
Ted Kremenekddedbe22007-11-29 00:56:49 +00001065 // isExact will be set by GetFloatValue().
1066 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001067 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1068 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001069
Chris Lattner1de66eb2007-08-26 03:42:43 +00001070 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001071 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001072 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001073 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001074
Neil Booth7421e9c2007-08-29 22:00:19 +00001075 // long long is a C99 feature.
1076 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001077 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001078 Diag(Tok.getLocation(), diag::ext_longlong);
1079
Chris Lattner4b009652007-07-25 00:24:17 +00001080 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001081 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001082
Chris Lattner4b009652007-07-25 00:24:17 +00001083 if (Literal.GetIntegerValue(ResultVal)) {
1084 // If this value didn't fit into uintmax_t, warn and force to ull.
1085 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001086 Ty = Context.UnsignedLongLongTy;
1087 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001088 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001089 } else {
1090 // If this value fits into a ULL, try to figure out what else it fits into
1091 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001092
Chris Lattner4b009652007-07-25 00:24:17 +00001093 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1094 // be an unsigned int.
1095 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1096
1097 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001098 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001099 if (!Literal.isLong && !Literal.isLongLong) {
1100 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001101 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001102
Chris Lattner4b009652007-07-25 00:24:17 +00001103 // Does it fit in a unsigned int?
1104 if (ResultVal.isIntN(IntSize)) {
1105 // Does it fit in a signed int?
1106 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001107 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001108 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001109 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001110 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001111 }
Chris Lattner4b009652007-07-25 00:24:17 +00001112 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001113
Chris Lattner4b009652007-07-25 00:24:17 +00001114 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001115 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001116 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001117
Chris Lattner4b009652007-07-25 00:24:17 +00001118 // Does it fit in a unsigned long?
1119 if (ResultVal.isIntN(LongSize)) {
1120 // Does it fit in a signed long?
1121 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001122 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001123 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001124 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001125 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001126 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001127 }
1128
Chris Lattner4b009652007-07-25 00:24:17 +00001129 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001130 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001131 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001132
Chris Lattner4b009652007-07-25 00:24:17 +00001133 // Does it fit in a unsigned long long?
1134 if (ResultVal.isIntN(LongLongSize)) {
1135 // Does it fit in a signed long long?
1136 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001137 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001138 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001139 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001140 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001141 }
1142 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001143
Chris Lattner4b009652007-07-25 00:24:17 +00001144 // If we still couldn't decide a type, we probably have something that
1145 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001146 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001147 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001148 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001149 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001150 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001151
Chris Lattnere4068872008-05-09 05:59:00 +00001152 if (ResultVal.getBitWidth() != Width)
1153 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001154 }
Sebastian Redl75324932009-01-20 22:23:13 +00001155 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001156 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001157
Chris Lattner1de66eb2007-08-26 03:42:43 +00001158 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1159 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001160 Res = new (Context) ImaginaryLiteral(Res,
1161 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001162
1163 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001164}
1165
Sebastian Redlcd883f72009-01-18 18:53:16 +00001166Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1167 SourceLocation R, ExprArg Val) {
1168 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001169 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001170 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001171}
1172
1173/// The UsualUnaryConversions() function is *not* called by this routine.
1174/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001175bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001176 SourceLocation OpLoc,
1177 const SourceRange &ExprRange,
1178 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001179 if (exprType->isDependentType())
1180 return false;
1181
Chris Lattner4b009652007-07-25 00:24:17 +00001182 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001183 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001184 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001185 if (isSizeof)
1186 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1187 return false;
1188 }
1189
1190 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001191 Diag(OpLoc, diag::ext_sizeof_void_type)
1192 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001193 return false;
1194 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001195
Douglas Gregorc84d8932009-03-09 16:13:40 +00001196 return RequireCompleteType(OpLoc, exprType,
Chris Lattner159fe082009-01-24 19:46:37 +00001197 isSizeof ? diag::err_sizeof_incomplete_type :
1198 diag::err_alignof_incomplete_type,
1199 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001200}
1201
Chris Lattner8d9f7962009-01-24 20:17:12 +00001202bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1203 const SourceRange &ExprRange) {
1204 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001205
Chris Lattner8d9f7962009-01-24 20:17:12 +00001206 // alignof decl is always ok.
1207 if (isa<DeclRefExpr>(E))
1208 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001209
1210 // Cannot know anything else if the expression is dependent.
1211 if (E->isTypeDependent())
1212 return false;
1213
Chris Lattner8d9f7962009-01-24 20:17:12 +00001214 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1215 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1216 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001217 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001218 return true;
1219 }
1220 // Other fields are ok.
1221 return false;
1222 }
1223 }
1224 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1225}
1226
Douglas Gregor396f1142009-03-13 21:01:28 +00001227/// \brief Build a sizeof or alignof expression given a type operand.
1228Action::OwningExprResult
1229Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1230 bool isSizeOf, SourceRange R) {
1231 if (T.isNull())
1232 return ExprError();
1233
1234 if (!T->isDependentType() &&
1235 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1236 return ExprError();
1237
1238 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1239 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1240 Context.getSizeType(), OpLoc,
1241 R.getEnd()));
1242}
1243
1244/// \brief Build a sizeof or alignof expression given an expression
1245/// operand.
1246Action::OwningExprResult
1247Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1248 bool isSizeOf, SourceRange R) {
1249 // Verify that the operand is valid.
1250 bool isInvalid = false;
1251 if (E->isTypeDependent()) {
1252 // Delay type-checking for type-dependent expressions.
1253 } else if (!isSizeOf) {
1254 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1255 } else if (E->isBitField()) { // C99 6.5.3.4p1.
1256 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1257 isInvalid = true;
1258 } else {
1259 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1260 }
1261
1262 if (isInvalid)
1263 return ExprError();
1264
1265 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1266 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1267 Context.getSizeType(), OpLoc,
1268 R.getEnd()));
1269}
1270
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001271/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1272/// the same for @c alignof and @c __alignof
1273/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001274Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001275Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1276 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001277 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001278 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001279
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001280 if (isType) {
Douglas Gregor396f1142009-03-13 21:01:28 +00001281 QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1282 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1283 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001284
Douglas Gregor396f1142009-03-13 21:01:28 +00001285 // Get the end location.
1286 Expr *ArgEx = (Expr *)TyOrEx;
1287 Action::OwningExprResult Result
1288 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1289
1290 if (Result.isInvalid())
1291 DeleteExpr(ArgEx);
1292
1293 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001294}
1295
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001296QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001297 if (V->isTypeDependent())
1298 return Context.DependentTy;
1299
Chris Lattner03931a72007-08-24 21:16:53 +00001300 DefaultFunctionArrayConversion(V);
1301
Chris Lattnera16e42d2007-08-26 05:39:26 +00001302 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001303 if (const ComplexType *CT = V->getType()->getAsComplexType())
1304 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001305
1306 // Otherwise they pass through real integer and floating point types here.
1307 if (V->getType()->isArithmeticType())
1308 return V->getType();
1309
1310 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001311 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1312 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001313 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001314}
1315
1316
Chris Lattner4b009652007-07-25 00:24:17 +00001317
Sebastian Redl8b769972009-01-19 00:08:26 +00001318Action::OwningExprResult
1319Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1320 tok::TokenKind Kind, ExprArg Input) {
1321 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001322
Chris Lattner4b009652007-07-25 00:24:17 +00001323 UnaryOperator::Opcode Opc;
1324 switch (Kind) {
1325 default: assert(0 && "Unknown unary op!");
1326 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1327 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1328 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001329
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001330 if (getLangOptions().CPlusPlus &&
1331 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1332 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001333 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001334 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1335
1336 // C++ [over.inc]p1:
1337 //
1338 // [...] If the function is a member function with one
1339 // parameter (which shall be of type int) or a non-member
1340 // function with two parameters (the second of which shall be
1341 // of type int), it defines the postfix increment operator ++
1342 // for objects of that type. When the postfix increment is
1343 // called as a result of using the ++ operator, the int
1344 // argument will have value zero.
1345 Expr *Args[2] = {
1346 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001347 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1348 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001349 };
1350
1351 // Build the candidate set for overloading
1352 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001353 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001354
1355 // Perform overload resolution.
1356 OverloadCandidateSet::iterator Best;
1357 switch (BestViableFunction(CandidateSet, Best)) {
1358 case OR_Success: {
1359 // We found a built-in operator or an overloaded operator.
1360 FunctionDecl *FnDecl = Best->Function;
1361
1362 if (FnDecl) {
1363 // We matched an overloaded operator. Build a call to that
1364 // operator.
1365
1366 // Convert the arguments.
1367 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1368 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001369 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001370 } else {
1371 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001372 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001373 FnDecl->getParamDecl(0)->getType(),
1374 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001375 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001376 }
1377
1378 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001379 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001380 = FnDecl->getType()->getAsFunctionType()->getResultType();
1381 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001382
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001383 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001384 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001385 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001386 UsualUnaryConversions(FnExpr);
1387
Sebastian Redl8b769972009-01-19 00:08:26 +00001388 Input.release();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001389 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1390 Args, 2, ResultTy,
1391 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001392 } else {
1393 // We matched a built-in operator. Convert the arguments, then
1394 // break out so that we will build the appropriate built-in
1395 // operator node.
1396 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1397 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001398 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001399
1400 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001401 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001402 }
1403
1404 case OR_No_Viable_Function:
1405 // No viable function; fall through to handling this as a
1406 // built-in operator, which will produce an error message for us.
1407 break;
1408
1409 case OR_Ambiguous:
1410 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1411 << UnaryOperator::getOpcodeStr(Opc)
1412 << Arg->getSourceRange();
1413 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001414 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001415
1416 case OR_Deleted:
1417 Diag(OpLoc, diag::err_ovl_deleted_oper)
1418 << Best->Function->isDeleted()
1419 << UnaryOperator::getOpcodeStr(Opc)
1420 << Arg->getSourceRange();
1421 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1422 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001423 }
1424
1425 // Either we found no viable overloaded operator or we matched a
1426 // built-in operator. In either case, fall through to trying to
1427 // build a built-in operation.
1428 }
1429
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001430 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1431 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001432 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001433 return ExprError();
1434 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001435 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001436}
1437
Sebastian Redl8b769972009-01-19 00:08:26 +00001438Action::OwningExprResult
1439Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1440 ExprArg Idx, SourceLocation RLoc) {
1441 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1442 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001443
Douglas Gregor80723c52008-11-19 17:17:41 +00001444 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001445 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001446 LHSExp->getType()->isEnumeralType() ||
1447 RHSExp->getType()->isRecordType() ||
1448 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001449 // Add the appropriate overloaded operators (C++ [over.match.oper])
1450 // to the candidate set.
1451 OverloadCandidateSet CandidateSet;
1452 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001453 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1454 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001455
Douglas Gregor80723c52008-11-19 17:17:41 +00001456 // Perform overload resolution.
1457 OverloadCandidateSet::iterator Best;
1458 switch (BestViableFunction(CandidateSet, Best)) {
1459 case OR_Success: {
1460 // We found a built-in operator or an overloaded operator.
1461 FunctionDecl *FnDecl = Best->Function;
1462
1463 if (FnDecl) {
1464 // We matched an overloaded operator. Build a call to that
1465 // operator.
1466
1467 // Convert the arguments.
1468 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1469 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1470 PerformCopyInitialization(RHSExp,
1471 FnDecl->getParamDecl(0)->getType(),
1472 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001473 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001474 } else {
1475 // Convert the arguments.
1476 if (PerformCopyInitialization(LHSExp,
1477 FnDecl->getParamDecl(0)->getType(),
1478 "passing") ||
1479 PerformCopyInitialization(RHSExp,
1480 FnDecl->getParamDecl(1)->getType(),
1481 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001482 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001483 }
1484
1485 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001486 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001487 = FnDecl->getType()->getAsFunctionType()->getResultType();
1488 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001489
Douglas Gregor80723c52008-11-19 17:17:41 +00001490 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001491 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1492 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001493 UsualUnaryConversions(FnExpr);
1494
Sebastian Redl8b769972009-01-19 00:08:26 +00001495 Base.release();
1496 Idx.release();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001497 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1498 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001499 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001500 } else {
1501 // We matched a built-in operator. Convert the arguments, then
1502 // break out so that we will build the appropriate built-in
1503 // operator node.
1504 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1505 "passing") ||
1506 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1507 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001508 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001509
1510 break;
1511 }
1512 }
1513
1514 case OR_No_Viable_Function:
1515 // No viable function; fall through to handling this as a
1516 // built-in operator, which will produce an error message for us.
1517 break;
1518
1519 case OR_Ambiguous:
1520 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1521 << "[]"
1522 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1523 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001524 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001525
1526 case OR_Deleted:
1527 Diag(LLoc, diag::err_ovl_deleted_oper)
1528 << Best->Function->isDeleted()
1529 << "[]"
1530 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1531 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1532 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001533 }
1534
1535 // Either we found no viable overloaded operator or we matched a
1536 // built-in operator. In either case, fall through to trying to
1537 // build a built-in operation.
1538 }
1539
Chris Lattner4b009652007-07-25 00:24:17 +00001540 // Perform default conversions.
1541 DefaultFunctionArrayConversion(LHSExp);
1542 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001543
Chris Lattner4b009652007-07-25 00:24:17 +00001544 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1545
1546 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001547 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001548 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001549 // and index from the expression types.
1550 Expr *BaseExpr, *IndexExpr;
1551 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001552 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1553 BaseExpr = LHSExp;
1554 IndexExpr = RHSExp;
1555 ResultType = Context.DependentTy;
1556 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001557 BaseExpr = LHSExp;
1558 IndexExpr = RHSExp;
1559 // FIXME: need to deal with const...
1560 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001561 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001562 // Handle the uncommon case of "123[Ptr]".
1563 BaseExpr = RHSExp;
1564 IndexExpr = LHSExp;
1565 // FIXME: need to deal with const...
1566 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001567 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1568 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001569 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001570
Chris Lattner4b009652007-07-25 00:24:17 +00001571 // FIXME: need to deal with const...
1572 ResultType = VTy->getElementType();
1573 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001574 return ExprError(Diag(LHSExp->getLocStart(),
1575 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1576 }
Chris Lattner4b009652007-07-25 00:24:17 +00001577 // C99 6.5.2.1p1
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001578 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Sebastian Redl8b769972009-01-19 00:08:26 +00001579 return ExprError(Diag(IndexExpr->getLocStart(),
1580 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001581
1582 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1583 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001584 // void (*)(int)) and pointers to incomplete types. Functions are not
1585 // objects in C99.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001586 if (!ResultType->isObjectType() && !ResultType->isDependentType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001587 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001588 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001589 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001590
Sebastian Redl8b769972009-01-19 00:08:26 +00001591 Base.release();
1592 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001593 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001594 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001595}
1596
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001597QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001598CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001599 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001600 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001601
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001602 // The vector accessor can't exceed the number of elements.
1603 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001604
Mike Stump9afab102009-02-19 03:04:26 +00001605 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001606 // special names that indicate a subset of exactly half the elements are
1607 // to be selected.
1608 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001609
Nate Begeman1486b502009-01-18 01:47:54 +00001610 // This flag determines whether or not CompName has an 's' char prefix,
1611 // indicating that it is a string of hex values to be used as vector indices.
1612 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001613
1614 // Check that we've found one of the special components, or that the component
1615 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001616 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001617 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1618 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001619 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001620 do
1621 compStr++;
1622 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001623 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001624 do
1625 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001626 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001627 }
Nate Begeman1486b502009-01-18 01:47:54 +00001628
Mike Stump9afab102009-02-19 03:04:26 +00001629 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001630 // We didn't get to the end of the string. This means the component names
1631 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001632 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1633 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001634 return QualType();
1635 }
Mike Stump9afab102009-02-19 03:04:26 +00001636
Nate Begeman1486b502009-01-18 01:47:54 +00001637 // Ensure no component accessor exceeds the width of the vector type it
1638 // operates on.
1639 if (!HalvingSwizzle) {
1640 compStr = CompName.getName();
1641
1642 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001643 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001644
1645 while (*compStr) {
1646 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1647 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1648 << baseType << SourceRange(CompLoc);
1649 return QualType();
1650 }
1651 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001652 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001653
Nate Begeman1486b502009-01-18 01:47:54 +00001654 // If this is a halving swizzle, verify that the base type has an even
1655 // number of elements.
1656 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001657 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001658 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001659 return QualType();
1660 }
Mike Stump9afab102009-02-19 03:04:26 +00001661
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001662 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001663 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001664 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001665 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001666 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001667 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1668 : CompName.getLength();
1669 if (HexSwizzle)
1670 CompSize--;
1671
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001672 if (CompSize == 1)
1673 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001674
Nate Begemanaf6ed502008-04-18 23:10:10 +00001675 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001676 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001677 // diagostics look bad. We want extended vector types to appear built-in.
1678 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1679 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1680 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001681 }
1682 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001683}
1684
Chris Lattner2cb744b2009-02-15 22:43:40 +00001685
Sebastian Redl8b769972009-01-19 00:08:26 +00001686Action::OwningExprResult
1687Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1688 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001689 IdentifierInfo &Member,
1690 DeclTy *ObjCImpDecl) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001691 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001692 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001693
1694 // Perform default conversions.
1695 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001696
Steve Naroff2cb66382007-07-26 03:11:44 +00001697 QualType BaseType = BaseExpr->getType();
1698 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001699
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001700 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1701 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001702 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001703 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001704 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001705 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001706 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1707 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001708 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001709 return ExprError(Diag(MemberLoc,
1710 diag::err_typecheck_member_reference_arrow)
1711 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001712 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001713
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001714 // Handle field access to simple records. This also handles access to fields
1715 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001716 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001717 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00001718 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001719 diag::err_typecheck_incomplete_tag,
1720 BaseExpr->getSourceRange()))
1721 return ExprError();
1722
Steve Naroff2cb66382007-07-26 03:11:44 +00001723 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001724 // FIXME: Qualified name lookup for C++ is a bit more complicated
1725 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001726 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00001727 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001728 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001729
Douglas Gregor09be81b2009-02-04 17:27:36 +00001730 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001731 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001732 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1733 << &Member << BaseExpr->getSourceRange());
1734 else if (Result.isAmbiguous()) {
1735 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1736 MemberLoc, BaseExpr->getSourceRange());
1737 return ExprError();
1738 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001739 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001740
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001741 // If the decl being referenced had an error, return an error for this
1742 // sub-expr without emitting another error, in order to avoid cascading
1743 // error cases.
1744 if (MemberDecl->isInvalidDecl())
1745 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001746
Douglas Gregoraa57e862009-02-18 21:56:37 +00001747 // Check the use of this field
1748 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1749 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001750
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001751 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001752 // We may have found a field within an anonymous union or struct
1753 // (C++ [class.union]).
1754 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001755 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001756 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001757
Douglas Gregor82d44772008-12-20 23:49:58 +00001758 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1759 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001760 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001761 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1762 MemberType = Ref->getPointeeType();
1763 else {
1764 unsigned combinedQualifiers =
1765 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001766 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001767 combinedQualifiers &= ~QualType::Const;
1768 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1769 }
Eli Friedman76b49832008-02-06 22:48:16 +00001770
Steve Naroff774e4152009-01-21 00:14:39 +00001771 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1772 MemberLoc, MemberType));
Douglas Gregor00660582009-03-11 20:22:50 +00001773 } else if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001774 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001775 Var, MemberLoc,
1776 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001777 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001778 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Steve Naroff774e4152009-01-21 00:14:39 +00001779 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001780 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001781 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001782 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001783 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001784 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001785 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1786 Enum, MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001787 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001788 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1789 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001790
Douglas Gregor82d44772008-12-20 23:49:58 +00001791 // We found a declaration kind that we didn't expect. This is a
1792 // generic error message that tells the user that she can't refer
1793 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001794 return ExprError(Diag(MemberLoc,
1795 diag::err_typecheck_member_reference_unknown)
1796 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001797 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001798
Chris Lattnere9d71612008-07-21 04:59:05 +00001799 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1800 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001801 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001802 ObjCInterfaceDecl *ClassDeclared;
1803 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member,
1804 ClassDeclared)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001805 // If the decl being referenced had an error, return an error for this
1806 // sub-expr without emitting another error, in order to avoid cascading
1807 // error cases.
1808 if (IV->isInvalidDecl())
1809 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001810
1811 // Check whether we can reference this field.
1812 if (DiagnoseUseOfDecl(IV, MemberLoc))
1813 return ExprError();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001814 if (IV->getAccessControl() != ObjCIvarDecl::Public) {
1815 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1816 if (ObjCMethodDecl *MD = getCurMethodDecl())
1817 ClassOfMethodDecl = MD->getClassInterface();
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001818 else if (ObjCImpDecl && getCurFunctionDecl()) {
1819 // Case of a c-function declared inside an objc implementation.
1820 // FIXME: For a c-style function nested inside an objc implementation
1821 // class, there is no implementation context available, so we pass down
1822 // the context as argument to this routine. Ideally, this context need
1823 // be passed down in the AST node and somehow calculated from the AST
1824 // for a function decl.
1825 Decl *ImplDecl = static_cast<Decl *>(ObjCImpDecl);
1826 if (ObjCImplementationDecl *IMPD =
1827 dyn_cast<ObjCImplementationDecl>(ImplDecl))
1828 ClassOfMethodDecl = IMPD->getClassInterface();
1829 else if (ObjCCategoryImplDecl* CatImplClass =
1830 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
1831 ClassOfMethodDecl = CatImplClass->getClassInterface();
Steve Narofff9606572009-03-04 18:34:24 +00001832 }
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001833 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001834 if (ClassDeclared != IFTy->getDecl() ||
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001835 ClassOfMethodDecl != ClassDeclared)
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001836 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
1837 }
1838 // @protected
1839 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
1840 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
1841 }
Mike Stump9afab102009-02-19 03:04:26 +00001842
1843 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001844 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001845 OpKind == tok::arrow);
1846 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001847 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001848 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001849 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1850 << IFTy->getDecl()->getDeclName() << &Member
1851 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001852 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001853
Chris Lattnere9d71612008-07-21 04:59:05 +00001854 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1855 // pointer to a (potentially qualified) interface type.
1856 const PointerType *PTy;
1857 const ObjCInterfaceType *IFTy;
1858 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1859 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1860 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001861
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001862 // Search for a declared property first.
Chris Lattner51f6fb32009-02-16 18:35:08 +00001863 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001864 // Check whether we can reference this property.
1865 if (DiagnoseUseOfDecl(PD, MemberLoc))
1866 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001867
Steve Naroff774e4152009-01-21 00:14:39 +00001868 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001869 MemberLoc, BaseExpr));
1870 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001871
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001872 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001873 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1874 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner51f6fb32009-02-16 18:35:08 +00001875 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001876 // Check whether we can reference this property.
1877 if (DiagnoseUseOfDecl(PD, MemberLoc))
1878 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001879
Steve Naroff774e4152009-01-21 00:14:39 +00001880 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001881 MemberLoc, BaseExpr));
1882 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001883
1884 // If that failed, look for an "implicit" property by seeing if the nullary
1885 // selector is implemented.
1886
1887 // FIXME: The logic for looking up nullary and unary selectors should be
1888 // shared with the code in ActOnInstanceMessage.
1889
1890 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1891 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001892
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001893 // If this reference is in an @implementation, check for 'private' methods.
1894 if (!Getter)
Steve Naroffd6bceef2009-03-11 15:15:01 +00001895 if (ObjCImplementationDecl *ImpDecl =
1896 ObjCImplementations[IFace->getIdentifier()])
1897 Getter = ImpDecl->getInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001898
Steve Naroff04151f32008-10-22 19:16:27 +00001899 // Look through local category implementations associated with the class.
1900 if (!Getter) {
1901 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1902 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1903 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1904 }
1905 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001906 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001907 // Check if we can reference this property.
1908 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1909 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00001910 }
1911 // If we found a getter then this may be a valid dot-reference, we
1912 // will look for the matching setter, in case it is needed.
1913 Selector SetterSel =
1914 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1915 PP.getSelectorTable(), &Member);
1916 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1917 if (!Setter) {
1918 // If this reference is in an @implementation, also check for 'private'
1919 // methods.
Steve Naroffd6bceef2009-03-11 15:15:01 +00001920 if (ObjCImplementationDecl *ImpDecl =
1921 ObjCImplementations[IFace->getIdentifier()])
1922 Setter = ImpDecl->getInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00001923 }
1924 // Look through local category implementations associated with the class.
1925 if (!Setter) {
1926 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1927 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1928 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001929 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001930 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001931
Steve Naroffdede0c92009-03-11 13:48:17 +00001932 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1933 return ExprError();
1934
1935 if (Getter || Setter) {
1936 QualType PType;
1937
1938 if (Getter)
1939 PType = Getter->getResultType();
1940 else {
1941 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
1942 E = Setter->param_end(); PI != E; ++PI)
1943 PType = (*PI)->getType();
1944 }
1945 // FIXME: we must check that the setter has property type.
1946 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
1947 Setter, MemberLoc, BaseExpr));
1948 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001949 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1950 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001951 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001952 // Handle properties on qualified "id" protocols.
1953 const ObjCQualifiedIdType *QIdTy;
1954 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1955 // Check protocols on qualified interfaces.
1956 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001957 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001958 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001959 // Check the use of this declaration
1960 if (DiagnoseUseOfDecl(PD, MemberLoc))
1961 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001962
Steve Naroff774e4152009-01-21 00:14:39 +00001963 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001964 MemberLoc, BaseExpr));
1965 }
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001966 // Also must look for a getter name which uses property syntax.
1967 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1968 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001969 // Check the use of this method.
1970 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1971 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001972
1973 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Steve Naroff774e4152009-01-21 00:14:39 +00001974 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001975 }
1976 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001977
1978 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1979 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00001980 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00001981 // Handle properties on ObjC 'Class' types.
1982 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) {
1983 // Also must look for a getter name which uses property syntax.
1984 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1985 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Steve Naroff6f9e59f2009-03-11 20:12:18 +00001986 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1987 ObjCMethodDecl *Getter;
Steve Naroffe3aa06f2009-03-05 20:12:00 +00001988 // FIXME: need to also look locally in the implementation.
Steve Naroff6f9e59f2009-03-11 20:12:18 +00001989 if ((Getter = IFace->lookupClassMethod(Sel))) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +00001990 // Check the use of this method.
Steve Naroff6f9e59f2009-03-11 20:12:18 +00001991 if (DiagnoseUseOfDecl(Getter, MemberLoc))
Steve Naroffe3aa06f2009-03-05 20:12:00 +00001992 return ExprError();
Steve Naroffe3aa06f2009-03-05 20:12:00 +00001993 }
Steve Naroff6f9e59f2009-03-11 20:12:18 +00001994 // If we found a getter then this may be a valid dot-reference, we
1995 // will look for the matching setter, in case it is needed.
1996 Selector SetterSel =
1997 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1998 PP.getSelectorTable(), &Member);
1999 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2000 if (!Setter) {
2001 // If this reference is in an @implementation, also check for 'private'
2002 // methods.
2003 if (ObjCImplementationDecl *ImpDecl =
2004 ObjCImplementations[IFace->getIdentifier()])
2005 Setter = ImpDecl->getInstanceMethod(SetterSel);
2006 }
2007 // Look through local category implementations associated with the class.
2008 if (!Setter) {
2009 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2010 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
2011 Setter = ObjCCategoryImpls[i]->getClassMethod(SetterSel);
2012 }
2013 }
2014
2015 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2016 return ExprError();
2017
2018 if (Getter || Setter) {
2019 QualType PType;
2020
2021 if (Getter)
2022 PType = Getter->getResultType();
2023 else {
2024 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2025 E = Setter->param_end(); PI != E; ++PI)
2026 PType = (*PI)->getType();
2027 }
2028 // FIXME: we must check that the setter has property type.
2029 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2030 Setter, MemberLoc, BaseExpr));
2031 }
2032 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2033 << &Member << BaseType);
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002034 }
2035 }
2036
Chris Lattnera57cf472008-07-21 04:28:12 +00002037 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002038 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00002039 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2040 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002041 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002042 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002043 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002044 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002045
2046 return ExprError(Diag(MemberLoc,
2047 diag::err_typecheck_member_reference_struct_union)
2048 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002049}
2050
Douglas Gregor3257fb52008-12-22 05:46:06 +00002051/// ConvertArgumentsForCall - Converts the arguments specified in
2052/// Args/NumArgs to the parameter types of the function FDecl with
2053/// function prototype Proto. Call is the call expression itself, and
2054/// Fn is the function expression. For a C++ member function, this
2055/// routine does not attempt to convert the object argument. Returns
2056/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002057bool
2058Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002059 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002060 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002061 Expr **Args, unsigned NumArgs,
2062 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002063 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002064 // assignment, to the types of the corresponding parameter, ...
2065 unsigned NumArgsInProto = Proto->getNumArgs();
2066 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002067 bool Invalid = false;
2068
Douglas Gregor3257fb52008-12-22 05:46:06 +00002069 // If too few arguments are available (and we don't have default
2070 // arguments for the remaining parameters), don't make the call.
2071 if (NumArgs < NumArgsInProto) {
2072 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2073 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2074 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2075 // Use default arguments for missing arguments
2076 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002077 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002078 }
2079
2080 // If too many are passed and not variadic, error on the extras and drop
2081 // them.
2082 if (NumArgs > NumArgsInProto) {
2083 if (!Proto->isVariadic()) {
2084 Diag(Args[NumArgsInProto]->getLocStart(),
2085 diag::err_typecheck_call_too_many_args)
2086 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2087 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2088 Args[NumArgs-1]->getLocEnd());
2089 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002090 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002091 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002092 }
2093 NumArgsToCheck = NumArgsInProto;
2094 }
Mike Stump9afab102009-02-19 03:04:26 +00002095
Douglas Gregor3257fb52008-12-22 05:46:06 +00002096 // Continue to check argument types (even if we have too few/many args).
2097 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2098 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002099
Douglas Gregor3257fb52008-12-22 05:46:06 +00002100 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002101 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002102 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002103
2104 // Pass the argument.
2105 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2106 return true;
Mike Stump9afab102009-02-19 03:04:26 +00002107 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002108 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00002109 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002110 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002111
Douglas Gregor3257fb52008-12-22 05:46:06 +00002112 Call->setArg(i, Arg);
2113 }
Mike Stump9afab102009-02-19 03:04:26 +00002114
Douglas Gregor3257fb52008-12-22 05:46:06 +00002115 // If this is a variadic call, handle args passed through "...".
2116 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002117 VariadicCallType CallType = VariadicFunction;
2118 if (Fn->getType()->isBlockPointerType())
2119 CallType = VariadicBlock; // Block
2120 else if (isa<MemberExpr>(Fn))
2121 CallType = VariadicMethod;
2122
Douglas Gregor3257fb52008-12-22 05:46:06 +00002123 // Promote the arguments (C99 6.5.2.2p7).
2124 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2125 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002126 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002127 Call->setArg(i, Arg);
2128 }
2129 }
2130
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002131 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002132}
2133
Steve Naroff87d58b42007-09-16 03:34:24 +00002134/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002135/// This provides the location of the left/right parens and a list of comma
2136/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002137Action::OwningExprResult
2138Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2139 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002140 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002141 unsigned NumArgs = args.size();
2142 Expr *Fn = static_cast<Expr *>(fn.release());
2143 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002144 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002145 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002146 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002147
Douglas Gregor3257fb52008-12-22 05:46:06 +00002148 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002149 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002150 // in which case we won't do any semantic analysis now.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002151 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2152 bool Dependent = false;
2153 if (Fn->isTypeDependent())
2154 Dependent = true;
2155 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2156 Dependent = true;
2157
2158 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002159 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002160 Context.DependentTy, RParenLoc));
2161
2162 // Determine whether this is a call to an object (C++ [over.call.object]).
2163 if (Fn->getType()->isRecordType())
2164 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2165 CommaLocs, RParenLoc));
2166
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002167 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002168 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2169 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2170 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002171 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2172 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002173 }
2174
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002175 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002176 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002177 Expr *FnExpr = Fn;
2178 bool ADL = true;
2179 while (true) {
2180 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2181 FnExpr = IcExpr->getSubExpr();
2182 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002183 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002184 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002185 ADL = false;
2186 FnExpr = PExpr->getSubExpr();
2187 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002188 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002189 == UnaryOperator::AddrOf) {
2190 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002191 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2192 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2193 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2194 break;
Mike Stump9afab102009-02-19 03:04:26 +00002195 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002196 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2197 UnqualifiedName = DepName->getName();
2198 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002199 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002200 // Any kind of name that does not refer to a declaration (or
2201 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2202 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002203 break;
2204 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002205 }
Mike Stump9afab102009-02-19 03:04:26 +00002206
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002207 OverloadedFunctionDecl *Ovl = 0;
2208 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002209 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002210 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2211 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002212
Douglas Gregorfcb19192009-02-11 23:02:49 +00002213 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002214 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002215 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002216 ADL = false;
2217
Douglas Gregorfcb19192009-02-11 23:02:49 +00002218 // We don't perform ADL in C.
2219 if (!getLangOptions().CPlusPlus)
2220 ADL = false;
2221
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002222 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002223 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2224 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002225 NumArgs, CommaLocs, RParenLoc, ADL);
2226 if (!FDecl)
2227 return ExprError();
2228
2229 // Update Fn to refer to the actual function selected.
2230 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002231 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002232 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregor7e508262009-03-19 03:51:16 +00002233 NewFn = QualifiedDeclRefExpr::Create(Context, FDecl, FDecl->getType(),
2234 QDRExpr->getLocation(),
2235 false, false,
2236 QDRExpr->getQualifierRange(),
2237 QDRExpr->begin(),
2238 QDRExpr->size());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002239 else
Mike Stump9afab102009-02-19 03:04:26 +00002240 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002241 Fn->getSourceRange().getBegin());
2242 Fn->Destroy(Context);
2243 Fn = NewFn;
2244 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002245 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002246
2247 // Promote the function operand.
2248 UsualUnaryConversions(Fn);
2249
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002250 // Make the call expr early, before semantic checks. This guarantees cleanup
2251 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002252 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2253 Args, NumArgs,
2254 Context.BoolTy,
2255 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002256
Steve Naroffd6163f32008-09-05 22:11:13 +00002257 const FunctionType *FuncT;
2258 if (!Fn->getType()->isBlockPointerType()) {
2259 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2260 // have type pointer to function".
2261 const PointerType *PT = Fn->getType()->getAsPointerType();
2262 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002263 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2264 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002265 FuncT = PT->getPointeeType()->getAsFunctionType();
2266 } else { // This is a block call.
2267 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2268 getAsFunctionType();
2269 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002270 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002271 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2272 << Fn->getType() << Fn->getSourceRange());
2273
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002274 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002275 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002276
Douglas Gregor4fa58902009-02-26 23:50:07 +00002277 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002278 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002279 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002280 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002281 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002282 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002283
Steve Naroffdb65e052007-08-28 23:30:39 +00002284 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002285 for (unsigned i = 0; i != NumArgs; i++) {
2286 Expr *Arg = Args[i];
2287 DefaultArgumentPromotion(Arg);
2288 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002289 }
Chris Lattner4b009652007-07-25 00:24:17 +00002290 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002291
Douglas Gregor3257fb52008-12-22 05:46:06 +00002292 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2293 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002294 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2295 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002296
Chris Lattner2e64c072007-08-10 20:18:51 +00002297 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002298 if (FDecl)
2299 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002300
Sebastian Redl8b769972009-01-19 00:08:26 +00002301 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002302}
2303
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002304Action::OwningExprResult
2305Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2306 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002307 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002308 QualType literalType = QualType::getFromOpaquePtr(Ty);
2309 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002310 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002311 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002312
Eli Friedman8c2173d2008-05-20 05:22:08 +00002313 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002314 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002315 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2316 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregorc84d8932009-03-09 16:13:40 +00002317 } else if (RequireCompleteType(LParenLoc, literalType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002318 diag::err_typecheck_decl_incomplete_type,
2319 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002320 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002321
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002322 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002323 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002324 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002325
Chris Lattnere5cb5862008-12-04 23:50:19 +00002326 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002327 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002328 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002329 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002330 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002331 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002332 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002333 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002334}
2335
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002336Action::OwningExprResult
2337Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2338 InitListDesignations &Designators,
2339 SourceLocation RBraceLoc) {
2340 unsigned NumInit = initlist.size();
2341 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002342
Steve Naroff0acc9c92007-09-15 18:49:24 +00002343 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002344 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002345
Mike Stump9afab102009-02-19 03:04:26 +00002346 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002347 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002348 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002349 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002350}
2351
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002352/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002353bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002354 UsualUnaryConversions(castExpr);
2355
2356 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2357 // type needs to be scalar.
2358 if (castType->isVoidType()) {
2359 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002360 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2361 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002362 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002363 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2364 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2365 (castType->isStructureType() || castType->isUnionType())) {
2366 // GCC struct/union extension: allow cast to self.
2367 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2368 << castType << castExpr->getSourceRange();
2369 } else if (castType->isUnionType()) {
2370 // GCC cast to union extension
2371 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2372 RecordDecl::field_iterator Field, FieldEnd;
2373 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2374 Field != FieldEnd; ++Field) {
2375 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2376 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2377 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2378 << castExpr->getSourceRange();
2379 break;
2380 }
2381 }
2382 if (Field == FieldEnd)
2383 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2384 << castExpr->getType() << castExpr->getSourceRange();
2385 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002386 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002387 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002388 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002389 }
Mike Stump9afab102009-02-19 03:04:26 +00002390 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002391 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002392 return Diag(castExpr->getLocStart(),
2393 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002394 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002395 } else if (castExpr->getType()->isVectorType()) {
2396 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2397 return true;
2398 } else if (castType->isVectorType()) {
2399 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2400 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00002401 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Chris Lattner2e9eb042009-03-05 23:09:00 +00002402 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002403 }
2404 return false;
2405}
2406
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002407bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002408 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002409
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002410 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002411 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002412 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002413 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002414 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002415 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002416 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002417 } else
2418 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002419 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002420 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002421
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002422 return false;
2423}
2424
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002425Action::OwningExprResult
2426Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2427 SourceLocation RParenLoc, ExprArg Op) {
2428 assert((Ty != 0) && (Op.get() != 0) &&
2429 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002430
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002431 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002432 QualType castType = QualType::getFromOpaquePtr(Ty);
2433
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002434 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002435 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002436 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002437 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002438}
2439
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00002440/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2441/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002442/// C99 6.5.15
2443QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2444 SourceLocation QuestionLoc) {
Chris Lattnere2897262009-02-18 04:28:32 +00002445 UsualUnaryConversions(Cond);
2446 UsualUnaryConversions(LHS);
2447 UsualUnaryConversions(RHS);
2448 QualType CondTy = Cond->getType();
2449 QualType LHSTy = LHS->getType();
2450 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002451
2452 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002453 if (!Cond->isTypeDependent()) {
2454 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2455 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2456 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002457 return QualType();
2458 }
Chris Lattner4b009652007-07-25 00:24:17 +00002459 }
Mike Stump9afab102009-02-19 03:04:26 +00002460
Chris Lattner992ae932008-01-06 22:42:25 +00002461 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002462 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002463 return Context.DependentTy;
2464
Chris Lattner992ae932008-01-06 22:42:25 +00002465 // If both operands have arithmetic type, do the usual arithmetic conversions
2466 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002467 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2468 UsualArithmeticConversions(LHS, RHS);
2469 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002470 }
Mike Stump9afab102009-02-19 03:04:26 +00002471
Chris Lattner992ae932008-01-06 22:42:25 +00002472 // If both operands are the same structure or union type, the result is that
2473 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002474 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2475 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002476 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002477 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002478 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002479 return LHSTy.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002480 }
Mike Stump9afab102009-02-19 03:04:26 +00002481
Chris Lattner992ae932008-01-06 22:42:25 +00002482 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002483 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002484 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2485 if (!LHSTy->isVoidType())
2486 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2487 << RHS->getSourceRange();
2488 if (!RHSTy->isVoidType())
2489 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2490 << LHS->getSourceRange();
2491 ImpCastExprToType(LHS, Context.VoidTy);
2492 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002493 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002494 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002495 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2496 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002497 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2498 Context.isObjCObjectPointerType(LHSTy)) &&
2499 RHS->isNullPointerConstant(Context)) {
2500 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2501 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002502 }
Chris Lattnere2897262009-02-18 04:28:32 +00002503 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2504 Context.isObjCObjectPointerType(RHSTy)) &&
2505 LHS->isNullPointerConstant(Context)) {
2506 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2507 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002508 }
Mike Stump9afab102009-02-19 03:04:26 +00002509
Chris Lattner0ac51632008-01-06 22:50:31 +00002510 // Handle the case where both operands are pointers before we handle null
2511 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002512 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2513 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002514 // get the "pointed to" types
2515 QualType lhptee = LHSPT->getPointeeType();
2516 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002517
Chris Lattner71225142007-07-31 21:27:01 +00002518 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2519 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002520 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002521 // Figure out necessary qualifiers (C99 6.5.15p6)
2522 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002523 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002524 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2525 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002526 return destType;
2527 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002528 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002529 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002530 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002531 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2532 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002533 return destType;
2534 }
Chris Lattner4b009652007-07-25 00:24:17 +00002535
Chris Lattner9c039b52009-02-18 04:38:20 +00002536 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattner676c86a2009-02-19 04:44:58 +00002537 // Two identical pointer types are always compatible.
Chris Lattner9c039b52009-02-18 04:38:20 +00002538 return LHSTy;
2539 }
Mike Stump9afab102009-02-19 03:04:26 +00002540
Chris Lattnere2897262009-02-18 04:28:32 +00002541 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002542
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002543 // If either type is an Objective-C object type then check
2544 // compatibility according to Objective-C.
Mike Stump9afab102009-02-19 03:04:26 +00002545 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnere2897262009-02-18 04:28:32 +00002546 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002547 // If both operands are interfaces and either operand can be
2548 // assigned to the other, use that type as the composite
2549 // type. This allows
2550 // xxx ? (A*) a : (B*) b
2551 // where B is a subclass of A.
2552 //
2553 // Additionally, as for assignment, if either type is 'id'
2554 // allow silent coercion. Finally, if the types are
2555 // incompatible then make sure to use 'id' as the composite
2556 // type so the result is acceptable for sending messages to.
2557
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002558 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stump9afab102009-02-19 03:04:26 +00002559 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002560 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2561 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2562 if (LHSIface && RHSIface &&
2563 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002564 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002565 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002566 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002567 compositeType = RHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002568 } else if (Context.isObjCIdStructType(lhptee) ||
2569 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002570 compositeType = Context.getObjCIdType();
2571 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002572 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stump9afab102009-02-19 03:04:26 +00002573 << LHSTy << RHSTy
Chris Lattnere2897262009-02-18 04:28:32 +00002574 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002575 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002576 ImpCastExprToType(LHS, incompatTy);
2577 ImpCastExprToType(RHS, incompatTy);
Mike Stump9afab102009-02-19 03:04:26 +00002578 return incompatTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002579 }
Mike Stump9afab102009-02-19 03:04:26 +00002580 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002581 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002582 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2583 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002584 // In this situation, we assume void* type. No especially good
2585 // reason, but this is what gcc does, and we do have to pick
2586 // to get a consistent AST.
2587 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002588 ImpCastExprToType(LHS, incompatTy);
2589 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002590 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002591 }
2592 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002593 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2594 // differently qualified versions of compatible types, the result type is
2595 // a pointer to an appropriately qualified version of the *composite*
2596 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002597 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002598 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002599 ImpCastExprToType(LHS, compositeType);
2600 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002601 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002602 }
Chris Lattner4b009652007-07-25 00:24:17 +00002603 }
Mike Stump9afab102009-02-19 03:04:26 +00002604
Chris Lattner9c039b52009-02-18 04:38:20 +00002605 // Selection between block pointer types is ok as long as they are the same.
2606 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2607 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2608 return LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002609
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002610 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2611 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00002612 // id with statically typed objects).
2613 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002614 // GCC allows qualified id and any Objective-C type to devolve to
2615 // id. Currently localizing to here until clear this should be
2616 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002617 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00002618 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00002619 Context.isObjCObjectPointerType(RHSTy)) ||
2620 (RHSTy->isObjCQualifiedIdType() &&
2621 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002622 // FIXME: This is not the correct composite type. This only
2623 // happens to work because id can more or less be used anywhere,
2624 // however this may change the type of method sends.
2625 // FIXME: gcc adds some type-checking of the arguments and emits
2626 // (confusing) incompatible comparison warnings in some
2627 // cases. Investigate.
2628 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002629 ImpCastExprToType(LHS, compositeType);
2630 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002631 return compositeType;
2632 }
2633 }
2634
Chris Lattner992ae932008-01-06 22:42:25 +00002635 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002636 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2637 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002638 return QualType();
2639}
2640
Steve Naroff87d58b42007-09-16 03:34:24 +00002641/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002642/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002643Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2644 SourceLocation ColonLoc,
2645 ExprArg Cond, ExprArg LHS,
2646 ExprArg RHS) {
2647 Expr *CondExpr = (Expr *) Cond.get();
2648 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002649
2650 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2651 // was the condition.
2652 bool isLHSNull = LHSExpr == 0;
2653 if (isLHSNull)
2654 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002655
2656 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002657 RHSExpr, QuestionLoc);
2658 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002659 return ExprError();
2660
2661 Cond.release();
2662 LHS.release();
2663 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00002664 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00002665 isLHSNull ? 0 : LHSExpr,
2666 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002667}
2668
Chris Lattner4b009652007-07-25 00:24:17 +00002669
2670// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00002671// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00002672// routine is it effectively iqnores the qualifiers on the top level pointee.
2673// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2674// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00002675Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002676Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2677 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002678
Chris Lattner4b009652007-07-25 00:24:17 +00002679 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002680 lhptee = lhsType->getAsPointerType()->getPointeeType();
2681 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002682
Chris Lattner4b009652007-07-25 00:24:17 +00002683 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002684 lhptee = Context.getCanonicalType(lhptee);
2685 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002686
Chris Lattner005ed752008-01-04 18:04:52 +00002687 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002688
2689 // C99 6.5.16.1p1: This following citation is common to constraints
2690 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2691 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002692 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002693 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002694 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002695
Mike Stump9afab102009-02-19 03:04:26 +00002696 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2697 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00002698 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002699 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002700 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002701 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00002702
Chris Lattner4ca3d772008-01-03 22:56:36 +00002703 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002704 assert(rhptee->isFunctionType());
2705 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002706 }
Mike Stump9afab102009-02-19 03:04:26 +00002707
Chris Lattner4ca3d772008-01-03 22:56:36 +00002708 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002709 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002710 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002711
2712 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002713 assert(lhptee->isFunctionType());
2714 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002715 }
Mike Stump9afab102009-02-19 03:04:26 +00002716 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00002717 // unqualified versions of compatible types, ...
Mike Stump9afab102009-02-19 03:04:26 +00002718 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Chris Lattner4ca3d772008-01-03 22:56:36 +00002719 rhptee.getUnqualifiedType()))
2720 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002721 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002722}
2723
Steve Naroff3454b6c2008-09-04 15:10:53 +00002724/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2725/// block pointer types are compatible or whether a block and normal pointer
2726/// are compatible. It is more restrict than comparing two function pointer
2727// types.
Mike Stump9afab102009-02-19 03:04:26 +00002728Sema::AssignConvertType
2729Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00002730 QualType rhsType) {
2731 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002732
Steve Naroff3454b6c2008-09-04 15:10:53 +00002733 // get the "pointed to" type (ignoring qualifiers at the top level)
2734 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002735 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2736
Steve Naroff3454b6c2008-09-04 15:10:53 +00002737 // make sure we operate on the canonical type
2738 lhptee = Context.getCanonicalType(lhptee);
2739 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00002740
Steve Naroff3454b6c2008-09-04 15:10:53 +00002741 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002742
Steve Naroff3454b6c2008-09-04 15:10:53 +00002743 // For blocks we enforce that qualifiers are identical.
2744 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2745 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00002746
Steve Naroff3454b6c2008-09-04 15:10:53 +00002747 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00002748 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002749 return ConvTy;
2750}
2751
Mike Stump9afab102009-02-19 03:04:26 +00002752/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2753/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00002754/// pointers. Here are some objectionable examples that GCC considers warnings:
2755///
2756/// int a, *pint;
2757/// short *pshort;
2758/// struct foo *pfoo;
2759///
2760/// pint = pshort; // warning: assignment from incompatible pointer type
2761/// a = pint; // warning: assignment makes integer from pointer without a cast
2762/// pint = a; // warning: assignment makes pointer from integer without a cast
2763/// pint = pfoo; // warning: assignment from incompatible pointer type
2764///
2765/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00002766/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002767///
Chris Lattner005ed752008-01-04 18:04:52 +00002768Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002769Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002770 // Get canonical types. We're not formatting these types, just comparing
2771 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002772 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2773 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002774
2775 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002776 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002777
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002778 // If the left-hand side is a reference type, then we are in a
2779 // (rare!) case where we've allowed the use of references in C,
2780 // e.g., as a parameter type in a built-in function. In this case,
2781 // just make sure that the type referenced is compatible with the
2782 // right-hand side type. The caller is responsible for adjusting
2783 // lhsType so that the resulting expression does not have reference
2784 // type.
2785 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2786 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002787 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002788 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002789 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002790
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002791 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2792 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002793 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002794 // Relax integer conversions like we do for pointers below.
2795 if (rhsType->isIntegerType())
2796 return IntToPointer;
2797 if (lhsType->isIntegerType())
2798 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002799 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002800 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002801
Nate Begemanc5f0f652008-07-14 18:02:46 +00002802 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002803 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002804 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2805 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002806 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002807
Nate Begemanc5f0f652008-07-14 18:02:46 +00002808 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00002809 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00002810 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002811 if (getLangOptions().LaxVectorConversions &&
2812 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002813 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002814 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002815 }
2816 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00002817 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002818
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002819 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002820 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002821
Chris Lattner390564e2008-04-07 06:49:41 +00002822 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002823 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002824 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002825
Chris Lattner390564e2008-04-07 06:49:41 +00002826 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002827 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002828
Steve Naroffa982c712008-09-29 18:10:17 +00002829 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002830 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002831 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002832
2833 // Treat block pointers as objects.
2834 if (getLangOptions().ObjC1 &&
2835 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2836 return Compatible;
2837 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002838 return Incompatible;
2839 }
2840
2841 if (isa<BlockPointerType>(lhsType)) {
2842 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00002843 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00002844
Steve Naroffa982c712008-09-29 18:10:17 +00002845 // Treat block pointers as objects.
2846 if (getLangOptions().ObjC1 &&
2847 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2848 return Compatible;
2849
Steve Naroff3454b6c2008-09-04 15:10:53 +00002850 if (rhsType->isBlockPointerType())
2851 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002852
Steve Naroff3454b6c2008-09-04 15:10:53 +00002853 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2854 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002855 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002856 }
Chris Lattner1853da22008-01-04 23:18:45 +00002857 return Incompatible;
2858 }
2859
Chris Lattner390564e2008-04-07 06:49:41 +00002860 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002861 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002862 if (lhsType == Context.BoolTy)
2863 return Compatible;
2864
2865 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002866 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002867
Mike Stump9afab102009-02-19 03:04:26 +00002868 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002869 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002870
2871 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00002872 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002873 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002874 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002875 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002876
Chris Lattner1853da22008-01-04 23:18:45 +00002877 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002878 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002879 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002880 }
2881 return Incompatible;
2882}
2883
Chris Lattner005ed752008-01-04 18:04:52 +00002884Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002885Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002886 if (getLangOptions().CPlusPlus) {
2887 if (!lhsType->isRecordType()) {
2888 // C++ 5.17p3: If the left operand is not of class type, the
2889 // expression is implicitly converted (C++ 4) to the
2890 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002891 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2892 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002893 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002894 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002895 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002896 }
2897
2898 // FIXME: Currently, we fall through and treat C++ classes like C
2899 // structures.
2900 }
2901
Steve Naroffcdee22d2007-11-27 17:58:44 +00002902 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2903 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00002904 if ((lhsType->isPointerType() ||
2905 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00002906 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002907 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002908 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002909 return Compatible;
2910 }
Mike Stump9afab102009-02-19 03:04:26 +00002911
Chris Lattner5f505bf2007-10-16 02:55:40 +00002912 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002913 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002914 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002915 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002916 //
Mike Stump9afab102009-02-19 03:04:26 +00002917 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002918 if (!lhsType->isReferenceType())
2919 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002920
Chris Lattner005ed752008-01-04 18:04:52 +00002921 Sema::AssignConvertType result =
2922 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00002923
Steve Naroff0f32f432007-08-24 22:33:52 +00002924 // C99 6.5.16.1p2: The value of the right operand is converted to the
2925 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002926 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2927 // so that we can use references in built-in functions even in C.
2928 // The getNonReferenceType() call makes sure that the resulting expression
2929 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002930 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002931 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002932 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002933}
2934
Chris Lattner005ed752008-01-04 18:04:52 +00002935Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002936Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2937 return CheckAssignmentConstraints(lhsType, rhsType);
2938}
2939
Chris Lattner1eafdea2008-11-18 01:30:42 +00002940QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002941 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002942 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002943 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002944 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002945}
2946
Mike Stump9afab102009-02-19 03:04:26 +00002947inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002948 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00002949 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00002950 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002951 QualType lhsType =
2952 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2953 QualType rhsType =
2954 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00002955
Nate Begemanc5f0f652008-07-14 18:02:46 +00002956 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002957 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002958 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002959
Nate Begemanc5f0f652008-07-14 18:02:46 +00002960 // Handle the case of a vector & extvector type of the same size and element
2961 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002962 if (getLangOptions().LaxVectorConversions) {
2963 // FIXME: Should we warn here?
2964 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002965 if (const VectorType *RV = rhsType->getAsVectorType())
2966 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002967 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002968 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002969 }
2970 }
2971 }
Mike Stump9afab102009-02-19 03:04:26 +00002972
Nate Begemanc5f0f652008-07-14 18:02:46 +00002973 // If the lhs is an extended vector and the rhs is a scalar of the same type
2974 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002975 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002976 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00002977
2978 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002979 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2980 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002981 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002982 return lhsType;
2983 }
2984 }
2985
Nate Begemanc5f0f652008-07-14 18:02:46 +00002986 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002987 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002988 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002989 QualType eltType = V->getElementType();
2990
Mike Stump9afab102009-02-19 03:04:26 +00002991 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002992 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2993 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002994 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002995 return rhsType;
2996 }
2997 }
2998
Chris Lattner4b009652007-07-25 00:24:17 +00002999 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00003000 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003001 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003002 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003003 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003004}
3005
Chris Lattner4b009652007-07-25 00:24:17 +00003006inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003007 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003008{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003009 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003010 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003011
Steve Naroff8f708362007-08-24 19:07:16 +00003012 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003013
Chris Lattner4b009652007-07-25 00:24:17 +00003014 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003015 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003016 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003017}
3018
3019inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003020 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003021{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003022 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3023 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3024 return CheckVectorOperands(Loc, lex, rex);
3025 return InvalidOperands(Loc, lex, rex);
3026 }
Chris Lattner4b009652007-07-25 00:24:17 +00003027
Steve Naroff8f708362007-08-24 19:07:16 +00003028 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003029
Chris Lattner4b009652007-07-25 00:24:17 +00003030 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003031 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003032 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003033}
3034
3035inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump9afab102009-02-19 03:04:26 +00003036 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003037{
3038 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003039 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003040
Steve Naroff8f708362007-08-24 19:07:16 +00003041 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003042
Chris Lattner4b009652007-07-25 00:24:17 +00003043 // handle the common case first (both operands are arithmetic).
3044 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003045 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00003046
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003047 // Put any potential pointer into PExp
3048 Expr* PExp = lex, *IExp = rex;
3049 if (IExp->getType()->isPointerType())
3050 std::swap(PExp, IExp);
3051
3052 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
3053 if (IExp->getType()->isIntegerType()) {
3054 // Check for arithmetic on pointers to incomplete types
3055 if (!PTy->getPointeeType()->isObjectType()) {
3056 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003057 if (getLangOptions().CPlusPlus) {
3058 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3059 << lex->getSourceRange() << rex->getSourceRange();
3060 return QualType();
3061 }
3062
3063 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00003064 Diag(Loc, diag::ext_gnu_void_ptr)
3065 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003066 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003067 if (getLangOptions().CPlusPlus) {
3068 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3069 << lex->getType() << lex->getSourceRange();
3070 return QualType();
3071 }
3072
3073 // GNU extension: arithmetic on pointer to function
3074 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003075 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003076 } else {
Douglas Gregorc84d8932009-03-09 16:13:40 +00003077 RequireCompleteType(Loc, PTy->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003078 diag::err_typecheck_arithmetic_incomplete_type,
3079 lex->getSourceRange(), SourceRange(),
3080 lex->getType());
3081 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003082 }
3083 }
3084 return PExp->getType();
3085 }
3086 }
3087
Chris Lattner1eafdea2008-11-18 01:30:42 +00003088 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003089}
3090
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003091// C99 6.5.6
3092QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003093 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00003094 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003095 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003096
Steve Naroff8f708362007-08-24 19:07:16 +00003097 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003098
Chris Lattnerf6da2912007-12-09 21:53:25 +00003099 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00003100
Chris Lattnerf6da2912007-12-09 21:53:25 +00003101 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00003102 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003103 return compType;
Mike Stump9afab102009-02-19 03:04:26 +00003104
Chris Lattnerf6da2912007-12-09 21:53:25 +00003105 // Either ptr - int or ptr - ptr.
3106 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00003107 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003108
Chris Lattnerf6da2912007-12-09 21:53:25 +00003109 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00003110 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00003111 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00003112 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003113 Diag(Loc, diag::ext_gnu_void_ptr)
3114 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00003115 } else if (lpointee->isFunctionType()) {
3116 if (getLangOptions().CPlusPlus) {
3117 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3118 << lex->getType() << lex->getSourceRange();
3119 return QualType();
3120 }
3121
3122 // GNU extension: arithmetic on pointer to function
3123 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3124 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003125 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003126 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003127 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003128 return QualType();
3129 }
3130 }
3131
3132 // The result type of a pointer-int computation is the pointer type.
3133 if (rex->getType()->isIntegerType())
3134 return lex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003135
Chris Lattnerf6da2912007-12-09 21:53:25 +00003136 // Handle pointer-pointer subtractions.
3137 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00003138 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003139
Chris Lattnerf6da2912007-12-09 21:53:25 +00003140 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00003141 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00003142 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00003143 if (rpointee->isVoidType()) {
3144 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00003145 Diag(Loc, diag::ext_gnu_void_ptr)
3146 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00003147 } else if (rpointee->isFunctionType()) {
3148 if (getLangOptions().CPlusPlus) {
3149 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3150 << rex->getType() << rex->getSourceRange();
3151 return QualType();
3152 }
Mike Stump9afab102009-02-19 03:04:26 +00003153
Douglas Gregorf93eda12009-01-23 19:03:35 +00003154 // GNU extension: arithmetic on pointer to function
3155 if (!lpointee->isFunctionType())
3156 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3157 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003158 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003159 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003160 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003161 return QualType();
3162 }
3163 }
Mike Stump9afab102009-02-19 03:04:26 +00003164
Chris Lattnerf6da2912007-12-09 21:53:25 +00003165 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003166 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003167 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003168 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003169 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003170 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003171 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003172 return QualType();
3173 }
Mike Stump9afab102009-02-19 03:04:26 +00003174
Chris Lattnerf6da2912007-12-09 21:53:25 +00003175 return Context.getPointerDiffType();
3176 }
3177 }
Mike Stump9afab102009-02-19 03:04:26 +00003178
Chris Lattner1eafdea2008-11-18 01:30:42 +00003179 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003180}
3181
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003182// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003183QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003184 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003185 // C99 6.5.7p2: Each of the operands shall have integer type.
3186 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003187 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003188
Chris Lattner2c8bff72007-12-12 05:47:28 +00003189 // Shifts don't perform usual arithmetic conversions, they just do integer
3190 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003191 if (!isCompAssign)
3192 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00003193 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003194
Chris Lattner2c8bff72007-12-12 05:47:28 +00003195 // "The type of the result is that of the promoted left operand."
3196 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003197}
3198
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003199// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003200QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003201 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003202 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003203 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003204
Chris Lattner254f3bc2007-08-26 01:18:55 +00003205 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003206 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3207 UsualArithmeticConversions(lex, rex);
3208 else {
3209 UsualUnaryConversions(lex);
3210 UsualUnaryConversions(rex);
3211 }
Chris Lattner4b009652007-07-25 00:24:17 +00003212 QualType lType = lex->getType();
3213 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003214
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003215 if (!lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003216 // For non-floating point types, check for self-comparisons of the form
3217 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3218 // often indicate logic errors in the program.
3219 Expr *LHSStripped = lex->IgnoreParens();
3220 Expr *RHSStripped = rex->IgnoreParens();
3221 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
3222 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003223 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003224 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00003225
3226 if (isa<CastExpr>(LHSStripped))
3227 LHSStripped = LHSStripped->IgnoreParenCasts();
3228 if (isa<CastExpr>(RHSStripped))
3229 RHSStripped = RHSStripped->IgnoreParenCasts();
3230
3231 // Warn about comparisons against a string constant (unless the other
3232 // operand is null), the user probably wants strcmp.
3233 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
3234 !RHSStripped->isNullPointerConstant(Context))
3235 Diag(Loc, diag::warn_stringcompare) << lex->getSourceRange();
3236 else if ((isa<StringLiteral>(RHSStripped) ||
3237 isa<ObjCEncodeExpr>(RHSStripped)) &&
3238 !LHSStripped->isNullPointerConstant(Context))
3239 Diag(Loc, diag::warn_stringcompare) << rex->getSourceRange();
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003240 }
Mike Stump9afab102009-02-19 03:04:26 +00003241
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003242 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00003243 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003244
Chris Lattner254f3bc2007-08-26 01:18:55 +00003245 if (isRelational) {
3246 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003247 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003248 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003249 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003250 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003251 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003252 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003253 }
Mike Stump9afab102009-02-19 03:04:26 +00003254
Chris Lattner254f3bc2007-08-26 01:18:55 +00003255 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003256 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003257 }
Mike Stump9afab102009-02-19 03:04:26 +00003258
Chris Lattner22be8422007-08-26 01:10:14 +00003259 bool LHSIsNull = lex->isNullPointerConstant(Context);
3260 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003261
Chris Lattner254f3bc2007-08-26 01:18:55 +00003262 // All of the following pointer related warnings are GCC extensions, except
3263 // when handling null pointer constants. One day, we can consider making them
3264 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003265 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003266 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003267 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003268 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003269 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003270
Steve Naroff3b435622007-11-13 14:57:38 +00003271 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003272 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3273 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003274 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003275 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003276 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003277 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003278 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003279 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003280 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003281 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003282 // Handle block pointer types.
3283 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3284 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3285 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003286
Steve Naroff3454b6c2008-09-04 15:10:53 +00003287 if (!LHSIsNull && !RHSIsNull &&
3288 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003289 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003290 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003291 }
3292 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003293 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003294 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003295 // Allow block pointers to be compared with null pointer constants.
3296 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3297 (lType->isPointerType() && rType->isBlockPointerType())) {
3298 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003299 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003300 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003301 }
3302 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003303 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003304 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003305
Steve Naroff936c4362008-06-03 14:04:54 +00003306 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003307 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003308 const PointerType *LPT = lType->getAsPointerType();
3309 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003310 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003311 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003312 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003313 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003314
Steve Naroff030fcda2008-11-17 19:49:16 +00003315 if (!LPtrToVoid && !RPtrToVoid &&
3316 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003317 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003318 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003319 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003320 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003321 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003322 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003323 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003324 }
Steve Naroff936c4362008-06-03 14:04:54 +00003325 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3326 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003327 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003328 } else {
3329 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003330 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003331 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003332 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003333 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003334 }
Steve Naroff936c4362008-06-03 14:04:54 +00003335 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003336 }
Mike Stump9afab102009-02-19 03:04:26 +00003337 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003338 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003339 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003340 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003341 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003342 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003343 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003344 }
Mike Stump9afab102009-02-19 03:04:26 +00003345 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00003346 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003347 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003348 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003349 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003350 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003351 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003352 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003353 // Handle block pointers.
3354 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3355 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003356 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003357 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003358 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003359 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003360 }
3361 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3362 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003363 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003364 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003365 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003366 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003367 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003368 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003369}
3370
Nate Begemanc5f0f652008-07-14 18:02:46 +00003371/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00003372/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003373/// like a scalar comparison, a vector comparison produces a vector of integer
3374/// types.
3375QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003376 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003377 bool isRelational) {
3378 // Check to make sure we're operating on vectors of the same type and width,
3379 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003380 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003381 if (vType.isNull())
3382 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00003383
Nate Begemanc5f0f652008-07-14 18:02:46 +00003384 QualType lType = lex->getType();
3385 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003386
Nate Begemanc5f0f652008-07-14 18:02:46 +00003387 // For non-floating point types, check for self-comparisons of the form
3388 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3389 // often indicate logic errors in the program.
3390 if (!lType->isFloatingType()) {
3391 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3392 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3393 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003394 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003395 }
Mike Stump9afab102009-02-19 03:04:26 +00003396
Nate Begemanc5f0f652008-07-14 18:02:46 +00003397 // Check for comparisons of floating point operands using != and ==.
3398 if (!isRelational && lType->isFloatingType()) {
3399 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003400 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003401 }
Mike Stump9afab102009-02-19 03:04:26 +00003402
Nate Begemanc5f0f652008-07-14 18:02:46 +00003403 // Return the type for the comparison, which is the same as vector type for
3404 // integer vectors, or an integer type of identical size and number of
3405 // elements for floating point vectors.
3406 if (lType->isIntegerType())
3407 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00003408
Nate Begemanc5f0f652008-07-14 18:02:46 +00003409 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003410 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003411 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003412 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003413 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3414 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3415
Mike Stump9afab102009-02-19 03:04:26 +00003416 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00003417 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003418 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3419}
3420
Chris Lattner4b009652007-07-25 00:24:17 +00003421inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003422 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003423{
3424 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003425 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003426
Steve Naroff8f708362007-08-24 19:07:16 +00003427 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003428
Chris Lattner4b009652007-07-25 00:24:17 +00003429 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003430 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003431 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003432}
3433
3434inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00003435 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003436{
3437 UsualUnaryConversions(lex);
3438 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003439
Eli Friedmanbea3f842008-05-13 20:16:47 +00003440 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003441 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003442 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003443}
3444
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003445/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3446/// is a read-only property; return true if so. A readonly property expression
3447/// depends on various declarations and thus must be treated specially.
3448///
Mike Stump9afab102009-02-19 03:04:26 +00003449static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003450{
3451 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3452 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3453 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3454 QualType BaseType = PropExpr->getBase()->getType();
3455 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00003456 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003457 PTy->getPointeeType()->getAsObjCInterfaceType())
3458 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3459 if (S.isPropertyReadonly(PDecl, IFace))
3460 return true;
3461 }
3462 }
3463 return false;
3464}
3465
Chris Lattner4c2642c2008-11-18 01:22:49 +00003466/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3467/// emit an error and return true. If so, return false.
3468static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003469 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3470 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3471 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003472 if (IsLV == Expr::MLV_Valid)
3473 return false;
Mike Stump9afab102009-02-19 03:04:26 +00003474
Chris Lattner4c2642c2008-11-18 01:22:49 +00003475 unsigned Diag = 0;
3476 bool NeedType = false;
3477 switch (IsLV) { // C99 6.5.16p2
3478 default: assert(0 && "Unknown result from isModifiableLvalue!");
3479 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00003480 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003481 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3482 NeedType = true;
3483 break;
Mike Stump9afab102009-02-19 03:04:26 +00003484 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003485 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3486 NeedType = true;
3487 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003488 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003489 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3490 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003491 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003492 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3493 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003494 case Expr::MLV_IncompleteType:
3495 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00003496 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003497 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3498 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003499 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003500 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3501 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003502 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003503 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3504 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003505 case Expr::MLV_ReadonlyProperty:
3506 Diag = diag::error_readonly_property_assignment;
3507 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003508 case Expr::MLV_NoSetterProperty:
3509 Diag = diag::error_nosetter_property_assignment;
3510 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003511 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003512
Chris Lattner4c2642c2008-11-18 01:22:49 +00003513 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003514 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003515 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003516 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003517 return true;
3518}
3519
3520
3521
3522// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003523QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3524 SourceLocation Loc,
3525 QualType CompoundType) {
3526 // Verify that LHS is a modifiable lvalue, and emit error if not.
3527 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003528 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003529
3530 QualType LHSType = LHS->getType();
3531 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00003532
Chris Lattner005ed752008-01-04 18:04:52 +00003533 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003534 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003535 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003536 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003537 // Special case of NSObject attributes on c-style pointer types.
3538 if (ConvTy == IncompatiblePointer &&
3539 ((Context.isObjCNSObjectType(LHSType) &&
3540 Context.isObjCObjectPointerType(RHSType)) ||
3541 (Context.isObjCNSObjectType(RHSType) &&
3542 Context.isObjCObjectPointerType(LHSType))))
3543 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003544
Chris Lattner34c85082008-08-21 18:04:13 +00003545 // If the RHS is a unary plus or minus, check to see if they = and + are
3546 // right next to each other. If so, the user may have typo'd "x =+ 4"
3547 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003548 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003549 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3550 RHSCheck = ICE->getSubExpr();
3551 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3552 if ((UO->getOpcode() == UnaryOperator::Plus ||
3553 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003554 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003555 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00003556 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
3557 // And there is a space or other character before the subexpr of the
3558 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00003559 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
3560 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003561 Diag(Loc, diag::warn_not_compound_assign)
3562 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3563 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00003564 }
Chris Lattner34c85082008-08-21 18:04:13 +00003565 }
3566 } else {
3567 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003568 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003569 }
Chris Lattner005ed752008-01-04 18:04:52 +00003570
Chris Lattner1eafdea2008-11-18 01:30:42 +00003571 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3572 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003573 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003574
Chris Lattner4b009652007-07-25 00:24:17 +00003575 // C99 6.5.16p3: The type of an assignment expression is the type of the
3576 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00003577 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00003578 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3579 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003580 // C++ 5.17p1: the type of the assignment expression is that of its left
3581 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003582 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003583}
3584
Chris Lattner1eafdea2008-11-18 01:30:42 +00003585// C99 6.5.17
3586QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3587 // FIXME: what is required for LHS?
Mike Stump9afab102009-02-19 03:04:26 +00003588
Chris Lattner03c430f2008-07-25 20:54:07 +00003589 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003590 DefaultFunctionArrayConversion(RHS);
3591 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003592}
3593
3594/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3595/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003596QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3597 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003598 if (Op->isTypeDependent())
3599 return Context.DependentTy;
3600
Chris Lattnere65182c2008-11-21 07:05:48 +00003601 QualType ResType = Op->getType();
3602 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003603
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003604 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3605 // Decrement of bool is not allowed.
3606 if (!isInc) {
3607 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3608 return QualType();
3609 }
3610 // Increment of bool sets it to true, but is deprecated.
3611 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3612 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003613 // OK!
3614 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3615 // C99 6.5.2.4p2, 6.5.6p2
3616 if (PT->getPointeeType()->isObjectType()) {
3617 // Pointer to object is ok!
3618 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003619 if (getLangOptions().CPlusPlus) {
3620 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3621 << Op->getSourceRange();
3622 return QualType();
3623 }
3624
3625 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003626 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003627 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003628 if (getLangOptions().CPlusPlus) {
3629 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3630 << Op->getType() << Op->getSourceRange();
3631 return QualType();
3632 }
3633
3634 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003635 << ResType << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003636 } else {
Douglas Gregorc84d8932009-03-09 16:13:40 +00003637 RequireCompleteType(OpLoc, PT->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003638 diag::err_typecheck_arithmetic_incomplete_type,
3639 Op->getSourceRange(), SourceRange(),
3640 ResType);
3641 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003642 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003643 } else if (ResType->isComplexType()) {
3644 // C99 does not support ++/-- on complex types, we allow as an extension.
3645 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003646 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003647 } else {
3648 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003649 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003650 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003651 }
Mike Stump9afab102009-02-19 03:04:26 +00003652 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00003653 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003654 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003655 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003656 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003657}
3658
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003659/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003660/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003661/// where the declaration is needed for type checking. We only need to
3662/// handle cases when the expression references a function designator
3663/// or is an lvalue. Here are some examples:
3664/// - &(x) => x
3665/// - &*****f => f for f a function designator.
3666/// - &s.xx => s
3667/// - &s.zz[1].yy -> s, if zz is an array
3668/// - *(x + 1) -> x, if x is an array
3669/// - &"123"[2] -> 0
3670/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003671static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003672 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003673 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003674 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003675 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003676 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003677 // Fields cannot be declared with a 'register' storage class.
3678 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003679 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003680 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003681 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003682 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003683 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stump9afab102009-02-19 03:04:26 +00003684
Douglas Gregord2baafd2008-10-21 16:13:35 +00003685 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003686 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003687 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003688 return 0;
3689 else
3690 return VD;
3691 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003692 case Stmt::UnaryOperatorClass: {
3693 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00003694
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003695 switch(UO->getOpcode()) {
3696 case UnaryOperator::Deref: {
3697 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003698 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3699 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3700 if (!VD || VD->getType()->isPointerType())
3701 return 0;
3702 return VD;
3703 }
3704 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003705 }
3706 case UnaryOperator::Real:
3707 case UnaryOperator::Imag:
3708 case UnaryOperator::Extension:
3709 return getPrimaryDecl(UO->getSubExpr());
3710 default:
3711 return 0;
3712 }
3713 }
3714 case Stmt::BinaryOperatorClass: {
3715 BinaryOperator *BO = cast<BinaryOperator>(E);
3716
3717 // Handle cases involving pointer arithmetic. The result of an
3718 // Assign or AddAssign is not an lvalue so they can be ignored.
3719
3720 // (x + n) or (n + x) => x
3721 if (BO->getOpcode() == BinaryOperator::Add) {
3722 if (BO->getLHS()->getType()->isPointerType()) {
3723 return getPrimaryDecl(BO->getLHS());
3724 } else if (BO->getRHS()->getType()->isPointerType()) {
3725 return getPrimaryDecl(BO->getRHS());
3726 }
3727 }
3728
3729 return 0;
3730 }
Chris Lattner4b009652007-07-25 00:24:17 +00003731 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003732 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003733 case Stmt::ImplicitCastExprClass:
3734 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003735 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003736 default:
3737 return 0;
3738 }
3739}
3740
3741/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00003742/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00003743/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00003744/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00003745/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00003746/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00003747/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003748QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003749 if (op->isTypeDependent())
3750 return Context.DependentTy;
3751
Steve Naroff9c6c3592008-01-13 17:10:08 +00003752 if (getLangOptions().C99) {
3753 // Implement C99-only parts of addressof rules.
3754 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3755 if (uOp->getOpcode() == UnaryOperator::Deref)
3756 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3757 // (assuming the deref expression is valid).
3758 return uOp->getSubExpr()->getType();
3759 }
3760 // Technically, there should be a check for array subscript
3761 // expressions here, but the result of one is always an lvalue anyway.
3762 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003763 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003764 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003765
Chris Lattner4b009652007-07-25 00:24:17 +00003766 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003767 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3768 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003769 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3770 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003771 return QualType();
3772 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003773 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003774 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3775 if (Field->isBitField()) {
3776 Diag(OpLoc, diag::err_typecheck_address_of)
3777 << "bit-field" << op->getSourceRange();
3778 return QualType();
3779 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003780 }
3781 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003782 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3783 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003784 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003785 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003786 return QualType();
3787 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00003788 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00003789 // with the register storage-class specifier.
3790 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3791 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003792 Diag(OpLoc, diag::err_typecheck_address_of)
3793 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003794 return QualType();
3795 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003796 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003797 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003798 } else if (isa<FieldDecl>(dcl)) {
3799 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003800 // Could be a pointer to member, though, if there is an explicit
3801 // scope qualifier for the class.
3802 if (isa<QualifiedDeclRefExpr>(op)) {
3803 DeclContext *Ctx = dcl->getDeclContext();
3804 if (Ctx && Ctx->isRecord())
3805 return Context.getMemberPointerType(op->getType(),
3806 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3807 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003808 } else if (isa<FunctionDecl>(dcl)) {
3809 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003810 // As above.
3811 if (isa<QualifiedDeclRefExpr>(op)) {
3812 DeclContext *Ctx = dcl->getDeclContext();
3813 if (Ctx && Ctx->isRecord())
3814 return Context.getMemberPointerType(op->getType(),
3815 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3816 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003817 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003818 else
Chris Lattner4b009652007-07-25 00:24:17 +00003819 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003820 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003821
Chris Lattner4b009652007-07-25 00:24:17 +00003822 // If the operand has type "type", the result has type "pointer to type".
3823 return Context.getPointerType(op->getType());
3824}
3825
Chris Lattnerda5c0872008-11-23 09:13:29 +00003826QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003827 if (Op->isTypeDependent())
3828 return Context.DependentTy;
3829
Chris Lattnerda5c0872008-11-23 09:13:29 +00003830 UsualUnaryConversions(Op);
3831 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003832
Chris Lattnerda5c0872008-11-23 09:13:29 +00003833 // Note that per both C89 and C99, this is always legal, even if ptype is an
3834 // incomplete type or void. It would be possible to warn about dereferencing
3835 // a void pointer, but it's completely well-defined, and such a warning is
3836 // unlikely to catch any mistakes.
3837 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003838 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003839
Chris Lattner77d52da2008-11-20 06:06:08 +00003840 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003841 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003842 return QualType();
3843}
3844
3845static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3846 tok::TokenKind Kind) {
3847 BinaryOperator::Opcode Opc;
3848 switch (Kind) {
3849 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003850 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3851 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003852 case tok::star: Opc = BinaryOperator::Mul; break;
3853 case tok::slash: Opc = BinaryOperator::Div; break;
3854 case tok::percent: Opc = BinaryOperator::Rem; break;
3855 case tok::plus: Opc = BinaryOperator::Add; break;
3856 case tok::minus: Opc = BinaryOperator::Sub; break;
3857 case tok::lessless: Opc = BinaryOperator::Shl; break;
3858 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3859 case tok::lessequal: Opc = BinaryOperator::LE; break;
3860 case tok::less: Opc = BinaryOperator::LT; break;
3861 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3862 case tok::greater: Opc = BinaryOperator::GT; break;
3863 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3864 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3865 case tok::amp: Opc = BinaryOperator::And; break;
3866 case tok::caret: Opc = BinaryOperator::Xor; break;
3867 case tok::pipe: Opc = BinaryOperator::Or; break;
3868 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3869 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3870 case tok::equal: Opc = BinaryOperator::Assign; break;
3871 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3872 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3873 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3874 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3875 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3876 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3877 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3878 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3879 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3880 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3881 case tok::comma: Opc = BinaryOperator::Comma; break;
3882 }
3883 return Opc;
3884}
3885
3886static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3887 tok::TokenKind Kind) {
3888 UnaryOperator::Opcode Opc;
3889 switch (Kind) {
3890 default: assert(0 && "Unknown unary op!");
3891 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3892 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3893 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3894 case tok::star: Opc = UnaryOperator::Deref; break;
3895 case tok::plus: Opc = UnaryOperator::Plus; break;
3896 case tok::minus: Opc = UnaryOperator::Minus; break;
3897 case tok::tilde: Opc = UnaryOperator::Not; break;
3898 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003899 case tok::kw___real: Opc = UnaryOperator::Real; break;
3900 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3901 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3902 }
3903 return Opc;
3904}
3905
Douglas Gregord7f915e2008-11-06 23:29:22 +00003906/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3907/// operator @p Opc at location @c TokLoc. This routine only supports
3908/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003909Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3910 unsigned Op,
3911 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003912 QualType ResultTy; // Result type of the binary operator.
3913 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3914 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3915
3916 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003917 case BinaryOperator::Assign:
3918 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3919 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003920 case BinaryOperator::PtrMemD:
3921 case BinaryOperator::PtrMemI:
3922 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3923 Opc == BinaryOperator::PtrMemI);
3924 break;
3925 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003926 case BinaryOperator::Div:
3927 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3928 break;
3929 case BinaryOperator::Rem:
3930 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3931 break;
3932 case BinaryOperator::Add:
3933 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3934 break;
3935 case BinaryOperator::Sub:
3936 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3937 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003938 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003939 case BinaryOperator::Shr:
3940 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3941 break;
3942 case BinaryOperator::LE:
3943 case BinaryOperator::LT:
3944 case BinaryOperator::GE:
3945 case BinaryOperator::GT:
3946 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3947 break;
3948 case BinaryOperator::EQ:
3949 case BinaryOperator::NE:
3950 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3951 break;
3952 case BinaryOperator::And:
3953 case BinaryOperator::Xor:
3954 case BinaryOperator::Or:
3955 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3956 break;
3957 case BinaryOperator::LAnd:
3958 case BinaryOperator::LOr:
3959 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3960 break;
3961 case BinaryOperator::MulAssign:
3962 case BinaryOperator::DivAssign:
3963 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3964 if (!CompTy.isNull())
3965 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3966 break;
3967 case BinaryOperator::RemAssign:
3968 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3969 if (!CompTy.isNull())
3970 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3971 break;
3972 case BinaryOperator::AddAssign:
3973 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3974 if (!CompTy.isNull())
3975 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3976 break;
3977 case BinaryOperator::SubAssign:
3978 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3979 if (!CompTy.isNull())
3980 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3981 break;
3982 case BinaryOperator::ShlAssign:
3983 case BinaryOperator::ShrAssign:
3984 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3985 if (!CompTy.isNull())
3986 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3987 break;
3988 case BinaryOperator::AndAssign:
3989 case BinaryOperator::XorAssign:
3990 case BinaryOperator::OrAssign:
3991 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3992 if (!CompTy.isNull())
3993 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3994 break;
3995 case BinaryOperator::Comma:
3996 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3997 break;
3998 }
3999 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004000 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00004001 if (CompTy.isNull())
4002 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
4003 else
4004 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Mike Stump9afab102009-02-19 03:04:26 +00004005 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00004006}
4007
Chris Lattner4b009652007-07-25 00:24:17 +00004008// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004009Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
4010 tok::TokenKind Kind,
4011 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00004012 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004013 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00004014
Steve Naroff87d58b42007-09-16 03:34:24 +00004015 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
4016 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004017
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004018 if (getLangOptions().CPlusPlus &&
4019 (lhs->getType()->isOverloadableType() ||
4020 rhs->getType()->isOverloadableType())) {
4021 // Find all of the overloaded operators visible from this
4022 // point. We perform both an operator-name lookup from the local
4023 // scope and an argument-dependent lookup based on the types of
4024 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00004025 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004026 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
4027 if (OverOp != OO_None) {
4028 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
4029 Functions);
4030 Expr *Args[2] = { lhs, rhs };
4031 DeclarationName OpName
4032 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4033 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00004034 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004035
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004036 // Build the (potentially-overloaded, potentially-dependent)
4037 // binary operation.
4038 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004039 }
4040
Douglas Gregord7f915e2008-11-06 23:29:22 +00004041 // Build a built-in binary operation.
4042 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00004043}
4044
Douglas Gregorc78182d2009-03-13 23:49:33 +00004045Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
4046 unsigned OpcIn,
4047 ExprArg InputArg) {
4048 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004049
Douglas Gregorc78182d2009-03-13 23:49:33 +00004050 // FIXME: Input is modified below, but InputArg is not updated
4051 // appropriately.
4052 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00004053 QualType resultType;
4054 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004055 case UnaryOperator::PostInc:
4056 case UnaryOperator::PostDec:
4057 case UnaryOperator::OffsetOf:
4058 assert(false && "Invalid unary operator");
4059 break;
4060
Chris Lattner4b009652007-07-25 00:24:17 +00004061 case UnaryOperator::PreInc:
4062 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004063 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4064 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004065 break;
Mike Stump9afab102009-02-19 03:04:26 +00004066 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004067 resultType = CheckAddressOfOperand(Input, OpLoc);
4068 break;
Mike Stump9afab102009-02-19 03:04:26 +00004069 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004070 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004071 resultType = CheckIndirectionOperand(Input, OpLoc);
4072 break;
4073 case UnaryOperator::Plus:
4074 case UnaryOperator::Minus:
4075 UsualUnaryConversions(Input);
4076 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004077 if (resultType->isDependentType())
4078 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004079 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4080 break;
4081 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4082 resultType->isEnumeralType())
4083 break;
4084 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4085 Opc == UnaryOperator::Plus &&
4086 resultType->isPointerType())
4087 break;
4088
Sebastian Redl8b769972009-01-19 00:08:26 +00004089 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4090 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004091 case UnaryOperator::Not: // bitwise complement
4092 UsualUnaryConversions(Input);
4093 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004094 if (resultType->isDependentType())
4095 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00004096 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4097 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4098 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004099 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004100 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004101 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004102 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4103 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004104 break;
4105 case UnaryOperator::LNot: // logical negation
4106 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4107 DefaultFunctionArrayConversion(Input);
4108 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004109 if (resultType->isDependentType())
4110 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004111 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004112 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4113 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004114 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004115 // In C++, it's bool. C++ 5.3.1p8
4116 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004117 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004118 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004119 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004120 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004121 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004122 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004123 resultType = Input->getType();
4124 break;
4125 }
4126 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004127 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00004128
4129 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004130 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004131}
4132
Douglas Gregorc78182d2009-03-13 23:49:33 +00004133// Unary Operators. 'Tok' is the token for the operator.
4134Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4135 tok::TokenKind Op, ExprArg input) {
4136 Expr *Input = (Expr*)input.get();
4137 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
4138
4139 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
4140 // Find all of the overloaded operators visible from this
4141 // point. We perform both an operator-name lookup from the local
4142 // scope and an argument-dependent lookup based on the types of
4143 // the arguments.
4144 FunctionSet Functions;
4145 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
4146 if (OverOp != OO_None) {
4147 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
4148 Functions);
4149 DeclarationName OpName
4150 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4151 ArgumentDependentLookup(OpName, &Input, 1, Functions);
4152 }
4153
4154 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
4155 }
4156
4157 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
4158}
4159
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004160/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004161Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4162 SourceLocation LabLoc,
4163 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00004164 // Look up the record for this label identifier.
Steve Naroffff9ecaf2009-03-13 16:03:38 +00004165 LabelStmt *&LabelDecl = CurBlock ? CurBlock->LabelMap[LabelII] :
4166 LabelMap[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00004167
Daniel Dunbar879788d2008-08-04 16:51:22 +00004168 // If we haven't seen this label yet, create a forward reference. It
4169 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00004170 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004171 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004172
Chris Lattner4b009652007-07-25 00:24:17 +00004173 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004174 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4175 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00004176}
4177
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004178Sema::OwningExprResult
4179Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
4180 SourceLocation RPLoc) { // "({..})"
4181 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00004182 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4183 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4184
Eli Friedmanbc941e12009-01-24 23:09:00 +00004185 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4186 if (isFileScope) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004187 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00004188 }
4189
Chris Lattner4b009652007-07-25 00:24:17 +00004190 // FIXME: there are a variety of strange constraints to enforce here, for
4191 // example, it is not possible to goto into a stmt expression apparently.
4192 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004193
Chris Lattner4b009652007-07-25 00:24:17 +00004194 // FIXME: the last statement in the compount stmt has its value used. We
4195 // should not warn about it being unused.
4196
4197 // If there are sub stmts in the compound stmt, take the type of the last one
4198 // as the type of the stmtexpr.
4199 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004200
Chris Lattner200964f2008-07-26 19:51:01 +00004201 if (!Compound->body_empty()) {
4202 Stmt *LastStmt = Compound->body_back();
4203 // If LastStmt is a label, skip down through into the body.
4204 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4205 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004206
Chris Lattner200964f2008-07-26 19:51:01 +00004207 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004208 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004209 }
Mike Stump9afab102009-02-19 03:04:26 +00004210
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004211 substmt.release();
4212 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004213}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004214
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004215Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4216 SourceLocation BuiltinLoc,
4217 SourceLocation TypeLoc,
4218 TypeTy *argty,
4219 OffsetOfComponent *CompPtr,
4220 unsigned NumComponents,
4221 SourceLocation RPLoc) {
4222 // FIXME: This function leaks all expressions in the offset components on
4223 // error.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004224 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4225 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004226
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004227 bool Dependent = ArgTy->isDependentType();
4228
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004229 // We must have at least one component that refers to the type, and the first
4230 // one is known to be a field designator. Verify that the ArgTy represents
4231 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004232 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004233 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00004234
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00004235 // FIXME: Does the type need to be complete?
4236
Eli Friedman342d9432009-02-27 06:44:11 +00004237 // Otherwise, create a null pointer as the base, and iteratively process
4238 // the offsetof designators.
4239 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4240 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004241 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00004242 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004243
Chris Lattnerb37522e2007-08-31 21:49:13 +00004244 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4245 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00004246 // FIXME: This diagnostic isn't actually visible because the location is in
4247 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00004248 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004249 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4250 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004251
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004252 if (!Dependent) {
4253 // FIXME: Dependent case loses a lot of information here. And probably
4254 // leaks like a sieve.
4255 for (unsigned i = 0; i != NumComponents; ++i) {
4256 const OffsetOfComponent &OC = CompPtr[i];
4257 if (OC.isBrackets) {
4258 // Offset of an array sub-field. TODO: Should we allow vector elements?
4259 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4260 if (!AT) {
4261 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004262 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
4263 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004264 }
4265
4266 // FIXME: C++: Verify that operator[] isn't overloaded.
4267
Eli Friedman342d9432009-02-27 06:44:11 +00004268 // Promote the array so it looks more like a normal array subscript
4269 // expression.
4270 DefaultFunctionArrayConversion(Res);
4271
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004272 // C99 6.5.2.1p1
4273 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004274 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004275 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004276 return ExprError(Diag(Idx->getLocStart(),
4277 diag::err_typecheck_subscript)
4278 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004279
4280 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4281 OC.LocEnd);
4282 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004283 }
Mike Stump9afab102009-02-19 03:04:26 +00004284
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004285 const RecordType *RC = Res->getType()->getAsRecordType();
4286 if (!RC) {
4287 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004288 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
4289 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004290 }
Chris Lattner2af6a802007-08-30 17:59:59 +00004291
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004292 // Get the decl corresponding to this.
4293 RecordDecl *RD = RC->getDecl();
4294 FieldDecl *MemberDecl
4295 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4296 LookupMemberName)
4297 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004298 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004299 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004300 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
4301 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00004302
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004303 // FIXME: C++: Verify that MemberDecl isn't a static field.
4304 // FIXME: Verify that MemberDecl isn't a bitfield.
4305 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4306 // matter here.
4307 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff774e4152009-01-21 00:14:39 +00004308 MemberDecl->getType().getNonReferenceType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004309 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004310 }
Mike Stump9afab102009-02-19 03:04:26 +00004311
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004312 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4313 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004314}
4315
4316
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004317Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
4318 TypeTy *arg1,TypeTy *arg2,
4319 SourceLocation RPLoc) {
Steve Naroff63bad2d2007-08-01 22:05:33 +00004320 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4321 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004322
Steve Naroff63bad2d2007-08-01 22:05:33 +00004323 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004324
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004325 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
4326 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00004327}
4328
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004329Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
4330 ExprArg cond,
4331 ExprArg expr1, ExprArg expr2,
4332 SourceLocation RPLoc) {
4333 Expr *CondExpr = static_cast<Expr*>(cond.get());
4334 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
4335 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00004336
Steve Naroff93c53012007-08-03 21:21:27 +00004337 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4338
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004339 QualType resType;
4340 if (CondExpr->isValueDependent()) {
4341 resType = Context.DependentTy;
4342 } else {
4343 // The conditional expression is required to be a constant expression.
4344 llvm::APSInt condEval(32);
4345 SourceLocation ExpLoc;
4346 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004347 return ExprError(Diag(ExpLoc,
4348 diag::err_typecheck_choose_expr_requires_constant)
4349 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00004350
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004351 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4352 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4353 }
4354
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004355 cond.release(); expr1.release(); expr2.release();
4356 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4357 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00004358}
4359
Steve Naroff52a81c02008-09-03 18:15:37 +00004360//===----------------------------------------------------------------------===//
4361// Clang Extensions.
4362//===----------------------------------------------------------------------===//
4363
4364/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004365void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004366 // Analyze block parameters.
4367 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00004368
Steve Naroff52a81c02008-09-03 18:15:37 +00004369 // Add BSI to CurBlock.
4370 BSI->PrevBlockInfo = CurBlock;
4371 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00004372
Steve Naroff52a81c02008-09-03 18:15:37 +00004373 BSI->ReturnType = 0;
4374 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00004375 BSI->hasBlockDeclRefExprs = false;
Mike Stump9afab102009-02-19 03:04:26 +00004376
Steve Naroff52059382008-10-10 01:28:17 +00004377 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004378 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004379}
4380
Mike Stumpc1fddff2009-02-04 22:31:32 +00004381void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4382 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4383
4384 if (ParamInfo.getNumTypeObjects() == 0
4385 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4386 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4387
4388 // The type is entirely optional as well, if none, use DependentTy.
4389 if (T.isNull())
4390 T = Context.DependentTy;
4391
4392 // The parameter list is optional, if there was none, assume ().
4393 if (!T->isFunctionType())
4394 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4395
4396 CurBlock->hasPrototype = true;
4397 CurBlock->isVariadic = false;
4398 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4399 .getTypePtr();
4400
4401 if (!RetTy->isDependentType())
4402 CurBlock->ReturnType = RetTy;
4403 return;
4404 }
4405
Steve Naroff52a81c02008-09-03 18:15:37 +00004406 // Analyze arguments to block.
4407 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4408 "Not a function declarator!");
4409 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00004410
Steve Naroff52059382008-10-10 01:28:17 +00004411 CurBlock->hasPrototype = FTI.hasPrototype;
4412 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00004413
Steve Naroff52a81c02008-09-03 18:15:37 +00004414 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4415 // no arguments, not a function that takes a single void argument.
4416 if (FTI.hasPrototype &&
4417 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4418 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4419 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4420 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004421 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004422 } else if (FTI.hasPrototype) {
4423 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004424 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4425 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004426 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4427
4428 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4429 .getTypePtr();
4430
4431 if (!RetTy->isDependentType())
4432 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004433 }
Steve Naroff494cb0f2009-03-13 16:56:44 +00004434 CurBlock->TheDecl->setParams(Context, &CurBlock->Params[0],
4435 CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00004436
Steve Naroff52059382008-10-10 01:28:17 +00004437 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4438 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4439 // If this has an identifier, add it to the scope stack.
4440 if ((*AI)->getIdentifier())
4441 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004442}
4443
4444/// ActOnBlockError - If there is an error parsing a block, this callback
4445/// is invoked to pop the information about the block from the action impl.
4446void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4447 // Ensure that CurBlock is deleted.
4448 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00004449
Steve Naroff52a81c02008-09-03 18:15:37 +00004450 // Pop off CurBlock, handle nested blocks.
4451 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004452
Steve Naroff52a81c02008-09-03 18:15:37 +00004453 // FIXME: Delete the ParmVarDecl objects as well???
Douglas Gregorc1408ea2009-03-11 23:54:15 +00004454
Steve Naroff52a81c02008-09-03 18:15:37 +00004455}
4456
4457/// ActOnBlockStmtExpr - This is called when the body of a block statement
4458/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004459Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
4460 StmtArg body, Scope *CurScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004461 // Ensure that CurBlock is deleted.
4462 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00004463
Steve Naroff52059382008-10-10 01:28:17 +00004464 PopDeclContext();
4465
Steve Naroff52a81c02008-09-03 18:15:37 +00004466 // Pop off CurBlock, handle nested blocks.
4467 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004468
Steve Naroff52a81c02008-09-03 18:15:37 +00004469 QualType RetTy = Context.VoidTy;
4470 if (BSI->ReturnType)
4471 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004472
Steve Naroff52a81c02008-09-03 18:15:37 +00004473 llvm::SmallVector<QualType, 8> ArgTypes;
4474 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4475 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00004476
Steve Naroff52a81c02008-09-03 18:15:37 +00004477 QualType BlockTy;
4478 if (!BSI->hasPrototype)
Douglas Gregor4fa58902009-02-26 23:50:07 +00004479 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004480 else
4481 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004482 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004483
Steve Naroff52a81c02008-09-03 18:15:37 +00004484 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00004485
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004486 BSI->TheDecl->setBody(static_cast<CompoundStmt*>(body.release()));
4487 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
4488 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00004489}
4490
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004491Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4492 ExprArg expr, TypeTy *type,
4493 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004494 QualType T = QualType::getFromOpaquePtr(type);
4495
4496 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004497
4498 // Get the va_list type
4499 QualType VaListType = Context.getBuiltinVaListType();
4500 // Deal with implicit array decay; for example, on x86-64,
4501 // va_list is an array, but it's supposed to decay to
4502 // a pointer for va_arg.
4503 if (VaListType->isArrayType())
4504 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004505 // Make sure the input expression also decays appropriately.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004506 Expr *E = static_cast<Expr*>(expr.get());
Eli Friedman8754e5b2008-08-20 22:17:17 +00004507 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004508
4509 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004510 return ExprError(Diag(E->getLocStart(),
4511 diag::err_first_argument_to_va_arg_not_of_type_va_list)
4512 << E->getType() << E->getSourceRange());
Mike Stump9afab102009-02-19 03:04:26 +00004513
Anders Carlsson36760332007-10-15 20:28:48 +00004514 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00004515
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004516 expr.release();
4517 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
4518 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00004519}
4520
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004521Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00004522 // The type of __null will be int or long, depending on the size of
4523 // pointers on the target.
4524 QualType Ty;
4525 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4526 Ty = Context.IntTy;
4527 else
4528 Ty = Context.LongTy;
4529
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004530 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00004531}
4532
Chris Lattner005ed752008-01-04 18:04:52 +00004533bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4534 SourceLocation Loc,
4535 QualType DstType, QualType SrcType,
4536 Expr *SrcExpr, const char *Flavor) {
4537 // Decode the result (notice that AST's are still created for extensions).
4538 bool isInvalid = false;
4539 unsigned DiagKind;
4540 switch (ConvTy) {
4541 default: assert(0 && "Unknown conversion type");
4542 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004543 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004544 DiagKind = diag::ext_typecheck_convert_pointer_int;
4545 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004546 case IntToPointer:
4547 DiagKind = diag::ext_typecheck_convert_int_pointer;
4548 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004549 case IncompatiblePointer:
4550 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4551 break;
4552 case FunctionVoidPointer:
4553 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4554 break;
4555 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004556 // If the qualifiers lost were because we were applying the
4557 // (deprecated) C++ conversion from a string literal to a char*
4558 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4559 // Ideally, this check would be performed in
4560 // CheckPointerTypesForAssignment. However, that would require a
4561 // bit of refactoring (so that the second argument is an
4562 // expression, rather than a type), which should be done as part
4563 // of a larger effort to fix CheckPointerTypesForAssignment for
4564 // C++ semantics.
4565 if (getLangOptions().CPlusPlus &&
4566 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4567 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004568 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4569 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004570 case IntToBlockPointer:
4571 DiagKind = diag::err_int_to_block_pointer;
4572 break;
4573 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004574 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004575 break;
Steve Naroff19608432008-10-14 22:18:38 +00004576 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00004577 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00004578 // it can give a more specific diagnostic.
4579 DiagKind = diag::warn_incompatible_qualified_id;
4580 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004581 case IncompatibleVectors:
4582 DiagKind = diag::warn_incompatible_vectors;
4583 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004584 case Incompatible:
4585 DiagKind = diag::err_typecheck_convert_incompatible;
4586 isInvalid = true;
4587 break;
4588 }
Mike Stump9afab102009-02-19 03:04:26 +00004589
Chris Lattner271d4c22008-11-24 05:29:24 +00004590 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4591 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004592 return isInvalid;
4593}
Anders Carlssond5201b92008-11-30 19:50:32 +00004594
4595bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4596{
4597 Expr::EvalResult EvalResult;
4598
Mike Stump9afab102009-02-19 03:04:26 +00004599 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00004600 EvalResult.HasSideEffects) {
4601 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4602
4603 if (EvalResult.Diag) {
4604 // We only show the note if it's not the usual "invalid subexpression"
4605 // or if it's actually in a subexpression.
4606 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4607 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4608 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4609 }
Mike Stump9afab102009-02-19 03:04:26 +00004610
Anders Carlssond5201b92008-11-30 19:50:32 +00004611 return true;
4612 }
4613
4614 if (EvalResult.Diag) {
Mike Stump9afab102009-02-19 03:04:26 +00004615 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssond5201b92008-11-30 19:50:32 +00004616 E->getSourceRange();
4617
4618 // Print the reason it's not a constant.
4619 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4620 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4621 }
Mike Stump9afab102009-02-19 03:04:26 +00004622
Anders Carlssond5201b92008-11-30 19:50:32 +00004623 if (Result)
4624 *Result = EvalResult.Val.getInt();
4625 return false;
4626}