blob: 9a77e4f8e1d53c34fa96f03bc1d1fa502bd756ff [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner04421082008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Chris Lattnere7a2e912008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattnere7a2e912008-07-25 21:10:04 +000033/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
34void Sema::DefaultFunctionArrayConversion(Expr *&E) {
35 QualType Ty = E->getType();
36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
37
Chris Lattnere7a2e912008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-07-25 21:33:13 +000040 else if (Ty->isArrayType()) {
41 // In C90 mode, arrays only promote to pointers if the array expression is
42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
43 // type 'array of type' is converted to an expression that has type 'pointer
44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
45 // that has type 'array of type' ...". The relevant change is "an lvalue"
46 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +000047 //
48 // C++ 4.2p1:
49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
50 // T" can be converted to an rvalue of type "pointer to T".
51 //
52 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
53 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner67d33d82008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattnere7a2e912008-07-25 21:10:04 +000056}
57
58/// UsualUnaryConversions - Performs various conversions that are common to most
59/// operators (C99 6.3). The conversions of array and function types are
60/// sometimes surpressed. For example, the array->pointer conversion doesn't
61/// apply if the array is an argument to the sizeof or address (&) operators.
62/// In these instances, this routine should *not* be called.
63Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
64 QualType Ty = Expr->getType();
65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
66
Chris Lattnere7a2e912008-07-25 21:10:04 +000067 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
68 ImpCastExprToType(Expr, Context.IntTy);
69 else
70 DefaultFunctionArrayConversion(Expr);
71
72 return Expr;
73}
74
Chris Lattner05faf172008-07-25 22:25:12 +000075/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
76/// do not have a prototype. Arguments that have type float are promoted to
77/// double. All other argument types are converted by UsualUnaryConversions().
78void Sema::DefaultArgumentPromotion(Expr *&Expr) {
79 QualType Ty = Expr->getType();
80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
81
82 // If this is a 'float' (CVR qualified or typedef) promote to double.
83 if (const BuiltinType *BT = Ty->getAsBuiltinType())
84 if (BT->getKind() == BuiltinType::Float)
85 return ImpCastExprToType(Expr, Context.DoubleTy);
86
87 UsualUnaryConversions(Expr);
88}
89
Chris Lattnere7a2e912008-07-25 21:10:04 +000090/// UsualArithmeticConversions - Performs various conversions that are common to
91/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
92/// routine returns the first non-arithmetic type found. The client is
93/// responsible for emitting appropriate error diagnostics.
94/// FIXME: verify the conversion rules for "complex int" are consistent with
95/// GCC.
96QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
97 bool isCompAssign) {
98 if (!isCompAssign) {
99 UsualUnaryConversions(lhsExpr);
100 UsualUnaryConversions(rhsExpr);
101 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000102
Chris Lattnere7a2e912008-07-25 21:10:04 +0000103 // For conversion purposes, we ignore any qualifiers.
104 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000105 QualType lhs =
106 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
107 QualType rhs =
108 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000109
110 // If both types are identical, no conversion is needed.
111 if (lhs == rhs)
112 return lhs;
113
114 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
115 // The caller can deal with this (e.g. pointer + int).
116 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
117 return lhs;
118
119 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
120 if (!isCompAssign) {
121 ImpCastExprToType(lhsExpr, destType);
122 ImpCastExprToType(rhsExpr, destType);
123 }
124 return destType;
125}
126
127QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
128 // Perform the usual unary conversions. We do this early so that
129 // integral promotions to "int" can allow us to exit early, in the
130 // lhs == rhs check. Also, for conversion purposes, we ignore any
131 // qualifiers. For example, "const float" and "float" are
132 // equivalent.
Douglas Gregorbf3af052008-11-13 20:12:29 +0000133 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
134 else lhs = lhs.getUnqualifiedType();
135 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
136 else rhs = rhs.getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000137
Chris Lattnere7a2e912008-07-25 21:10:04 +0000138 // If both types are identical, no conversion is needed.
139 if (lhs == rhs)
140 return lhs;
141
142 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
143 // The caller can deal with this (e.g. pointer + int).
144 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
145 return lhs;
146
147 // At this point, we have two different arithmetic types.
148
149 // Handle complex types first (C99 6.3.1.8p1).
150 if (lhs->isComplexType() || rhs->isComplexType()) {
151 // if we have an integer operand, the result is the complex type.
152 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
153 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000154 return lhs;
155 }
156 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
157 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000158 return rhs;
159 }
160 // This handles complex/complex, complex/float, or float/complex.
161 // When both operands are complex, the shorter operand is converted to the
162 // type of the longer, and that is the type of the result. This corresponds
163 // to what is done when combining two real floating-point operands.
164 // The fun begins when size promotion occur across type domains.
165 // From H&S 6.3.4: When one operand is complex and the other is a real
166 // floating-point type, the less precise type is converted, within it's
167 // real or complex domain, to the precision of the other type. For example,
168 // when combining a "long double" with a "double _Complex", the
169 // "double _Complex" is promoted to "long double _Complex".
170 int result = Context.getFloatingTypeOrder(lhs, rhs);
171
172 if (result > 0) { // The left side is bigger, convert rhs.
173 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000174 } else if (result < 0) { // The right side is bigger, convert lhs.
175 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000176 }
177 // At this point, lhs and rhs have the same rank/size. Now, make sure the
178 // domains match. This is a requirement for our implementation, C99
179 // does not require this promotion.
180 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
181 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattnere7a2e912008-07-25 21:10:04 +0000182 return rhs;
183 } else { // handle "_Complex double, double".
Chris Lattnere7a2e912008-07-25 21:10:04 +0000184 return lhs;
185 }
186 }
187 return lhs; // The domain/size match exactly.
188 }
189 // Now handle "real" floating types (i.e. float, double, long double).
190 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
191 // if we have an integer operand, the result is the real floating type.
192 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
193 // convert rhs to the lhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000194 return lhs;
195 }
196 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
197 // convert lhs to the rhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000198 return rhs;
199 }
200 // We have two real floating types, float/complex combos were handled above.
201 // Convert the smaller operand to the bigger result.
202 int result = Context.getFloatingTypeOrder(lhs, rhs);
203
204 if (result > 0) { // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000205 return lhs;
206 }
207 if (result < 0) { // convert the lhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000208 return rhs;
209 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000210 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattnere7a2e912008-07-25 21:10:04 +0000211 }
212 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
213 // Handle GCC complex int extension.
214 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
215 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
216
217 if (lhsComplexInt && rhsComplexInt) {
218 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
219 rhsComplexInt->getElementType()) >= 0) {
220 // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000221 return lhs;
222 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000223 return rhs;
224 } else if (lhsComplexInt && rhs->isIntegerType()) {
225 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000226 return lhs;
227 } else if (rhsComplexInt && lhs->isIntegerType()) {
228 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000229 return rhs;
230 }
231 }
232 // Finally, we have two differing integer types.
233 // The rules for this case are in C99 6.3.1.8
234 int compare = Context.getIntegerTypeOrder(lhs, rhs);
235 bool lhsSigned = lhs->isSignedIntegerType(),
236 rhsSigned = rhs->isSignedIntegerType();
237 QualType destType;
238 if (lhsSigned == rhsSigned) {
239 // Same signedness; use the higher-ranked type
240 destType = compare >= 0 ? lhs : rhs;
241 } else if (compare != (lhsSigned ? 1 : -1)) {
242 // The unsigned type has greater than or equal rank to the
243 // signed type, so use the unsigned type
244 destType = lhsSigned ? rhs : lhs;
245 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
246 // The two types are different widths; if we are here, that
247 // means the signed type is larger than the unsigned type, so
248 // use the signed type.
249 destType = lhsSigned ? lhs : rhs;
250 } else {
251 // The signed type is higher-ranked than the unsigned type,
252 // but isn't actually any bigger (like unsigned int and long
253 // on most 32-bit systems). Use the unsigned type corresponding
254 // to the signed type.
255 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
256 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000257 return destType;
258}
259
260//===----------------------------------------------------------------------===//
261// Semantic Analysis for various Expression Types
262//===----------------------------------------------------------------------===//
263
264
Steve Narofff69936d2007-09-16 03:34:24 +0000265/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000266/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
267/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
268/// multiple tokens. However, the common case is that StringToks points to one
269/// string.
270///
271Action::ExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000272Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000273 assert(NumStringToks && "Must have at least one string!");
274
275 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
276 if (Literal.hadError)
277 return ExprResult(true);
278
279 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
280 for (unsigned i = 0; i != NumStringToks; ++i)
281 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000282
283 // Verify that pascal strings aren't too large.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000284 if (Literal.Pascal && Literal.GetStringLength() > 256)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000285 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
286 << SourceRange(StringToks[0].getLocation(),
287 StringToks[NumStringToks-1].getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000288
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000289 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000290 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000291 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000292
293 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
294 if (getLangOptions().CPlusPlus)
295 StrTy.addConst();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000296
297 // Get an array type for the string, according to C99 6.4.5. This includes
298 // the nul terminator character as well as the string length for pascal
299 // strings.
300 StrTy = Context.getConstantArrayType(StrTy,
301 llvm::APInt(32, Literal.GetStringLength()+1),
302 ArrayType::Normal, 0);
303
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
305 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000306 Literal.AnyWide, StrTy,
Anders Carlssonee98ac52007-10-15 02:50:23 +0000307 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 StringToks[NumStringToks-1].getLocation());
309}
310
Chris Lattner639e2d32008-10-20 05:16:36 +0000311/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
312/// CurBlock to VD should cause it to be snapshotted (as we do for auto
313/// variables defined outside the block) or false if this is not needed (e.g.
314/// for values inside the block or for globals).
315///
316/// FIXME: This will create BlockDeclRefExprs for global variables,
317/// function references, etc which is suboptimal :) and breaks
318/// things like "integer constant expression" tests.
319static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
320 ValueDecl *VD) {
321 // If the value is defined inside the block, we couldn't snapshot it even if
322 // we wanted to.
323 if (CurBlock->TheDecl == VD->getDeclContext())
324 return false;
325
326 // If this is an enum constant or function, it is constant, don't snapshot.
327 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
328 return false;
329
330 // If this is a reference to an extern, static, or global variable, no need to
331 // snapshot it.
332 // FIXME: What about 'const' variables in C++?
333 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
334 return Var->hasLocalStorage();
335
336 return true;
337}
338
339
340
Steve Naroff08d92e42007-09-15 18:49:24 +0000341/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000342/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000343/// identifier is used in a function call context.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000344/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the
345/// class or namespace that the identifier must be a member of.
Steve Naroff08d92e42007-09-15 18:49:24 +0000346Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 IdentifierInfo &II,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000348 bool HasTrailingLParen,
349 const CXXScopeSpec *SS) {
Douglas Gregor10c42622008-11-18 15:03:34 +0000350 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
351}
352
353/// ActOnDeclarationNameExpr - The parser has read some kind of name
354/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
355/// performs lookup on that name and returns an expression that refers
356/// to that name. This routine isn't directly called from the parser,
357/// because the parser doesn't know about DeclarationName. Rather,
358/// this routine is called by ActOnIdentifierExpr,
359/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
360/// which form the DeclarationName from the corresponding syntactic
361/// forms.
362///
363/// HasTrailingLParen indicates whether this identifier is used in a
364/// function call context. LookupCtx is only used for a C++
365/// qualified-id (foo::bar) to indicate the class or namespace that
366/// the identifier must be a member of.
367Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
368 DeclarationName Name,
369 bool HasTrailingLParen,
370 const CXXScopeSpec *SS) {
Chris Lattner8a934232008-03-31 00:36:02 +0000371 // Could be enum-constant, value decl, instance variable, etc.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000372 Decl *D;
373 if (SS && !SS->isEmpty()) {
374 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
375 if (DC == 0)
376 return true;
Douglas Gregor10c42622008-11-18 15:03:34 +0000377 D = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000378 } else
Douglas Gregor10c42622008-11-18 15:03:34 +0000379 D = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Chris Lattner8a934232008-03-31 00:36:02 +0000380
381 // If this reference is in an Objective-C method, then ivar lookup happens as
382 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000383 IdentifierInfo *II = Name.getAsIdentifierInfo();
384 if (II && getCurMethodDecl()) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000385 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattner8a934232008-03-31 00:36:02 +0000386 // There are two cases to handle here. 1) scoped lookup could have failed,
387 // in which case we should look for an ivar. 2) scoped lookup could have
388 // found a decl, but that decl is outside the current method (i.e. a global
389 // variable). In these two cases, we do a lookup for an ivar with this
390 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe8043c32008-04-01 23:04:06 +0000391 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000392 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregor10c42622008-11-18 15:03:34 +0000393 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner8a934232008-03-31 00:36:02 +0000394 // FIXME: This should use a new expr for a direct reference, don't turn
395 // this into Self->ivar, just return a BareIVarExpr or something.
396 IdentifierInfo &II = Context.Idents.get("self");
397 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
398 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
399 static_cast<Expr*>(SelfExpr.Val), true, true);
400 }
401 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000402 // Needed to implement property "super.method" notation.
Douglas Gregor10c42622008-11-18 15:03:34 +0000403 if (SD == 0 && II == SuperID) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000404 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000405 getCurMethodDecl()->getClassInterface()));
Douglas Gregorcd9b46e2008-11-04 14:56:14 +0000406 return new ObjCSuperExpr(Loc, T);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000407 }
Chris Lattner8a934232008-03-31 00:36:02 +0000408 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 if (D == 0) {
410 // Otherwise, this could be an implicitly declared function reference (legal
411 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000412 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000413 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000414 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 else {
416 // If this name wasn't predeclared and if this is not a function call,
417 // diagnose the problem.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000418 if (SS && !SS->isEmpty())
419 return Diag(Loc, diag::err_typecheck_no_member,
Douglas Gregor10c42622008-11-18 15:03:34 +0000420 Name.getAsString(), SS->getRange());
421 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
422 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000423 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000424 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000425 return Diag(Loc, diag::err_undeclared_var_use) << Name.getAsString();
Reid Spencer5f016e22007-07-11 17:01:13 +0000426 }
427 }
Chris Lattner8a934232008-03-31 00:36:02 +0000428
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000429 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
430 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
431 if (MD->isStatic())
432 // "invalid use of member 'x' in static member function"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000433 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
434 << FD->getName();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000435 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
436 // "invalid use of nonstatic data member 'x'"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000437 return Diag(Loc, diag::err_invalid_non_static_member_use)
438 << FD->getName();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000439
440 if (FD->isInvalidDecl())
441 return true;
442
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +0000443 // FIXME: Handle 'mutable'.
444 return new DeclRefExpr(FD,
445 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000446 }
447
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000448 return Diag(Loc, diag::err_invalid_non_static_member_use) << FD->getName();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000449 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 if (isa<TypedefDecl>(D))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000451 return Diag(Loc, diag::err_unexpected_typedef) << Name.getAsString();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000452 if (isa<ObjCInterfaceDecl>(D))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000453 return Diag(Loc, diag::err_unexpected_interface) << Name.getAsString();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000454 if (isa<NamespaceDecl>(D))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000455 return Diag(Loc, diag::err_unexpected_namespace) << Name.getAsString();
Reid Spencer5f016e22007-07-11 17:01:13 +0000456
Steve Naroffdd972f22008-09-05 22:11:13 +0000457 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000458 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
459 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
460
Steve Naroffdd972f22008-09-05 22:11:13 +0000461 ValueDecl *VD = cast<ValueDecl>(D);
462
463 // check if referencing an identifier with __attribute__((deprecated)).
464 if (VD->getAttr<DeprecatedAttr>())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000465 Diag(Loc, diag::warn_deprecated) << VD->getName();
Steve Naroffdd972f22008-09-05 22:11:13 +0000466
467 // Only create DeclRefExpr's for valid Decl's.
468 if (VD->isInvalidDecl())
469 return true;
Chris Lattner639e2d32008-10-20 05:16:36 +0000470
471 // If the identifier reference is inside a block, and it refers to a value
472 // that is outside the block, create a BlockDeclRefExpr instead of a
473 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
474 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000475 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000476 // We do not do this for things like enum constants, global variables, etc,
477 // as they do not get snapshotted.
478 //
479 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff090276f2008-10-10 01:28:17 +0000480 // The BlocksAttr indicates the variable is bound by-reference.
481 if (VD->getAttr<BlocksAttr>())
Douglas Gregor9d293df2008-10-28 00:22:11 +0000482 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
483 Loc, true);
Steve Naroff090276f2008-10-10 01:28:17 +0000484
485 // Variable will be bound by-copy, make it const within the closure.
486 VD->getType().addConst();
Douglas Gregor9d293df2008-10-28 00:22:11 +0000487 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
488 Loc, false);
Steve Naroff090276f2008-10-10 01:28:17 +0000489 }
490 // If this reference is not in a block or if the referenced variable is
491 // within the block, create a normal DeclRefExpr.
Douglas Gregore0a5d5f2008-10-22 04:14:44 +0000492 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000493}
494
Chris Lattnerd9f69102008-08-10 01:53:14 +0000495Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000496 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000497 PredefinedExpr::IdentType IT;
Anders Carlsson22742662007-07-21 05:21:51 +0000498
Reid Spencer5f016e22007-07-11 17:01:13 +0000499 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000500 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000501 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
502 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
503 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000504 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000505
506 // Verify that this is in a function context.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000507 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattner1423ea42008-01-12 18:39:25 +0000508 return Diag(Loc, diag::err_predef_outside_function);
Anders Carlsson22742662007-07-21 05:21:51 +0000509
Chris Lattnerfa28b302008-01-12 08:14:25 +0000510 // Pre-defined identifiers are of type char[x], where x is the length of the
511 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000512 unsigned Length;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000513 if (getCurFunctionDecl())
514 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattner8f978d52008-01-12 19:32:28 +0000515 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000516 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattner1423ea42008-01-12 18:39:25 +0000517
Chris Lattner8f978d52008-01-12 19:32:28 +0000518 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000519 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000520 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerd9f69102008-08-10 01:53:14 +0000521 return new PredefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000522}
523
Steve Narofff69936d2007-09-16 03:34:24 +0000524Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000525 llvm::SmallString<16> CharBuffer;
526 CharBuffer.resize(Tok.getLength());
527 const char *ThisTokBegin = &CharBuffer[0];
528 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
529
530 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
531 Tok.getLocation(), PP);
532 if (Literal.hadError())
533 return ExprResult(true);
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000534
535 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
536
Chris Lattnerc250aae2008-06-07 22:35:38 +0000537 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
538 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000539}
540
Steve Narofff69936d2007-09-16 03:34:24 +0000541Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000542 // fast path for a single digit (which is quite common). A single digit
543 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
544 if (Tok.getLength() == 1) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000545 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000546
Chris Lattner98be4942008-03-05 18:54:05 +0000547 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000548 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +0000549 Context.IntTy,
550 Tok.getLocation()));
551 }
552 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000553 // Add padding so that NumericLiteralParser can overread by one character.
554 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000555 const char *ThisTokBegin = &IntegerBuffer[0];
556
557 // Get the spelling of the token, which eliminates trigraphs, etc.
558 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner28997ec2008-09-30 20:51:14 +0000559
Reid Spencer5f016e22007-07-11 17:01:13 +0000560 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
561 Tok.getLocation(), PP);
562 if (Literal.hadError)
563 return ExprResult(true);
564
Chris Lattner5d661452007-08-26 03:42:43 +0000565 Expr *Res;
566
567 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000568 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000569 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000570 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000571 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000572 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000573 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000574 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000575
576 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
577
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000578 // isExact will be set by GetFloatValue().
579 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000580 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000581 Ty, Tok.getLocation());
582
Chris Lattner5d661452007-08-26 03:42:43 +0000583 } else if (!Literal.isIntegerLiteral()) {
584 return ExprResult(true);
585 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000586 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000587
Neil Boothb9449512007-08-29 22:00:19 +0000588 // long long is a C99 feature.
589 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000590 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000591 Diag(Tok.getLocation(), diag::ext_longlong);
592
Reid Spencer5f016e22007-07-11 17:01:13 +0000593 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000594 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000595
596 if (Literal.GetIntegerValue(ResultVal)) {
597 // If this value didn't fit into uintmax_t, warn and force to ull.
598 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000599 Ty = Context.UnsignedLongLongTy;
600 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000601 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 } else {
603 // If this value fits into a ULL, try to figure out what else it fits into
604 // according to the rules of C99 6.4.4.1p5.
605
606 // Octal, Hexadecimal, and integers with a U suffix are allowed to
607 // be an unsigned int.
608 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
609
610 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000611 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000612 if (!Literal.isLong && !Literal.isLongLong) {
613 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000614 unsigned IntSize = Context.Target.getIntWidth();
615
Reid Spencer5f016e22007-07-11 17:01:13 +0000616 // Does it fit in a unsigned int?
617 if (ResultVal.isIntN(IntSize)) {
618 // Does it fit in a signed int?
619 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000620 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000621 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000622 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000623 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000624 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000625 }
626
627 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000628 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000629 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000630
631 // Does it fit in a unsigned long?
632 if (ResultVal.isIntN(LongSize)) {
633 // Does it fit in a signed long?
634 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000635 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000636 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000637 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000638 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000639 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 }
641
642 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000643 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000644 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000645
646 // Does it fit in a unsigned long long?
647 if (ResultVal.isIntN(LongLongSize)) {
648 // Does it fit in a signed long long?
649 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000650 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000651 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000652 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000653 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000654 }
655 }
656
657 // If we still couldn't decide a type, we probably have something that
658 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000659 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000660 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000661 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000662 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000663 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000664
665 if (ResultVal.getBitWidth() != Width)
666 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000667 }
668
Chris Lattnerf0467b32008-04-02 04:24:33 +0000669 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000670 }
Chris Lattner5d661452007-08-26 03:42:43 +0000671
672 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
673 if (Literal.isImaginary)
674 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
675
676 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000677}
678
Steve Narofff69936d2007-09-16 03:34:24 +0000679Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000680 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000681 Expr *E = (Expr *)Val;
682 assert((E != 0) && "ActOnParenExpr() missing expr");
683 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +0000684}
685
686/// The UsualUnaryConversions() function is *not* called by this routine.
687/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl05189992008-11-11 17:56:53 +0000688bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
689 SourceLocation OpLoc,
690 const SourceRange &ExprRange,
691 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000692 // C99 6.5.3.4p1:
693 if (isa<FunctionType>(exprType) && isSizeof)
694 // alignof(function) is allowed.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000695 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Reid Spencer5f016e22007-07-11 17:01:13 +0000696 else if (exprType->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000697 Diag(OpLoc, diag::ext_sizeof_void_type)
698 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
699 else if (exprType->isIncompleteType())
700 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
701 diag::err_alignof_incomplete_type)
702 << exprType.getAsString() << ExprRange;
Sebastian Redl05189992008-11-11 17:56:53 +0000703
704 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000705}
706
Sebastian Redl05189992008-11-11 17:56:53 +0000707/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
708/// the same for @c alignof and @c __alignof
709/// Note that the ArgRange is invalid if isType is false.
710Action::ExprResult
711Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
712 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000713 // If error parsing type, ignore.
Sebastian Redl05189992008-11-11 17:56:53 +0000714 if (TyOrEx == 0) return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000715
Sebastian Redl05189992008-11-11 17:56:53 +0000716 QualType ArgTy;
717 SourceRange Range;
718 if (isType) {
719 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
720 Range = ArgRange;
721 } else {
722 // Get the end location.
723 Expr *ArgEx = (Expr *)TyOrEx;
724 Range = ArgEx->getSourceRange();
725 ArgTy = ArgEx->getType();
726 }
727
728 // Verify that the operand is valid.
729 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 return true;
Sebastian Redl05189992008-11-11 17:56:53 +0000731
732 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
733 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
734 OpLoc, Range.getEnd());
Reid Spencer5f016e22007-07-11 17:01:13 +0000735}
736
Chris Lattner5d794252007-08-24 21:41:10 +0000737QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000738 DefaultFunctionArrayConversion(V);
739
Chris Lattnercc26ed72007-08-26 05:39:26 +0000740 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000741 if (const ComplexType *CT = V->getType()->getAsComplexType())
742 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000743
744 // Otherwise they pass through real integer and floating point types here.
745 if (V->getType()->isArithmeticType())
746 return V->getType();
747
748 // Reject anything else.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000749 Diag(Loc, diag::err_realimag_invalid_type) << V->getType().getAsString();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000750 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000751}
752
753
Reid Spencer5f016e22007-07-11 17:01:13 +0000754
Steve Narofff69936d2007-09-16 03:34:24 +0000755Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 tok::TokenKind Kind,
757 ExprTy *Input) {
758 UnaryOperator::Opcode Opc;
759 switch (Kind) {
760 default: assert(0 && "Unknown unary op!");
761 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
762 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
763 }
764 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
765 if (result.isNull())
766 return true;
767 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
768}
769
770Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000771ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000772 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000773 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000774
775 // Perform default conversions.
776 DefaultFunctionArrayConversion(LHSExp);
777 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000778
Chris Lattner12d9ff62007-07-16 00:14:47 +0000779 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000780
Reid Spencer5f016e22007-07-11 17:01:13 +0000781 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000782 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000783 // in the subscript position. As a result, we need to derive the array base
784 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000785 Expr *BaseExpr, *IndexExpr;
786 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000787 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000788 BaseExpr = LHSExp;
789 IndexExpr = RHSExp;
790 // FIXME: need to deal with const...
791 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000792 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000793 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000794 BaseExpr = RHSExp;
795 IndexExpr = LHSExp;
796 // FIXME: need to deal with const...
797 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000798 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
799 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000800 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000801
802 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +0000803 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
804 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000805 return Diag(LLoc, diag::err_ext_vector_component_access)
806 << SourceRange(LLoc, RLoc);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000807 // FIXME: need to deal with const...
808 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000809 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000810 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
811 << RHSExp->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +0000812 }
813 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000814 if (!IndexExpr->getType()->isIntegerType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000815 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
816 << IndexExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +0000817
Chris Lattner12d9ff62007-07-16 00:14:47 +0000818 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
819 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +0000820 // void (*)(int)) and pointers to incomplete types. Functions are not
821 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000822 if (!ResultType->isObjectType())
823 return Diag(BaseExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000824 diag::err_typecheck_subscript_not_object)
825 << BaseExpr->getType().getAsString() << BaseExpr->getSourceRange();
Chris Lattner12d9ff62007-07-16 00:14:47 +0000826
827 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000828}
829
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000830QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +0000831CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000832 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +0000833 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +0000834
835 // This flag determines whether or not the component is to be treated as a
836 // special name, or a regular GLSL-style component access.
837 bool SpecialComponent = false;
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000838
839 // The vector accessor can't exceed the number of elements.
840 const char *compStr = CompName.getName();
841 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000842 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
843 << baseType.getAsString() << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000844 return QualType();
845 }
Nate Begeman8a997642008-05-09 06:41:27 +0000846
847 // Check that we've found one of the special components, or that the component
848 // names must come from the same set.
849 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
850 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
851 SpecialComponent = true;
852 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +0000853 do
854 compStr++;
855 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
856 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
857 do
858 compStr++;
859 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
860 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
861 do
862 compStr++;
863 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
864 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000865
Nate Begeman8a997642008-05-09 06:41:27 +0000866 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000867 // We didn't get to the end of the string. This means the component names
868 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000869 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
870 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000871 return QualType();
872 }
873 // Each component accessor can't exceed the vector type.
874 compStr = CompName.getName();
875 while (*compStr) {
876 if (vecType->isAccessorWithinNumElements(*compStr))
877 compStr++;
878 else
879 break;
880 }
Nate Begeman8a997642008-05-09 06:41:27 +0000881 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000882 // We didn't get to the end of the string. This means a component accessor
883 // exceeds the number of elements in the vector.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000884 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
885 << baseType.getAsString() << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000886 return QualType();
887 }
Nate Begeman8a997642008-05-09 06:41:27 +0000888
889 // If we have a special component name, verify that the current vector length
890 // is an even number, since all special component names return exactly half
891 // the elements.
892 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000893 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
894 << baseType.getAsString() << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +0000895 return QualType();
896 }
897
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000898 // The component accessor looks fine - now we need to compute the actual type.
899 // The vector type is implied by the component accessor. For example,
900 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +0000901 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
902 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner3c73c412008-11-19 08:23:25 +0000903 : CompName.getLength();
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000904 if (CompSize == 1)
905 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000906
Nate Begeman213541a2008-04-18 23:10:10 +0000907 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +0000908 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +0000909 // diagostics look bad. We want extended vector types to appear built-in.
910 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
911 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
912 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +0000913 }
914 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000915}
916
Daniel Dunbar2307d312008-09-03 01:05:41 +0000917/// constructSetterName - Return the setter name for the given
918/// identifier, i.e. "set" + Name where the initial character of Name
919/// has been capitalized.
920// FIXME: Merge with same routine in Parser. But where should this
921// live?
922static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
923 const IdentifierInfo *Name) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000924 llvm::SmallString<100> SelectorName;
925 SelectorName += "set";
926 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
Daniel Dunbar2307d312008-09-03 01:05:41 +0000927 SelectorName[3] = toupper(SelectorName[3]);
Chris Lattner3c73c412008-11-19 08:23:25 +0000928 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
Daniel Dunbar2307d312008-09-03 01:05:41 +0000929}
930
Reid Spencer5f016e22007-07-11 17:01:13 +0000931Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000932ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000933 tok::TokenKind OpKind, SourceLocation MemberLoc,
934 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000935 Expr *BaseExpr = static_cast<Expr *>(Base);
936 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +0000937
938 // Perform default conversions.
939 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000940
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000941 QualType BaseType = BaseExpr->getType();
942 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000943
Chris Lattner68a057b2008-07-21 04:36:39 +0000944 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
945 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +0000946 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000947 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000948 BaseType = PT->getPointeeType();
949 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000950 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
951 << BaseType.getAsString() << BaseExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +0000952 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000953
Chris Lattner68a057b2008-07-21 04:36:39 +0000954 // Handle field access to simple records. This also handles access to fields
955 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +0000956 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000957 RecordDecl *RDecl = RTy->getDecl();
958 if (RTy->isIncompleteType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000959 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
960 << RDecl->getName() << BaseExpr->getSourceRange();
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000961 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000962 FieldDecl *MemberDecl = RDecl->getMember(&Member);
963 if (!MemberDecl)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000964 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner3c73c412008-11-19 08:23:25 +0000965 << &Member << BaseExpr->getSourceRange();
Eli Friedman51019072008-02-06 22:48:16 +0000966
967 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedman64ec0cc2008-02-07 05:24:51 +0000968 // FIXME: Handle address space modifiers
Eli Friedman51019072008-02-06 22:48:16 +0000969 QualType MemberType = MemberDecl->getType();
970 unsigned combinedQualifiers =
Chris Lattnerf46699c2008-02-20 20:55:12 +0000971 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Sebastian Redla11f42f2008-11-17 23:24:37 +0000972 if (CXXFieldDecl *CXXMember = dyn_cast<CXXFieldDecl>(MemberDecl)) {
973 if (CXXMember->isMutable())
974 combinedQualifiers &= ~QualType::Const;
975 }
Eli Friedman51019072008-02-06 22:48:16 +0000976 MemberType = MemberType.getQualifiedType(combinedQualifiers);
977
Chris Lattner68a057b2008-07-21 04:36:39 +0000978 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman51019072008-02-06 22:48:16 +0000979 MemberLoc, MemberType);
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000980 }
981
Chris Lattnera38e6b12008-07-21 04:59:05 +0000982 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
983 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +0000984 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
985 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000986 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000987 OpKind == tok::arrow);
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000988 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattner3c73c412008-11-19 08:23:25 +0000989 << IFTy->getDecl()->getName() << &Member
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000990 << BaseExpr->getSourceRange();
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000991 }
992
Chris Lattnera38e6b12008-07-21 04:59:05 +0000993 // Handle Objective-C property access, which is "Obj.property" where Obj is a
994 // pointer to a (potentially qualified) interface type.
995 const PointerType *PTy;
996 const ObjCInterfaceType *IFTy;
997 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
998 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
999 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001000
Daniel Dunbar2307d312008-09-03 01:05:41 +00001001 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +00001002 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1003 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1004
Daniel Dunbar2307d312008-09-03 01:05:41 +00001005 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00001006 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1007 E = IFTy->qual_end(); I != E; ++I)
1008 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1009 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +00001010
1011 // If that failed, look for an "implicit" property by seeing if the nullary
1012 // selector is implemented.
1013
1014 // FIXME: The logic for looking up nullary and unary selectors should be
1015 // shared with the code in ActOnInstanceMessage.
1016
1017 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1018 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1019
1020 // If this reference is in an @implementation, check for 'private' methods.
1021 if (!Getter)
1022 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1023 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1024 if (ObjCImplementationDecl *ImpDecl =
1025 ObjCImplementations[ClassDecl->getIdentifier()])
1026 Getter = ImpDecl->getInstanceMethod(Sel);
1027
Steve Naroff7692ed62008-10-22 19:16:27 +00001028 // Look through local category implementations associated with the class.
1029 if (!Getter) {
1030 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1031 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1032 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1033 }
1034 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001035 if (Getter) {
1036 // If we found a getter then this may be a valid dot-reference, we
1037 // need to also look for the matching setter.
1038 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1039 &Member);
1040 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1041 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1042
1043 if (!Setter) {
1044 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1045 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1046 if (ObjCImplementationDecl *ImpDecl =
1047 ObjCImplementations[ClassDecl->getIdentifier()])
1048 Setter = ImpDecl->getInstanceMethod(SetterSel);
1049 }
1050
1051 // FIXME: There are some issues here. First, we are not
1052 // diagnosing accesses to read-only properties because we do not
1053 // know if this is a getter or setter yet. Second, we are
1054 // checking that the type of the setter matches the type we
1055 // expect.
1056 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1057 MemberLoc, BaseExpr);
1058 }
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001059 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001060 // Handle properties on qualified "id" protocols.
1061 const ObjCQualifiedIdType *QIdTy;
1062 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1063 // Check protocols on qualified interfaces.
1064 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1065 E = QIdTy->qual_end(); I != E; ++I)
1066 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1067 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1068 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001069 // Handle 'field access' to vectors, such as 'V.xx'.
1070 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1071 // Component access limited to variables (reject vec4.rg.g).
1072 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1073 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001074 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1075 << BaseExpr->getSourceRange();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001076 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1077 if (ret.isNull())
1078 return true;
1079 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1080 }
1081
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001082 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
1083 << BaseType.getAsString() << BaseExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001084}
1085
Steve Narofff69936d2007-09-16 03:34:24 +00001086/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001087/// This provides the location of the left/right parens and a list of comma
1088/// locations.
1089Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001090ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +00001091 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +00001092 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +00001093 Expr *Fn = static_cast<Expr *>(fn);
1094 Expr **Args = reinterpret_cast<Expr**>(args);
1095 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001096 FunctionDecl *FDecl = NULL;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001097 OverloadedFunctionDecl *Ovl = NULL;
1098
1099 // If we're directly calling a function or a set of overloaded
1100 // functions, get the appropriate declaration.
1101 {
1102 DeclRefExpr *DRExpr = NULL;
1103 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1104 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1105 else
1106 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1107
1108 if (DRExpr) {
1109 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1110 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1111 }
1112 }
1113
1114 // If we have a set of overloaded functions, perform overload
1115 // resolution to pick the function.
1116 if (Ovl) {
1117 OverloadCandidateSet CandidateSet;
1118 OverloadCandidateSet::iterator Best;
1119 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
1120 switch (BestViableFunction(CandidateSet, Best)) {
1121 case OR_Success:
1122 {
1123 // Success! Let the remainder of this function build a call to
1124 // the function selected by overload resolution.
1125 FDecl = Best->Function;
1126 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1127 Fn->getSourceRange().getBegin());
1128 delete Fn;
1129 Fn = NewFn;
1130 }
1131 break;
1132
1133 case OR_No_Viable_Function:
1134 if (CandidateSet.empty())
1135 Diag(Fn->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001136 diag::err_ovl_no_viable_function_in_call)
1137 << Ovl->getName() << Fn->getSourceRange();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001138 else {
1139 Diag(Fn->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001140 diag::err_ovl_no_viable_function_in_call_with_cands)
1141 << Ovl->getName() << Fn->getSourceRange();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001142 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1143 }
1144 return true;
1145
1146 case OR_Ambiguous:
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001147 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
1148 << Ovl->getName() << Fn->getSourceRange();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001149 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1150 return true;
1151 }
1152 }
Chris Lattner04421082008-04-08 04:40:51 +00001153
1154 // Promote the function operand.
1155 UsualUnaryConversions(Fn);
1156
Chris Lattner925e60d2007-12-28 05:29:59 +00001157 // Make the call expr early, before semantic checks. This guarantees cleanup
1158 // of arguments and function on error.
Chris Lattner8123a952008-04-10 02:22:51 +00001159 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001160 Context.BoolTy, RParenLoc));
Steve Naroffdd972f22008-09-05 22:11:13 +00001161 const FunctionType *FuncT;
1162 if (!Fn->getType()->isBlockPointerType()) {
1163 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1164 // have type pointer to function".
1165 const PointerType *PT = Fn->getType()->getAsPointerType();
1166 if (PT == 0)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001167 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
1168 << Fn->getSourceRange();
Steve Naroffdd972f22008-09-05 22:11:13 +00001169 FuncT = PT->getPointeeType()->getAsFunctionType();
1170 } else { // This is a block call.
1171 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1172 getAsFunctionType();
1173 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001174 if (FuncT == 0)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001175 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
1176 << Fn->getSourceRange();
Chris Lattner925e60d2007-12-28 05:29:59 +00001177
1178 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001179 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001180
Chris Lattner925e60d2007-12-28 05:29:59 +00001181 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001182 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1183 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +00001184 unsigned NumArgsInProto = Proto->getNumArgs();
1185 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001186
Chris Lattner04421082008-04-08 04:40:51 +00001187 // If too few arguments are available (and we don't have default
1188 // arguments for the remaining parameters), don't make the call.
1189 if (NumArgs < NumArgsInProto) {
Chris Lattner8123a952008-04-10 02:22:51 +00001190 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner04421082008-04-08 04:40:51 +00001191 // Use default arguments for missing arguments
1192 NumArgsToCheck = NumArgsInProto;
Chris Lattner8123a952008-04-10 02:22:51 +00001193 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner04421082008-04-08 04:40:51 +00001194 } else
Steve Naroffdd972f22008-09-05 22:11:13 +00001195 return Diag(RParenLoc,
1196 !Fn->getType()->isBlockPointerType()
1197 ? diag::err_typecheck_call_too_few_args
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001198 : diag::err_typecheck_block_too_few_args)
1199 << Fn->getSourceRange();
Chris Lattner04421082008-04-08 04:40:51 +00001200 }
1201
Chris Lattner925e60d2007-12-28 05:29:59 +00001202 // If too many are passed and not variadic, error on the extras and drop
1203 // them.
1204 if (NumArgs > NumArgsInProto) {
1205 if (!Proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +00001206 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffdd972f22008-09-05 22:11:13 +00001207 !Fn->getType()->isBlockPointerType()
1208 ? diag::err_typecheck_call_too_many_args
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001209 : diag::err_typecheck_block_too_many_args)
1210 << Fn->getSourceRange()
1211 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1212 Args[NumArgs-1]->getLocEnd());
Chris Lattner925e60d2007-12-28 05:29:59 +00001213 // This deletes the extra arguments.
1214 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +00001215 }
1216 NumArgsToCheck = NumArgsInProto;
1217 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001218
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +00001220 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00001221 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner04421082008-04-08 04:40:51 +00001222
1223 Expr *Arg;
1224 if (i < NumArgs)
1225 Arg = Args[i];
1226 else
1227 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner5cf216b2008-01-04 18:04:52 +00001228 QualType ArgType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +00001229
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001230 // Pass the argument.
1231 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00001232 return true;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001233
1234 TheCall->setArg(i, Arg);
Reid Spencer5f016e22007-07-11 17:01:13 +00001235 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001236
1237 // If this is a variadic call, handle args passed through "...".
1238 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +00001239 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-12-28 05:29:59 +00001240 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1241 Expr *Arg = Args[i];
1242 DefaultArgumentPromotion(Arg);
1243 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001244 }
Steve Naroffb291ab62007-08-28 23:30:39 +00001245 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001246 } else {
1247 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1248
Steve Naroffb291ab62007-08-28 23:30:39 +00001249 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001250 for (unsigned i = 0; i != NumArgs; i++) {
1251 Expr *Arg = Args[i];
1252 DefaultArgumentPromotion(Arg);
1253 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001254 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001255 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001256
Chris Lattner59907c42007-08-10 20:18:51 +00001257 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001258 if (FDecl)
1259 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001260
Chris Lattner925e60d2007-12-28 05:29:59 +00001261 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001262}
1263
1264Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001265ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +00001266 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001267 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001268 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001269 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001270 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +00001271 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +00001272
Eli Friedman6223c222008-05-20 05:22:08 +00001273 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001274 if (literalType->isVariableArrayType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001275 return Diag(LParenLoc, diag::err_variable_object_no_init)
1276 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman6223c222008-05-20 05:22:08 +00001277 } else if (literalType->isIncompleteType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001278 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
1279 << literalType.getAsString()
1280 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman6223c222008-05-20 05:22:08 +00001281 }
1282
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001283 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
1284 "temporary"))
Steve Naroff58d18212008-01-09 20:58:06 +00001285 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +00001286
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001287 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffe9b12192008-01-14 18:19:28 +00001288 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001289 if (CheckForConstantInitializer(literalExpr, literalType))
1290 return true;
1291 }
Chris Lattner220ad7c2008-10-26 23:35:51 +00001292 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1293 isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001294}
1295
1296Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001297ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattner220ad7c2008-10-26 23:35:51 +00001298 InitListDesignations &Designators,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001299 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +00001300 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001301
Steve Naroff08d92e42007-09-15 18:49:24 +00001302 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001303 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001304
Chris Lattner418f6c72008-10-26 23:43:26 +00001305 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1306 Designators.hasAnyDesignators());
Chris Lattnerf0467b32008-04-02 04:24:33 +00001307 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1308 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001309}
1310
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001311/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001312bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001313 UsualUnaryConversions(castExpr);
1314
1315 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1316 // type needs to be scalar.
1317 if (castType->isVoidType()) {
1318 // Cast to void allows any expr type.
1319 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1320 // GCC struct/union extension: allow cast to self.
1321 if (Context.getCanonicalType(castType) !=
1322 Context.getCanonicalType(castExpr->getType()) ||
1323 (!castType->isStructureType() && !castType->isUnionType())) {
1324 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001325 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
1326 << castType.getAsString() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001327 }
1328
1329 // accept this, but emit an ext-warn.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001330 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
1331 << castType.getAsString() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001332 } else if (!castExpr->getType()->isScalarType() &&
1333 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001334 return Diag(castExpr->getLocStart(),
1335 diag::err_typecheck_expect_scalar_operand)
1336 << castExpr->getType().getAsString() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001337 } else if (castExpr->getType()->isVectorType()) {
1338 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1339 return true;
1340 } else if (castType->isVectorType()) {
1341 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1342 return true;
1343 }
1344 return false;
1345}
1346
Chris Lattnerfe23e212007-12-20 00:44:32 +00001347bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00001348 assert(VectorTy->isVectorType() && "Not a vector type!");
1349
1350 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00001351 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00001352 return Diag(R.getBegin(),
1353 Ty->isVectorType() ?
1354 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001355 diag::err_invalid_conversion_between_vector_and_integer)
1356 << VectorTy.getAsString() << Ty.getAsString() << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00001357 } else
1358 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001359 diag::err_invalid_conversion_between_vector_and_scalar)
1360 << VectorTy.getAsString() << Ty.getAsString() << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00001361
1362 return false;
1363}
1364
Steve Naroff4aa88f82007-07-19 01:06:55 +00001365Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001366ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +00001367 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +00001368 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00001369
1370 Expr *castExpr = static_cast<Expr*>(Op);
1371 QualType castType = QualType::getFromOpaquePtr(Ty);
1372
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001373 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1374 return true;
Steve Naroffb2f9e512008-11-03 23:29:32 +00001375 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001376}
1377
Chris Lattnera21ddb32007-11-26 01:40:58 +00001378/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1379/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00001380inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00001381 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001382 UsualUnaryConversions(cond);
1383 UsualUnaryConversions(lex);
1384 UsualUnaryConversions(rex);
1385 QualType condT = cond->getType();
1386 QualType lexT = lex->getType();
1387 QualType rexT = rex->getType();
1388
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +00001390 if (!condT->isScalarType()) { // C99 6.5.15p2
1391 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1392 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 return QualType();
1394 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001395
1396 // Now check the two expressions.
1397
1398 // If both operands have arithmetic type, do the usual arithmetic conversions
1399 // to find a common type: C99 6.5.15p3,5.
1400 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00001401 UsualArithmeticConversions(lex, rex);
1402 return lex->getType();
1403 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001404
1405 // If both operands are the same structure or union type, the result is that
1406 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001407 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00001408 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00001409 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00001410 // "If both the operands have structure or union type, the result has
1411 // that type." This implies that CV qualifiers are dropped.
1412 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001413 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001414
1415 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00001416 // The following || allows only one side to be void (a GCC-ism).
1417 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00001418 if (!lexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001419 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
1420 << rex->getSourceRange();
Steve Naroffe701c0a2008-05-12 21:44:38 +00001421 if (!rexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001422 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
1423 << lex->getSourceRange();
Eli Friedman0e724012008-06-04 19:47:51 +00001424 ImpCastExprToType(lex, Context.VoidTy);
1425 ImpCastExprToType(rex, Context.VoidTy);
1426 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00001427 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00001428 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1429 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001430 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1431 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001432 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001433 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001434 return lexT;
1435 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001436 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1437 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001438 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001439 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001440 return rexT;
1441 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00001442 // Handle the case where both operands are pointers before we handle null
1443 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001444 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1445 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1446 // get the "pointed to" types
1447 QualType lhptee = LHSPT->getPointeeType();
1448 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001449
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001450 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1451 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00001452 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001453 // Figure out necessary qualifiers (C99 6.5.15p6)
1454 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001455 QualType destType = Context.getPointerType(destPointee);
1456 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1457 ImpCastExprToType(rex, destType); // promote to void*
1458 return destType;
1459 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00001460 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001461 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001462 QualType destType = Context.getPointerType(destPointee);
1463 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1464 ImpCastExprToType(rex, destType); // promote to void*
1465 return destType;
1466 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001467
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001468 QualType compositeType = lexT;
1469
1470 // If either type is an Objective-C object type then check
1471 // compatibility according to Objective-C.
1472 if (Context.isObjCObjectPointerType(lexT) ||
1473 Context.isObjCObjectPointerType(rexT)) {
1474 // If both operands are interfaces and either operand can be
1475 // assigned to the other, use that type as the composite
1476 // type. This allows
1477 // xxx ? (A*) a : (B*) b
1478 // where B is a subclass of A.
1479 //
1480 // Additionally, as for assignment, if either type is 'id'
1481 // allow silent coercion. Finally, if the types are
1482 // incompatible then make sure to use 'id' as the composite
1483 // type so the result is acceptable for sending messages to.
1484
1485 // FIXME: This code should not be localized to here. Also this
1486 // should use a compatible check instead of abusing the
1487 // canAssignObjCInterfaces code.
1488 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1489 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1490 if (LHSIface && RHSIface &&
1491 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1492 compositeType = lexT;
1493 } else if (LHSIface && RHSIface &&
1494 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1495 compositeType = rexT;
1496 } else if (Context.isObjCIdType(lhptee) ||
1497 Context.isObjCIdType(rhptee)) {
1498 // FIXME: This code looks wrong, because isObjCIdType checks
1499 // the struct but getObjCIdType returns the pointer to
1500 // struct. This is horrible and should be fixed.
1501 compositeType = Context.getObjCIdType();
1502 } else {
1503 QualType incompatTy = Context.getObjCIdType();
1504 ImpCastExprToType(lex, incompatTy);
1505 ImpCastExprToType(rex, incompatTy);
1506 return incompatTy;
1507 }
1508 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1509 rhptee.getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001510 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
1511 << lexT.getAsString() << rexT.getAsString()
1512 << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001513 // In this situation, we assume void* type. No especially good
1514 // reason, but this is what gcc does, and we do have to pick
1515 // to get a consistent AST.
1516 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00001517 ImpCastExprToType(lex, incompatTy);
1518 ImpCastExprToType(rex, incompatTy);
1519 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001520 }
1521 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001522 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1523 // differently qualified versions of compatible types, the result type is
1524 // a pointer to an appropriately qualified version of the *composite*
1525 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00001526 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00001527 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00001528 ImpCastExprToType(lex, compositeType);
1529 ImpCastExprToType(rex, compositeType);
1530 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001531 }
1532 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001533 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1534 // evaluates to "struct objc_object *" (and is handled above when comparing
1535 // id with statically typed objects).
1536 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1537 // GCC allows qualified id and any Objective-C type to devolve to
1538 // id. Currently localizing to here until clear this should be
1539 // part of ObjCQualifiedIdTypesAreCompatible.
1540 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1541 (lexT->isObjCQualifiedIdType() &&
1542 Context.isObjCObjectPointerType(rexT)) ||
1543 (rexT->isObjCQualifiedIdType() &&
1544 Context.isObjCObjectPointerType(lexT))) {
1545 // FIXME: This is not the correct composite type. This only
1546 // happens to work because id can more or less be used anywhere,
1547 // however this may change the type of method sends.
1548 // FIXME: gcc adds some type-checking of the arguments and emits
1549 // (confusing) incompatible comparison warnings in some
1550 // cases. Investigate.
1551 QualType compositeType = Context.getObjCIdType();
1552 ImpCastExprToType(lex, compositeType);
1553 ImpCastExprToType(rex, compositeType);
1554 return compositeType;
1555 }
1556 }
1557
Steve Naroff61f40a22008-09-10 19:17:48 +00001558 // Selection between block pointer types is ok as long as they are the same.
1559 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1560 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1561 return lexT;
1562
Chris Lattner70d67a92008-01-06 22:42:25 +00001563 // Otherwise, the operands are not compatible.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001564 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
1565 << lexT.getAsString() << rexT.getAsString()
1566 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 return QualType();
1568}
1569
Steve Narofff69936d2007-09-16 03:34:24 +00001570/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00001571/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00001572Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 SourceLocation ColonLoc,
1574 ExprTy *Cond, ExprTy *LHS,
1575 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00001576 Expr *CondExpr = (Expr *) Cond;
1577 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001578
1579 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1580 // was the condition.
1581 bool isLHSNull = LHSExpr == 0;
1582 if (isLHSNull)
1583 LHSExpr = CondExpr;
1584
Chris Lattner26824902007-07-16 21:39:03 +00001585 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1586 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 if (result.isNull())
1588 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001589 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1590 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001591}
1592
Reid Spencer5f016e22007-07-11 17:01:13 +00001593
1594// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1595// being closely modeled after the C99 spec:-). The odd characteristic of this
1596// routine is it effectively iqnores the qualifiers on the top level pointee.
1597// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1598// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001599Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001600Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1601 QualType lhptee, rhptee;
1602
1603 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001604 lhptee = lhsType->getAsPointerType()->getPointeeType();
1605 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001606
1607 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00001608 lhptee = Context.getCanonicalType(lhptee);
1609 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00001610
Chris Lattner5cf216b2008-01-04 18:04:52 +00001611 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001612
1613 // C99 6.5.16.1p1: This following citation is common to constraints
1614 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1615 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00001616 // FIXME: Handle ASQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00001617 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00001618 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001619
1620 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1621 // incomplete type and the other is a pointer to a qualified or unqualified
1622 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001623 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001624 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001625 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001626
1627 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001628 assert(rhptee->isFunctionType());
1629 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001630 }
1631
1632 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001633 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001634 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001635
1636 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001637 assert(lhptee->isFunctionType());
1638 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001639 }
Eli Friedman3d815e72008-08-22 00:56:42 +00001640
1641 // Check for ObjC interfaces
1642 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1643 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1644 if (LHSIface && RHSIface &&
1645 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1646 return ConvTy;
1647
1648 // ID acts sort of like void* for ObjC interfaces
1649 if (LHSIface && Context.isObjCIdType(rhptee))
1650 return ConvTy;
1651 if (RHSIface && Context.isObjCIdType(lhptee))
1652 return ConvTy;
1653
Reid Spencer5f016e22007-07-11 17:01:13 +00001654 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1655 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001656 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1657 rhptee.getUnqualifiedType()))
1658 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00001659 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001660}
1661
Steve Naroff1c7d0672008-09-04 15:10:53 +00001662/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1663/// block pointer types are compatible or whether a block and normal pointer
1664/// are compatible. It is more restrict than comparing two function pointer
1665// types.
1666Sema::AssignConvertType
1667Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1668 QualType rhsType) {
1669 QualType lhptee, rhptee;
1670
1671 // get the "pointed to" type (ignoring qualifiers at the top level)
1672 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1673 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1674
1675 // make sure we operate on the canonical type
1676 lhptee = Context.getCanonicalType(lhptee);
1677 rhptee = Context.getCanonicalType(rhptee);
1678
1679 AssignConvertType ConvTy = Compatible;
1680
1681 // For blocks we enforce that qualifiers are identical.
1682 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1683 ConvTy = CompatiblePointerDiscardsQualifiers;
1684
1685 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1686 return IncompatibleBlockPointer;
1687 return ConvTy;
1688}
1689
Reid Spencer5f016e22007-07-11 17:01:13 +00001690/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1691/// has code to accommodate several GCC extensions when type checking
1692/// pointers. Here are some objectionable examples that GCC considers warnings:
1693///
1694/// int a, *pint;
1695/// short *pshort;
1696/// struct foo *pfoo;
1697///
1698/// pint = pshort; // warning: assignment from incompatible pointer type
1699/// a = pint; // warning: assignment makes integer from pointer without a cast
1700/// pint = a; // warning: assignment makes pointer from integer without a cast
1701/// pint = pfoo; // warning: assignment from incompatible pointer type
1702///
1703/// As a result, the code for dealing with pointers is more complex than the
1704/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00001705///
Chris Lattner5cf216b2008-01-04 18:04:52 +00001706Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001707Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00001708 // Get canonical types. We're not formatting these types, just comparing
1709 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001710 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1711 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001712
1713 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00001714 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00001715
Douglas Gregor9d293df2008-10-28 00:22:11 +00001716 // If the left-hand side is a reference type, then we are in a
1717 // (rare!) case where we've allowed the use of references in C,
1718 // e.g., as a parameter type in a built-in function. In this case,
1719 // just make sure that the type referenced is compatible with the
1720 // right-hand side type. The caller is responsible for adjusting
1721 // lhsType so that the resulting expression does not have reference
1722 // type.
1723 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
1724 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001725 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001726 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001727 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001728
Chris Lattnereca7be62008-04-07 05:30:13 +00001729 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1730 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001731 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00001732 // Relax integer conversions like we do for pointers below.
1733 if (rhsType->isIntegerType())
1734 return IntToPointer;
1735 if (lhsType->isIntegerType())
1736 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00001737 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001738 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00001739
Nate Begemanbe2341d2008-07-14 18:02:46 +00001740 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001741 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00001742 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1743 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00001744 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001745
Nate Begemanbe2341d2008-07-14 18:02:46 +00001746 // If we are allowing lax vector conversions, and LHS and RHS are both
1747 // vectors, the total size only needs to be the same. This is a bitcast;
1748 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00001749 if (getLangOptions().LaxVectorConversions &&
1750 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001751 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1752 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00001753 }
1754 return Incompatible;
1755 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001756
Chris Lattnere8b3e962008-01-04 23:32:24 +00001757 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001759
Chris Lattner78eca282008-04-07 06:49:41 +00001760 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001761 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001762 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001763
Chris Lattner78eca282008-04-07 06:49:41 +00001764 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001765 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001766
Steve Naroffb4406862008-09-29 18:10:17 +00001767 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00001768 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff1c7d0672008-09-04 15:10:53 +00001769 return BlockVoidPointer;
Steve Naroffb4406862008-09-29 18:10:17 +00001770
1771 // Treat block pointers as objects.
1772 if (getLangOptions().ObjC1 &&
1773 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1774 return Compatible;
1775 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001776 return Incompatible;
1777 }
1778
1779 if (isa<BlockPointerType>(lhsType)) {
1780 if (rhsType->isIntegerType())
1781 return IntToPointer;
1782
Steve Naroffb4406862008-09-29 18:10:17 +00001783 // Treat block pointers as objects.
1784 if (getLangOptions().ObjC1 &&
1785 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1786 return Compatible;
1787
Steve Naroff1c7d0672008-09-04 15:10:53 +00001788 if (rhsType->isBlockPointerType())
1789 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1790
1791 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1792 if (RHSPT->getPointeeType()->isVoidType())
1793 return BlockVoidPointer;
1794 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00001795 return Incompatible;
1796 }
1797
Chris Lattner78eca282008-04-07 06:49:41 +00001798 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001799 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001800 if (lhsType == Context.BoolTy)
1801 return Compatible;
1802
1803 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001804 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00001805
Chris Lattner78eca282008-04-07 06:49:41 +00001806 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001807 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001808
1809 if (isa<BlockPointerType>(lhsType) &&
1810 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1811 return BlockVoidPointer;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001812 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001813 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001814
Chris Lattnerfc144e22008-01-04 23:18:45 +00001815 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00001816 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001817 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001818 }
1819 return Incompatible;
1820}
1821
Chris Lattner5cf216b2008-01-04 18:04:52 +00001822Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001823Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001824 if (getLangOptions().CPlusPlus) {
1825 if (!lhsType->isRecordType()) {
1826 // C++ 5.17p3: If the left operand is not of class type, the
1827 // expression is implicitly converted (C++ 4) to the
1828 // cv-unqualified type of the left operand.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001829 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001830 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001831 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00001832 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001833 }
1834
1835 // FIXME: Currently, we fall through and treat C++ classes like C
1836 // structures.
1837 }
1838
Steve Naroff529a4ad2007-11-27 17:58:44 +00001839 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1840 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00001841 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1842 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00001843 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001844 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00001845 return Compatible;
1846 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001847
1848 // We don't allow conversion of non-null-pointer constants to integers.
1849 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1850 return IntToBlockPointer;
1851
Chris Lattner943140e2007-10-16 02:55:40 +00001852 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001853 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001854 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001855 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001856 //
Douglas Gregor9d293df2008-10-28 00:22:11 +00001857 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00001858 if (!lhsType->isReferenceType())
1859 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001860
Chris Lattner5cf216b2008-01-04 18:04:52 +00001861 Sema::AssignConvertType result =
1862 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00001863
1864 // C99 6.5.16.1p2: The value of the right operand is converted to the
1865 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00001866 // CheckAssignmentConstraints allows the left-hand side to be a reference,
1867 // so that we can use references in built-in functions even in C.
1868 // The getNonReferenceType() call makes sure that the resulting expression
1869 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00001870 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00001871 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00001872 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001873}
1874
Chris Lattner5cf216b2008-01-04 18:04:52 +00001875Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001876Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1877 return CheckAssignmentConstraints(lhsType, rhsType);
1878}
1879
Chris Lattner29a1cfb2008-11-18 01:30:42 +00001880QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001881 Diag(Loc, diag::err_typecheck_invalid_operands)
1882 << lex->getType().getAsString() << rex->getType().getAsString()
1883 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00001884 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001885}
1886
Chris Lattner29a1cfb2008-11-18 01:30:42 +00001887inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00001888 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00001889 // For conversion purposes, we ignore any qualifiers.
1890 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001891 QualType lhsType =
1892 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1893 QualType rhsType =
1894 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001895
Nate Begemanbe2341d2008-07-14 18:02:46 +00001896 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00001897 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001898 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00001899
Nate Begemanbe2341d2008-07-14 18:02:46 +00001900 // Handle the case of a vector & extvector type of the same size and element
1901 // type. It would be nice if we only had one vector type someday.
1902 if (getLangOptions().LaxVectorConversions)
1903 if (const VectorType *LV = lhsType->getAsVectorType())
1904 if (const VectorType *RV = rhsType->getAsVectorType())
1905 if (LV->getElementType() == RV->getElementType() &&
1906 LV->getNumElements() == RV->getNumElements())
1907 return lhsType->isExtVectorType() ? lhsType : rhsType;
1908
1909 // If the lhs is an extended vector and the rhs is a scalar of the same type
1910 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001911 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001912 QualType eltType = V->getElementType();
1913
1914 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1915 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1916 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001917 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001918 return lhsType;
1919 }
1920 }
1921
Nate Begemanbe2341d2008-07-14 18:02:46 +00001922 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00001923 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001924 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001925 QualType eltType = V->getElementType();
1926
1927 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1928 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1929 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001930 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001931 return rhsType;
1932 }
1933 }
1934
Reid Spencer5f016e22007-07-11 17:01:13 +00001935 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001936 Diag(Loc, diag::err_typecheck_vector_not_convertable)
1937 << lex->getType().getAsString() << rex->getType().getAsString()
1938 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001939 return QualType();
1940}
1941
1942inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00001943 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001944{
Steve Naroff90045e82007-07-13 23:32:42 +00001945 QualType lhsType = lex->getType(), rhsType = rex->getType();
1946
1947 if (lhsType->isVectorType() || rhsType->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00001948 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001949
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001950 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001951
Steve Naroffa4332e22007-07-17 00:58:39 +00001952 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001953 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00001954 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001955}
1956
1957inline QualType Sema::CheckRemainderOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00001958 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001959{
Steve Naroff90045e82007-07-13 23:32:42 +00001960 QualType lhsType = lex->getType(), rhsType = rex->getType();
1961
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001962 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001963
Steve Naroffa4332e22007-07-17 00:58:39 +00001964 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001965 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00001966 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001967}
1968
1969inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner29a1cfb2008-11-18 01:30:42 +00001970 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001971{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001972 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00001973 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001974
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001975 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00001976
Reid Spencer5f016e22007-07-11 17:01:13 +00001977 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001978 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001979 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001980
Eli Friedmand72d16e2008-05-18 18:08:51 +00001981 // Put any potential pointer into PExp
1982 Expr* PExp = lex, *IExp = rex;
1983 if (IExp->getType()->isPointerType())
1984 std::swap(PExp, IExp);
1985
1986 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1987 if (IExp->getType()->isIntegerType()) {
1988 // Check for arithmetic on pointers to incomplete types
1989 if (!PTy->getPointeeType()->isObjectType()) {
1990 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001991 Diag(Loc, diag::ext_gnu_void_ptr)
1992 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand72d16e2008-05-18 18:08:51 +00001993 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001994 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
1995 << lex->getType().getAsString() << lex->getSourceRange();
Eli Friedmand72d16e2008-05-18 18:08:51 +00001996 return QualType();
1997 }
1998 }
1999 return PExp->getType();
2000 }
2001 }
2002
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002003 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002004}
2005
Chris Lattnereca7be62008-04-07 05:30:13 +00002006// C99 6.5.6
2007QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002008 SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00002009 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002010 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002011
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002012 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002013
Chris Lattner6e4ab612007-12-09 21:53:25 +00002014 // Enforce type constraints: C99 6.5.6p3.
2015
2016 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002017 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002018 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00002019
2020 // Either ptr - int or ptr - ptr.
2021 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00002022 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00002023
Chris Lattner6e4ab612007-12-09 21:53:25 +00002024 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00002025 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002026 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002027 if (lpointee->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002028 Diag(Loc, diag::ext_gnu_void_ptr)
2029 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002030 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002031 Diag(Loc, diag::err_typecheck_sub_ptr_object)
2032 << lex->getType().getAsString() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002033 return QualType();
2034 }
2035 }
2036
2037 // The result type of a pointer-int computation is the pointer type.
2038 if (rex->getType()->isIntegerType())
2039 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00002040
Chris Lattner6e4ab612007-12-09 21:53:25 +00002041 // Handle pointer-pointer subtractions.
2042 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00002043 QualType rpointee = RHSPTy->getPointeeType();
2044
Chris Lattner6e4ab612007-12-09 21:53:25 +00002045 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00002046 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002047 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002048 if (rpointee->isVoidType()) {
2049 if (!lpointee->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002050 Diag(Loc, diag::ext_gnu_void_ptr)
2051 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002052 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002053 Diag(Loc, diag::err_typecheck_sub_ptr_object)
2054 << rex->getType().getAsString() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002055 return QualType();
2056 }
2057 }
2058
2059 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00002060 if (!Context.typesAreCompatible(
2061 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2062 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002063 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
2064 << lex->getType().getAsString() << rex->getType().getAsString()
2065 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002066 return QualType();
2067 }
2068
2069 return Context.getPointerDiffType();
2070 }
2071 }
2072
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002073 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002074}
2075
Chris Lattnereca7be62008-04-07 05:30:13 +00002076// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002077QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002078 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002079 // C99 6.5.7p2: Each of the operands shall have integer type.
2080 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002081 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002082
Chris Lattnerca5eede2007-12-12 05:47:28 +00002083 // Shifts don't perform usual arithmetic conversions, they just do integer
2084 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002085 if (!isCompAssign)
2086 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002087 UsualUnaryConversions(rex);
2088
2089 // "The type of the result is that of the promoted left operand."
2090 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002091}
2092
Eli Friedman3d815e72008-08-22 00:56:42 +00002093static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2094 ASTContext& Context) {
2095 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2096 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2097 // ID acts sort of like void* for ObjC interfaces
2098 if (LHSIface && Context.isObjCIdType(RHS))
2099 return true;
2100 if (RHSIface && Context.isObjCIdType(LHS))
2101 return true;
2102 if (!LHSIface || !RHSIface)
2103 return false;
2104 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2105 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2106}
2107
Chris Lattnereca7be62008-04-07 05:30:13 +00002108// C99 6.5.8
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002109QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002110 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002111 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002112 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002113
Chris Lattnera5937dd2007-08-26 01:18:55 +00002114 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002115 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2116 UsualArithmeticConversions(lex, rex);
2117 else {
2118 UsualUnaryConversions(lex);
2119 UsualUnaryConversions(rex);
2120 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002121 QualType lType = lex->getType();
2122 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002123
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002124 // For non-floating point types, check for self-comparisons of the form
2125 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2126 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002127 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002128 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2129 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002130 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002131 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002132 }
2133
Douglas Gregor447b69e2008-11-19 03:25:36 +00002134 // The result of comparisons is 'bool' in C++, 'int' in C.
2135 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2136
Chris Lattnera5937dd2007-08-26 01:18:55 +00002137 if (isRelational) {
2138 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002139 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002140 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002141 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002142 if (lType->isFloatingType()) {
2143 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002144 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002145 }
2146
Chris Lattnera5937dd2007-08-26 01:18:55 +00002147 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002148 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002149 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002150
Chris Lattnerd28f8152007-08-26 01:10:14 +00002151 bool LHSIsNull = lex->isNullPointerConstant(Context);
2152 bool RHSIsNull = rex->isNullPointerConstant(Context);
2153
Chris Lattnera5937dd2007-08-26 01:18:55 +00002154 // All of the following pointer related warnings are GCC extensions, except
2155 // when handling null pointer constants. One day, we can consider making them
2156 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002157 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002158 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002159 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002160 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002161 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002162
Steve Naroff66296cb2007-11-13 14:57:38 +00002163 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002164 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2165 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002166 RCanPointeeTy.getUnqualifiedType()) &&
2167 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002168 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
2169 << lType.getAsString() << rType.getAsString()
2170 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002171 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002172 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002173 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002174 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002175 // Handle block pointer types.
2176 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2177 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2178 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2179
2180 if (!LHSIsNull && !RHSIsNull &&
2181 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002182 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
2183 << lType.getAsString() << rType.getAsString()
2184 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00002185 }
2186 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002187 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002188 }
Steve Naroff59f53942008-09-28 01:11:11 +00002189 // Allow block pointers to be compared with null pointer constants.
2190 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2191 (lType->isPointerType() && rType->isBlockPointerType())) {
2192 if (!LHSIsNull && !RHSIsNull) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002193 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
2194 << lType.getAsString() << rType.getAsString()
2195 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00002196 }
2197 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002198 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00002199 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002200
Steve Naroff20373222008-06-03 14:04:54 +00002201 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00002202 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00002203 const PointerType *LPT = lType->getAsPointerType();
2204 const PointerType *RPT = rType->getAsPointerType();
2205 bool LPtrToVoid = LPT ?
2206 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2207 bool RPtrToVoid = RPT ?
2208 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2209
2210 if (!LPtrToVoid && !RPtrToVoid &&
2211 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002212 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
2213 << lType.getAsString() << rType.getAsString()
2214 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00002215 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002216 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00002217 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002218 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002219 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00002220 }
Steve Naroff20373222008-06-03 14:04:54 +00002221 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2222 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002223 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002224 } else {
2225 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002226 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
2227 << lType.getAsString() << rType.getAsString()
2228 << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002229 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002230 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002231 }
Steve Naroff20373222008-06-03 14:04:54 +00002232 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00002233 }
Steve Naroff20373222008-06-03 14:04:54 +00002234 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2235 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002236 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002237 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
2238 << lType.getAsString() << rType.getAsString()
2239 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002240 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002241 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002242 }
Steve Naroff20373222008-06-03 14:04:54 +00002243 if (lType->isIntegerType() &&
2244 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002245 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002246 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
2247 << lType.getAsString() << rType.getAsString()
2248 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002249 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002250 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002251 }
Steve Naroff39218df2008-09-04 16:56:14 +00002252 // Handle block pointers.
2253 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2254 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002255 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
2256 << lType.getAsString() << rType.getAsString()
2257 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002258 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002259 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00002260 }
2261 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2262 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002263 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
2264 << lType.getAsString() << rType.getAsString()
2265 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002266 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002267 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00002268 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002269 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002270}
2271
Nate Begemanbe2341d2008-07-14 18:02:46 +00002272/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2273/// operates on extended vector types. Instead of producing an IntTy result,
2274/// like a scalar comparison, a vector comparison produces a vector of integer
2275/// types.
2276QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002277 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00002278 bool isRelational) {
2279 // Check to make sure we're operating on vectors of the same type and width,
2280 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002281 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002282 if (vType.isNull())
2283 return vType;
2284
2285 QualType lType = lex->getType();
2286 QualType rType = rex->getType();
2287
2288 // For non-floating point types, check for self-comparisons of the form
2289 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2290 // often indicate logic errors in the program.
2291 if (!lType->isFloatingType()) {
2292 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2293 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2294 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002295 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002296 }
2297
2298 // Check for comparisons of floating point operands using != and ==.
2299 if (!isRelational && lType->isFloatingType()) {
2300 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002301 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002302 }
2303
2304 // Return the type for the comparison, which is the same as vector type for
2305 // integer vectors, or an integer type of identical size and number of
2306 // elements for floating point vectors.
2307 if (lType->isIntegerType())
2308 return lType;
2309
2310 const VectorType *VTy = lType->getAsVectorType();
2311
2312 // FIXME: need to deal with non-32b int / non-64b long long
2313 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2314 if (TypeSize == 32) {
2315 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2316 }
2317 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2318 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2319}
2320
Reid Spencer5f016e22007-07-11 17:01:13 +00002321inline QualType Sema::CheckBitwiseOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002322 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002323{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002324 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002325 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002326
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002327 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002328
Steve Naroffa4332e22007-07-17 00:58:39 +00002329 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002330 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002331 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002332}
2333
2334inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002335 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00002336{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002337 UsualUnaryConversions(lex);
2338 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002339
Eli Friedman5773a6c2008-05-13 20:16:47 +00002340 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002341 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002342 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002343}
2344
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002345/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2346/// emit an error and return true. If so, return false.
2347static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2348 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2349 if (IsLV == Expr::MLV_Valid)
2350 return false;
2351
2352 unsigned Diag = 0;
2353 bool NeedType = false;
2354 switch (IsLV) { // C99 6.5.16p2
2355 default: assert(0 && "Unknown result from isModifiableLvalue!");
2356 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002357 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002358 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2359 NeedType = true;
2360 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002361 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002362 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2363 NeedType = true;
2364 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00002365 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002366 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2367 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002368 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002369 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2370 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002371 case Expr::MLV_IncompleteType:
2372 case Expr::MLV_IncompleteVoidType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002373 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2374 NeedType = true;
2375 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002376 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002377 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2378 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00002379 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002380 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2381 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002382 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00002383
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002384 if (NeedType)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002385 S.Diag(Loc, Diag) << E->getType().getAsString() << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002386 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002387 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002388 return true;
2389}
2390
2391
2392
2393// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002394QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
2395 SourceLocation Loc,
2396 QualType CompoundType) {
2397 // Verify that LHS is a modifiable lvalue, and emit error if not.
2398 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002399 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002400
2401 QualType LHSType = LHS->getType();
2402 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002403
Chris Lattner5cf216b2008-01-04 18:04:52 +00002404 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002405 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00002406 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002407 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner2c156472008-08-21 18:04:13 +00002408
2409 // If the RHS is a unary plus or minus, check to see if they = and + are
2410 // right next to each other. If so, the user may have typo'd "x =+ 4"
2411 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002412 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00002413 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2414 RHSCheck = ICE->getSubExpr();
2415 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2416 if ((UO->getOpcode() == UnaryOperator::Plus ||
2417 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002418 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00002419 // Only if the two operators are exactly adjacent.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002420 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2421 Diag(Loc, diag::warn_not_compound_assign,
Chris Lattner2c156472008-08-21 18:04:13 +00002422 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2423 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2424 }
2425 } else {
2426 // Compound assignment "x += y"
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002427 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00002428 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00002429
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002430 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
2431 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00002432 return QualType();
2433
Reid Spencer5f016e22007-07-11 17:01:13 +00002434 // C99 6.5.16p3: The type of an assignment expression is the type of the
2435 // left operand unless the left operand has qualified type, in which case
2436 // it is the unqualified version of the type of the left operand.
2437 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2438 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002439 // C++ 5.17p1: the type of the assignment expression is that of its left
2440 // oprdu.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002441 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002442}
2443
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002444// C99 6.5.17
2445QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
2446 // FIXME: what is required for LHS?
Chris Lattner53fcaa92008-07-25 20:54:07 +00002447
2448 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002449 DefaultFunctionArrayConversion(RHS);
2450 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002451}
2452
Steve Naroff49b45262007-07-13 16:58:59 +00002453/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2454/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00002455QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00002456 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002457 assert(!resType.isNull() && "no type for increment/decrement expression");
2458
Steve Naroff084f9ed2007-08-24 17:20:07 +00002459 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00002460 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00002461 if (pt->getPointeeType()->isVoidType()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002462 Diag(OpLoc, diag::ext_gnu_void_ptr) << op->getSourceRange();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002463 } else if (!pt->getPointeeType()->isObjectType()) {
2464 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002465 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
2466 << resType.getAsString() << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002467 return QualType();
2468 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00002469 } else if (!resType->isRealType()) {
2470 if (resType->isComplexType())
2471 // C99 does not support ++/-- on complex types.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002472 Diag(OpLoc, diag::ext_integer_increment_complex)
2473 << resType.getAsString() << op->getSourceRange();
Steve Naroff084f9ed2007-08-24 17:20:07 +00002474 else {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002475 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
2476 << resType.getAsString() << op->getSourceRange();
Steve Naroff084f9ed2007-08-24 17:20:07 +00002477 return QualType();
2478 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002479 }
Steve Naroffdd10e022007-08-23 21:37:33 +00002480 // At this point, we know we have a real, complex or pointer type.
2481 // Now make sure the operand is a modifiable lvalue.
Chris Lattner858bb6f2008-11-18 01:26:17 +00002482 if (CheckForModifiableLvalue(op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00002483 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002484 return resType;
2485}
2486
Anders Carlsson369dee42008-02-01 07:15:58 +00002487/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00002488/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002489/// where the declaration is needed for type checking. We only need to
2490/// handle cases when the expression references a function designator
2491/// or is an lvalue. Here are some examples:
2492/// - &(x) => x
2493/// - &*****f => f for f a function designator.
2494/// - &s.xx => s
2495/// - &s.zz[1].yy -> s, if zz is an array
2496/// - *(x + 1) -> x, if x is an array
2497/// - &"123"[2] -> 0
2498/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002499static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002500 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002501 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002502 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002503 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00002504 // Fields cannot be declared with a 'register' storage class.
2505 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002506 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00002507 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00002508 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00002509 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002510 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00002511
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002512 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00002513 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00002514 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00002515 return 0;
2516 else
2517 return VD;
2518 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002519 case Stmt::UnaryOperatorClass: {
2520 UnaryOperator *UO = cast<UnaryOperator>(E);
2521
2522 switch(UO->getOpcode()) {
2523 case UnaryOperator::Deref: {
2524 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002525 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2526 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2527 if (!VD || VD->getType()->isPointerType())
2528 return 0;
2529 return VD;
2530 }
2531 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002532 }
2533 case UnaryOperator::Real:
2534 case UnaryOperator::Imag:
2535 case UnaryOperator::Extension:
2536 return getPrimaryDecl(UO->getSubExpr());
2537 default:
2538 return 0;
2539 }
2540 }
2541 case Stmt::BinaryOperatorClass: {
2542 BinaryOperator *BO = cast<BinaryOperator>(E);
2543
2544 // Handle cases involving pointer arithmetic. The result of an
2545 // Assign or AddAssign is not an lvalue so they can be ignored.
2546
2547 // (x + n) or (n + x) => x
2548 if (BO->getOpcode() == BinaryOperator::Add) {
2549 if (BO->getLHS()->getType()->isPointerType()) {
2550 return getPrimaryDecl(BO->getLHS());
2551 } else if (BO->getRHS()->getType()->isPointerType()) {
2552 return getPrimaryDecl(BO->getRHS());
2553 }
2554 }
2555
2556 return 0;
2557 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002558 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002559 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00002560 case Stmt::ImplicitCastExprClass:
2561 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002562 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00002563 default:
2564 return 0;
2565 }
2566}
2567
2568/// CheckAddressOfOperand - The operand of & must be either a function
2569/// designator or an lvalue designating an object. If it is an lvalue, the
2570/// object cannot be declared with storage class register or be a bit field.
2571/// Note: The usual conversions are *not* applied to the operand of the &
2572/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor904eed32008-11-10 20:40:00 +00002573/// In C++, the operand might be an overloaded function name, in which case
2574/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002575QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff08f19672008-01-13 17:10:08 +00002576 if (getLangOptions().C99) {
2577 // Implement C99-only parts of addressof rules.
2578 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2579 if (uOp->getOpcode() == UnaryOperator::Deref)
2580 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2581 // (assuming the deref expression is valid).
2582 return uOp->getSubExpr()->getType();
2583 }
2584 // Technically, there should be a check for array subscript
2585 // expressions here, but the result of one is always an lvalue anyway.
2586 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002587 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00002588 Expr::isLvalueResult lval = op->isLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002589
2590 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00002591 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2592 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002593 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
2594 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002595 return QualType();
2596 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00002597 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2598 if (MemExpr->getMemberDecl()->isBitField()) {
2599 Diag(OpLoc, diag::err_typecheck_address_of,
2600 std::string("bit-field"), op->getSourceRange());
2601 return QualType();
2602 }
2603 // Check for Apple extension for accessing vector components.
2604 } else if (isa<ArraySubscriptExpr>(op) &&
2605 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2606 Diag(OpLoc, diag::err_typecheck_address_of,
2607 std::string("vector"), op->getSourceRange());
2608 return QualType();
2609 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00002610 // We have an lvalue with a decl. Make sure the decl is not declared
2611 // with the register storage-class specifier.
2612 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2613 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroffbcb2b612008-02-29 23:30:25 +00002614 Diag(OpLoc, diag::err_typecheck_address_of,
2615 std::string("register variable"), op->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002616 return QualType();
2617 }
Douglas Gregor904eed32008-11-10 20:40:00 +00002618 } else if (isa<OverloadedFunctionDecl>(dcl))
2619 return Context.OverloadTy;
2620 else
Reid Spencer5f016e22007-07-11 17:01:13 +00002621 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002622 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00002623
Reid Spencer5f016e22007-07-11 17:01:13 +00002624 // If the operand has type "type", the result has type "pointer to type".
2625 return Context.getPointerType(op->getType());
2626}
2627
2628QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002629 UsualUnaryConversions(op);
2630 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002631
Chris Lattnerbefee482007-07-31 16:53:04 +00002632 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff08f19672008-01-13 17:10:08 +00002633 // Note that per both C89 and C99, this is always legal, even
2634 // if ptype is an incomplete type or void.
2635 // It would be possible to warn about dereferencing a
2636 // void pointer, but it's completely well-defined,
2637 // and such a warning is unlikely to catch any mistakes.
2638 return PT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002639 }
2640 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2641 qType.getAsString(), op->getSourceRange());
2642 return QualType();
2643}
2644
2645static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2646 tok::TokenKind Kind) {
2647 BinaryOperator::Opcode Opc;
2648 switch (Kind) {
2649 default: assert(0 && "Unknown binop!");
2650 case tok::star: Opc = BinaryOperator::Mul; break;
2651 case tok::slash: Opc = BinaryOperator::Div; break;
2652 case tok::percent: Opc = BinaryOperator::Rem; break;
2653 case tok::plus: Opc = BinaryOperator::Add; break;
2654 case tok::minus: Opc = BinaryOperator::Sub; break;
2655 case tok::lessless: Opc = BinaryOperator::Shl; break;
2656 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2657 case tok::lessequal: Opc = BinaryOperator::LE; break;
2658 case tok::less: Opc = BinaryOperator::LT; break;
2659 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2660 case tok::greater: Opc = BinaryOperator::GT; break;
2661 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2662 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2663 case tok::amp: Opc = BinaryOperator::And; break;
2664 case tok::caret: Opc = BinaryOperator::Xor; break;
2665 case tok::pipe: Opc = BinaryOperator::Or; break;
2666 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2667 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2668 case tok::equal: Opc = BinaryOperator::Assign; break;
2669 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2670 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2671 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2672 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2673 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2674 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2675 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2676 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2677 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2678 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2679 case tok::comma: Opc = BinaryOperator::Comma; break;
2680 }
2681 return Opc;
2682}
2683
2684static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2685 tok::TokenKind Kind) {
2686 UnaryOperator::Opcode Opc;
2687 switch (Kind) {
2688 default: assert(0 && "Unknown unary op!");
2689 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2690 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2691 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2692 case tok::star: Opc = UnaryOperator::Deref; break;
2693 case tok::plus: Opc = UnaryOperator::Plus; break;
2694 case tok::minus: Opc = UnaryOperator::Minus; break;
2695 case tok::tilde: Opc = UnaryOperator::Not; break;
2696 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002697 case tok::kw___real: Opc = UnaryOperator::Real; break;
2698 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2699 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2700 }
2701 return Opc;
2702}
2703
Douglas Gregoreaebc752008-11-06 23:29:22 +00002704/// CreateBuiltinBinOp - Creates a new built-in binary operation with
2705/// operator @p Opc at location @c TokLoc. This routine only supports
2706/// built-in operations; ActOnBinOp handles overloaded operators.
2707Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
2708 unsigned Op,
2709 Expr *lhs, Expr *rhs) {
2710 QualType ResultTy; // Result type of the binary operator.
2711 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2712 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
2713
2714 switch (Opc) {
2715 default:
2716 assert(0 && "Unknown binary expr!");
2717 case BinaryOperator::Assign:
2718 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
2719 break;
2720 case BinaryOperator::Mul:
2721 case BinaryOperator::Div:
2722 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
2723 break;
2724 case BinaryOperator::Rem:
2725 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
2726 break;
2727 case BinaryOperator::Add:
2728 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
2729 break;
2730 case BinaryOperator::Sub:
2731 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
2732 break;
2733 case BinaryOperator::Shl:
2734 case BinaryOperator::Shr:
2735 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
2736 break;
2737 case BinaryOperator::LE:
2738 case BinaryOperator::LT:
2739 case BinaryOperator::GE:
2740 case BinaryOperator::GT:
2741 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
2742 break;
2743 case BinaryOperator::EQ:
2744 case BinaryOperator::NE:
2745 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
2746 break;
2747 case BinaryOperator::And:
2748 case BinaryOperator::Xor:
2749 case BinaryOperator::Or:
2750 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
2751 break;
2752 case BinaryOperator::LAnd:
2753 case BinaryOperator::LOr:
2754 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
2755 break;
2756 case BinaryOperator::MulAssign:
2757 case BinaryOperator::DivAssign:
2758 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
2759 if (!CompTy.isNull())
2760 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2761 break;
2762 case BinaryOperator::RemAssign:
2763 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
2764 if (!CompTy.isNull())
2765 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2766 break;
2767 case BinaryOperator::AddAssign:
2768 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
2769 if (!CompTy.isNull())
2770 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2771 break;
2772 case BinaryOperator::SubAssign:
2773 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
2774 if (!CompTy.isNull())
2775 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2776 break;
2777 case BinaryOperator::ShlAssign:
2778 case BinaryOperator::ShrAssign:
2779 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
2780 if (!CompTy.isNull())
2781 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2782 break;
2783 case BinaryOperator::AndAssign:
2784 case BinaryOperator::XorAssign:
2785 case BinaryOperator::OrAssign:
2786 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
2787 if (!CompTy.isNull())
2788 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2789 break;
2790 case BinaryOperator::Comma:
2791 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
2792 break;
2793 }
2794 if (ResultTy.isNull())
2795 return true;
2796 if (CompTy.isNull())
2797 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
2798 else
2799 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
2800}
2801
Reid Spencer5f016e22007-07-11 17:01:13 +00002802// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00002803Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
2804 tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00002805 ExprTy *LHS, ExprTy *RHS) {
2806 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2807 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2808
Steve Narofff69936d2007-09-16 03:34:24 +00002809 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2810 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00002811
Douglas Gregoreaebc752008-11-06 23:29:22 +00002812 if (getLangOptions().CPlusPlus &&
2813 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
2814 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002815 // If this is one of the assignment operators, we only perform
2816 // overload resolution if the left-hand side is a class or
2817 // enumeration type (C++ [expr.ass]p3).
2818 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
2819 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
2820 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
2821 }
2822
Douglas Gregoreaebc752008-11-06 23:29:22 +00002823 // C++ [over.binary]p1:
2824 // A binary operator shall be implemented either by a non-static
2825 // member function (9.3) with one parameter or by a non-member
2826 // function with two parameters. Thus, for any binary operator
2827 // @, x@y can be interpreted as either x.operator@(y) or
2828 // operator@(x,y). If both forms of the operator function have
2829 // been declared, the rules in 13.3.1.2 determines which, if
2830 // any, interpretation is used.
2831 OverloadCandidateSet CandidateSet;
2832
2833 // Determine which overloaded operator we're dealing with.
2834 static const OverloadedOperatorKind OverOps[] = {
2835 OO_Star, OO_Slash, OO_Percent,
2836 OO_Plus, OO_Minus,
2837 OO_LessLess, OO_GreaterGreater,
2838 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2839 OO_EqualEqual, OO_ExclaimEqual,
2840 OO_Amp,
2841 OO_Caret,
2842 OO_Pipe,
2843 OO_AmpAmp,
2844 OO_PipePipe,
2845 OO_Equal, OO_StarEqual,
2846 OO_SlashEqual, OO_PercentEqual,
2847 OO_PlusEqual, OO_MinusEqual,
2848 OO_LessLessEqual, OO_GreaterGreaterEqual,
2849 OO_AmpEqual, OO_CaretEqual,
2850 OO_PipeEqual,
2851 OO_Comma
2852 };
2853 OverloadedOperatorKind OverOp = OverOps[Opc];
2854
Douglas Gregor96176b32008-11-18 23:14:02 +00002855 // Add the appropriate overloaded operators (C++ [over.match.oper])
2856 // to the candidate set.
Douglas Gregoreaebc752008-11-06 23:29:22 +00002857 Expr *Args[2] = { lhs, rhs };
Douglas Gregor96176b32008-11-18 23:14:02 +00002858 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregoreaebc752008-11-06 23:29:22 +00002859
2860 // Perform overload resolution.
2861 OverloadCandidateSet::iterator Best;
2862 switch (BestViableFunction(CandidateSet, Best)) {
2863 case OR_Success: {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002864 // We found a built-in operator or an overloaded operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00002865 FunctionDecl *FnDecl = Best->Function;
2866
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002867 if (FnDecl) {
2868 // We matched an overloaded operator. Build a call to that
2869 // operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00002870
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002871 // Convert the arguments.
Douglas Gregor96176b32008-11-18 23:14:02 +00002872 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
2873 if (PerformObjectArgumentInitialization(lhs, Method) ||
2874 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
2875 "passing"))
2876 return true;
2877 } else {
2878 // Convert the arguments.
2879 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
2880 "passing") ||
2881 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
2882 "passing"))
2883 return true;
2884 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00002885
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002886 // Determine the result type
2887 QualType ResultTy
2888 = FnDecl->getType()->getAsFunctionType()->getResultType();
2889 ResultTy = ResultTy.getNonReferenceType();
2890
2891 // Build the actual expression node.
Douglas Gregorb4609802008-11-14 16:09:21 +00002892 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
2893 SourceLocation());
2894 UsualUnaryConversions(FnExpr);
2895
2896 Expr *Args[2] = { lhs, rhs };
2897 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002898 } else {
2899 // We matched a built-in operator. Convert the arguments, then
2900 // break out so that we will build the appropriate built-in
2901 // operator node.
2902 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
2903 "passing") ||
2904 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
2905 "passing"))
2906 return true;
2907
2908 break;
2909 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00002910 }
2911
2912 case OR_No_Viable_Function:
2913 // No viable function; fall through to handling this as a
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002914 // built-in operator, which will produce an error message for us.
Douglas Gregoreaebc752008-11-06 23:29:22 +00002915 break;
2916
2917 case OR_Ambiguous:
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002918 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
2919 << BinaryOperator::getOpcodeStr(Opc)
2920 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregoreaebc752008-11-06 23:29:22 +00002921 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2922 return true;
2923 }
2924
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002925 // Either we found no viable overloaded operator or we matched a
2926 // built-in operator. In either case, fall through to trying to
2927 // build a built-in operation.
Douglas Gregoreaebc752008-11-06 23:29:22 +00002928 }
2929
Reid Spencer5f016e22007-07-11 17:01:13 +00002930
Douglas Gregoreaebc752008-11-06 23:29:22 +00002931 // Build a built-in binary operation.
2932 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00002933}
2934
2935// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002936Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00002937 ExprTy *input) {
2938 Expr *Input = (Expr*)input;
2939 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2940 QualType resultType;
2941 switch (Opc) {
2942 default:
2943 assert(0 && "Unimplemented unary expr!");
2944 case UnaryOperator::PreInc:
2945 case UnaryOperator::PreDec:
2946 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2947 break;
2948 case UnaryOperator::AddrOf:
2949 resultType = CheckAddressOfOperand(Input, OpLoc);
2950 break;
2951 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00002952 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002953 resultType = CheckIndirectionOperand(Input, OpLoc);
2954 break;
2955 case UnaryOperator::Plus:
2956 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002957 UsualUnaryConversions(Input);
2958 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002959 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2960 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2961 resultType.getAsString());
2962 break;
2963 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002964 UsualUnaryConversions(Input);
2965 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00002966 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2967 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2968 // C99 does not support '~' for complex conjugation.
2969 Diag(OpLoc, diag::ext_integer_complement_complex,
2970 resultType.getAsString(), Input->getSourceRange());
2971 else if (!resultType->isIntegerType())
2972 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2973 resultType.getAsString(), Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002974 break;
2975 case UnaryOperator::LNot: // logical negation
2976 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002977 DefaultFunctionArrayConversion(Input);
2978 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002979 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2980 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2981 resultType.getAsString());
2982 // LNot always has type int. C99 6.5.3.3p5.
2983 resultType = Context.IntTy;
2984 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00002985 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00002986 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00002987 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00002988 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002989 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00002990 resultType = Input->getType();
2991 break;
2992 }
2993 if (resultType.isNull())
2994 return true;
2995 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2996}
2997
Steve Naroff1b273c42007-09-16 14:56:35 +00002998/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2999Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00003000 SourceLocation LabLoc,
3001 IdentifierInfo *LabelII) {
3002 // Look up the record for this label identifier.
3003 LabelStmt *&LabelDecl = LabelMap[LabelII];
3004
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00003005 // If we haven't seen this label yet, create a forward reference. It
3006 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00003007 if (LabelDecl == 0)
3008 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3009
3010 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00003011 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3012 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00003013}
3014
Steve Naroff1b273c42007-09-16 14:56:35 +00003015Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003016 SourceLocation RPLoc) { // "({..})"
3017 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3018 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3019 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3020
3021 // FIXME: there are a variety of strange constraints to enforce here, for
3022 // example, it is not possible to goto into a stmt expression apparently.
3023 // More semantic analysis is needed.
3024
3025 // FIXME: the last statement in the compount stmt has its value used. We
3026 // should not warn about it being unused.
3027
3028 // If there are sub stmts in the compound stmt, take the type of the last one
3029 // as the type of the stmtexpr.
3030 QualType Ty = Context.VoidTy;
3031
Chris Lattner611b2ec2008-07-26 19:51:01 +00003032 if (!Compound->body_empty()) {
3033 Stmt *LastStmt = Compound->body_back();
3034 // If LastStmt is a label, skip down through into the body.
3035 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3036 LastStmt = Label->getSubStmt();
3037
3038 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003039 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00003040 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003041
3042 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3043}
Steve Naroffd34e9152007-08-01 22:05:33 +00003044
Steve Naroff1b273c42007-09-16 14:56:35 +00003045Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003046 SourceLocation TypeLoc,
3047 TypeTy *argty,
3048 OffsetOfComponent *CompPtr,
3049 unsigned NumComponents,
3050 SourceLocation RPLoc) {
3051 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3052 assert(!ArgTy.isNull() && "Missing type argument!");
3053
3054 // We must have at least one component that refers to the type, and the first
3055 // one is known to be a field designator. Verify that the ArgTy represents
3056 // a struct/union/class.
3057 if (!ArgTy->isRecordType())
3058 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
3059
3060 // Otherwise, create a compound literal expression as the base, and
3061 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00003062 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003063
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003064 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3065 // GCC extension, diagnose them.
3066 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003067 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3068 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003069
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003070 for (unsigned i = 0; i != NumComponents; ++i) {
3071 const OffsetOfComponent &OC = CompPtr[i];
3072 if (OC.isBrackets) {
3073 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003074 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003075 if (!AT) {
3076 delete Res;
3077 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
3078 Res->getType().getAsString());
3079 }
3080
Chris Lattner704fe352007-08-30 17:59:59 +00003081 // FIXME: C++: Verify that operator[] isn't overloaded.
3082
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003083 // C99 6.5.2.1p1
3084 Expr *Idx = static_cast<Expr*>(OC.U.E);
3085 if (!Idx->getType()->isIntegerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003086 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3087 << Idx->getSourceRange();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003088
3089 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3090 continue;
3091 }
3092
3093 const RecordType *RC = Res->getType()->getAsRecordType();
3094 if (!RC) {
3095 delete Res;
3096 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
3097 Res->getType().getAsString());
3098 }
3099
3100 // Get the decl corresponding to this.
3101 RecordDecl *RD = RC->getDecl();
3102 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
3103 if (!MemberDecl)
Chris Lattner3c73c412008-11-19 08:23:25 +00003104 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3105 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner704fe352007-08-30 17:59:59 +00003106
3107 // FIXME: C++: Verify that MemberDecl isn't a static field.
3108 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00003109 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3110 // matter here.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003111 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3112 MemberDecl->getType().getNonReferenceType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003113 }
3114
3115 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3116 BuiltinLoc);
3117}
3118
3119
Steve Naroff1b273c42007-09-16 14:56:35 +00003120Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00003121 TypeTy *arg1, TypeTy *arg2,
3122 SourceLocation RPLoc) {
3123 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3124 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3125
3126 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3127
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003128 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00003129}
3130
Steve Naroff1b273c42007-09-16 14:56:35 +00003131Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00003132 ExprTy *expr1, ExprTy *expr2,
3133 SourceLocation RPLoc) {
3134 Expr *CondExpr = static_cast<Expr*>(cond);
3135 Expr *LHSExpr = static_cast<Expr*>(expr1);
3136 Expr *RHSExpr = static_cast<Expr*>(expr2);
3137
3138 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3139
3140 // The conditional expression is required to be a constant expression.
3141 llvm::APSInt condEval(32);
3142 SourceLocation ExpLoc;
3143 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003144 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3145 << CondExpr->getSourceRange();
Steve Naroffd04fdd52007-08-03 21:21:27 +00003146
3147 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3148 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3149 RHSExpr->getType();
3150 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3151}
3152
Steve Naroff4eb206b2008-09-03 18:15:37 +00003153//===----------------------------------------------------------------------===//
3154// Clang Extensions.
3155//===----------------------------------------------------------------------===//
3156
3157/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00003158void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00003159 // Analyze block parameters.
3160 BlockSemaInfo *BSI = new BlockSemaInfo();
3161
3162 // Add BSI to CurBlock.
3163 BSI->PrevBlockInfo = CurBlock;
3164 CurBlock = BSI;
3165
3166 BSI->ReturnType = 0;
3167 BSI->TheScope = BlockScope;
3168
Steve Naroff090276f2008-10-10 01:28:17 +00003169 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
3170 PushDeclContext(BSI->TheDecl);
3171}
3172
3173void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00003174 // Analyze arguments to block.
3175 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3176 "Not a function declarator!");
3177 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3178
Steve Naroff090276f2008-10-10 01:28:17 +00003179 CurBlock->hasPrototype = FTI.hasPrototype;
3180 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003181
3182 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3183 // no arguments, not a function that takes a single void argument.
3184 if (FTI.hasPrototype &&
3185 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3186 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3187 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3188 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00003189 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003190 } else if (FTI.hasPrototype) {
3191 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00003192 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3193 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003194 }
Steve Naroff090276f2008-10-10 01:28:17 +00003195 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3196
3197 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3198 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3199 // If this has an identifier, add it to the scope stack.
3200 if ((*AI)->getIdentifier())
3201 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003202}
3203
3204/// ActOnBlockError - If there is an error parsing a block, this callback
3205/// is invoked to pop the information about the block from the action impl.
3206void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3207 // Ensure that CurBlock is deleted.
3208 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3209
3210 // Pop off CurBlock, handle nested blocks.
3211 CurBlock = CurBlock->PrevBlockInfo;
3212
3213 // FIXME: Delete the ParmVarDecl objects as well???
3214
3215}
3216
3217/// ActOnBlockStmtExpr - This is called when the body of a block statement
3218/// literal was successfully completed. ^(int x){...}
3219Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3220 Scope *CurScope) {
3221 // Ensure that CurBlock is deleted.
3222 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3223 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3224
Steve Naroff090276f2008-10-10 01:28:17 +00003225 PopDeclContext();
3226
Steve Naroff4eb206b2008-09-03 18:15:37 +00003227 // Pop off CurBlock, handle nested blocks.
3228 CurBlock = CurBlock->PrevBlockInfo;
3229
3230 QualType RetTy = Context.VoidTy;
3231 if (BSI->ReturnType)
3232 RetTy = QualType(BSI->ReturnType, 0);
3233
3234 llvm::SmallVector<QualType, 8> ArgTypes;
3235 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3236 ArgTypes.push_back(BSI->Params[i]->getType());
3237
3238 QualType BlockTy;
3239 if (!BSI->hasPrototype)
3240 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3241 else
3242 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003243 BSI->isVariadic, 0);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003244
3245 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00003246
Steve Naroff1c90bfc2008-10-08 18:44:00 +00003247 BSI->TheDecl->setBody(Body.take());
3248 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003249}
3250
Nate Begeman67295d02008-01-30 20:50:20 +00003251/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00003252/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00003253/// The number of arguments has already been validated to match the number of
3254/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003255static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3256 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00003257 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00003258 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00003259 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3260 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00003261
3262 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00003263 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00003264 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003265 return true;
3266}
3267
3268Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3269 SourceLocation *CommaLocs,
3270 SourceLocation BuiltinLoc,
3271 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003272 // __builtin_overload requires at least 2 arguments
3273 if (NumArgs < 2)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003274 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3275 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003276
Nate Begemane2ce1d92008-01-17 17:46:27 +00003277 // The first argument is required to be a constant expression. It tells us
3278 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003279 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003280 Expr *NParamsExpr = Args[0];
3281 llvm::APSInt constEval(32);
3282 SourceLocation ExpLoc;
3283 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003284 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3285 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003286
3287 // Verify that the number of parameters is > 0
3288 unsigned NumParams = constEval.getZExtValue();
3289 if (NumParams == 0)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003290 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3291 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003292 // Verify that we have at least 1 + NumParams arguments to the builtin.
3293 if ((NumParams + 1) > NumArgs)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003294 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3295 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003296
3297 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00003298 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003299 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003300 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3301 // UsualUnaryConversions will convert the function DeclRefExpr into a
3302 // pointer to function.
3303 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00003304 const FunctionTypeProto *FnType = 0;
3305 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3306 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003307
3308 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3309 // parameters, and the number of parameters must match the value passed to
3310 // the builtin.
3311 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003312 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
3313 << Fn->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003314
3315 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00003316 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00003317 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003318 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003319 if (OE)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003320 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
3321 << OE->getFn()->getSourceRange();
Nate Begeman796ef3d2008-01-31 05:38:29 +00003322 // Remember our match, and continue processing the remaining arguments
3323 // to catch any errors.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003324 OE = new OverloadExpr(Args, NumArgs, i,
3325 FnType->getResultType().getNonReferenceType(),
Nate Begeman796ef3d2008-01-31 05:38:29 +00003326 BuiltinLoc, RParenLoc);
3327 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003328 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00003329 // Return the newly created OverloadExpr node, if we succeded in matching
3330 // exactly one of the candidate functions.
3331 if (OE)
3332 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003333
3334 // If we didn't find a matching function Expr in the __builtin_overload list
3335 // the return an error.
3336 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00003337 for (unsigned i = 0; i != NumParams; ++i) {
3338 if (i != 0) typeNames += ", ";
3339 typeNames += Args[i+1]->getType().getAsString();
3340 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003341
3342 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3343 SourceRange(BuiltinLoc, RParenLoc));
3344}
3345
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003346Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3347 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00003348 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003349 Expr *E = static_cast<Expr*>(expr);
3350 QualType T = QualType::getFromOpaquePtr(type);
3351
3352 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003353
3354 // Get the va_list type
3355 QualType VaListType = Context.getBuiltinVaListType();
3356 // Deal with implicit array decay; for example, on x86-64,
3357 // va_list is an array, but it's supposed to decay to
3358 // a pointer for va_arg.
3359 if (VaListType->isArrayType())
3360 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00003361 // Make sure the input expression also decays appropriately.
3362 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003363
3364 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003365 return Diag(E->getLocStart(),
3366 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3367 E->getType().getAsString(),
3368 E->getSourceRange());
3369
3370 // FIXME: Warn if a non-POD type is passed in.
3371
Douglas Gregor9d293df2008-10-28 00:22:11 +00003372 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003373}
3374
Chris Lattner5cf216b2008-01-04 18:04:52 +00003375bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3376 SourceLocation Loc,
3377 QualType DstType, QualType SrcType,
3378 Expr *SrcExpr, const char *Flavor) {
3379 // Decode the result (notice that AST's are still created for extensions).
3380 bool isInvalid = false;
3381 unsigned DiagKind;
3382 switch (ConvTy) {
3383 default: assert(0 && "Unknown conversion type");
3384 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003385 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00003386 DiagKind = diag::ext_typecheck_convert_pointer_int;
3387 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003388 case IntToPointer:
3389 DiagKind = diag::ext_typecheck_convert_int_pointer;
3390 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003391 case IncompatiblePointer:
3392 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3393 break;
3394 case FunctionVoidPointer:
3395 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3396 break;
3397 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00003398 // If the qualifiers lost were because we were applying the
3399 // (deprecated) C++ conversion from a string literal to a char*
3400 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3401 // Ideally, this check would be performed in
3402 // CheckPointerTypesForAssignment. However, that would require a
3403 // bit of refactoring (so that the second argument is an
3404 // expression, rather than a type), which should be done as part
3405 // of a larger effort to fix CheckPointerTypesForAssignment for
3406 // C++ semantics.
3407 if (getLangOptions().CPlusPlus &&
3408 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3409 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003410 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3411 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003412 case IntToBlockPointer:
3413 DiagKind = diag::err_int_to_block_pointer;
3414 break;
3415 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00003416 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003417 break;
3418 case BlockVoidPointer:
3419 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3420 break;
Steve Naroff39579072008-10-14 22:18:38 +00003421 case IncompatibleObjCQualifiedId:
3422 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3423 // it can give a more specific diagnostic.
3424 DiagKind = diag::warn_incompatible_qualified_id;
3425 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003426 case Incompatible:
3427 DiagKind = diag::err_typecheck_convert_incompatible;
3428 isInvalid = true;
3429 break;
3430 }
3431
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003432 Diag(Loc, DiagKind) << DstType.getAsString() << SrcType.getAsString()
3433 << Flavor << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00003434 return isInvalid;
3435}