blob: fdd5732cc51e3df40e53a497d7d2c9ad20a1cd2b [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Chris Lattner299b8842008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattner299b8842008-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 Lattner299b8842008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-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).
Argiris Kirtzidisf580b4d2008-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 Lattner2aa68822008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattner299b8842008-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 Lattner299b8842008-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 Lattner9305c3d2008-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 Lattner299b8842008-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 Gregor70d26122008-11-12 17:17:38 +0000102
Chris Lattner299b8842008-07-25 21:10:04 +0000103 // For conversion purposes, we ignore any qualifiers.
104 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000105 QualType lhs =
106 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
107 QualType rhs =
108 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-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 Gregor3d4492e2008-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 Gregor70d26122008-11-12 17:17:38 +0000137
Chris Lattner299b8842008-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 Lattner299b8842008-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 Lattner299b8842008-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 Lattner299b8842008-07-25 21:10:04 +0000174 } else if (result < 0) { // The right side is bigger, convert lhs.
175 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-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 Lattner299b8842008-07-25 21:10:04 +0000182 return rhs;
183 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-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 Lattner299b8842008-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 Lattner299b8842008-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 Lattner299b8842008-07-25 21:10:04 +0000205 return lhs;
206 }
207 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000208 return rhs;
209 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000210 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-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 Lattner299b8842008-07-25 21:10:04 +0000221 return lhs;
222 }
Chris Lattner299b8842008-07-25 21:10:04 +0000223 return rhs;
224 } else if (lhsComplexInt && rhs->isIntegerType()) {
225 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000226 return lhs;
227 } else if (rhsComplexInt && lhs->isIntegerType()) {
228 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-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 Lattner299b8842008-07-25 21:10:04 +0000257 return destType;
258}
259
260//===----------------------------------------------------------------------===//
261// Semantic Analysis for various Expression Types
262//===----------------------------------------------------------------------===//
263
264
Steve Naroff87d58b42007-09-16 03:34:24 +0000265/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroff87d58b42007-09-16 03:34:24 +0000272Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnera6dcce32008-02-11 00:02:17 +0000282
283 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000284 if (Literal.Pascal && Literal.GetStringLength() > 256)
Chris Lattner8ba580c2008-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());
Chris Lattner4b009652007-07-25 00:24:17 +0000288
Chris Lattnera6dcce32008-02-11 00:02:17 +0000289 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000290 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000291 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-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 Lattnera6dcce32008-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
Chris Lattner4b009652007-07-25 00:24:17 +0000304 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
305 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000306 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000307 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000308 StringToks[NumStringToks-1].getLocation());
309}
310
Chris Lattnerb2ebd482008-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 Naroff0acc9c92007-09-15 18:49:24 +0000341/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000342/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000343/// identifier is used in a function call context.
Argiris Kirtzidis054a2632008-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 Naroff0acc9c92007-09-15 18:49:24 +0000346Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000347 IdentifierInfo &II,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000348 bool HasTrailingLParen,
349 const CXXScopeSpec *SS) {
Douglas Gregoraee3bf82008-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 Lattnerc72d22d2008-03-31 00:36:02 +0000371 // Could be enum-constant, value decl, instance variable, etc.
Argiris Kirtzidis054a2632008-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 Gregoraee3bf82008-11-18 15:03:34 +0000377 D = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000378 } else
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000379 D = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000380
381 // If this reference is in an Objective-C method, then ivar lookup happens as
382 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000383 IdentifierInfo *II = Name.getAsIdentifierInfo();
384 if (II && getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000385 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-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 Naroffe57c21a2008-04-01 23:04:06 +0000391 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000392 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000393 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-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 Naroff0ccfaa42008-08-10 19:10:41 +0000402 // Needed to implement property "super.method" notation.
Chris Lattner87fada82008-11-20 05:35:30 +0000403 if (SD == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000404 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000405 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000406 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000407 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000408 }
Chris Lattner4b009652007-07-25 00:24:17 +0000409 if (D == 0) {
410 // Otherwise, this could be an implicitly declared function reference (legal
411 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000412 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000413 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000414 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000415 else {
416 // If this name wasn't predeclared and if this is not a function call,
417 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000418 if (SS && !SS->isEmpty())
Chris Lattner77d52da2008-11-20 06:06:08 +0000419 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattnerb1753422008-11-23 21:45:46 +0000420 << Name << SS->getRange();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000421 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
422 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000423 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000424 else
Chris Lattnerb1753422008-11-23 21:45:46 +0000425 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000426 }
427 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000428
Argiris Kirtzidis38f16712008-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 Lattner8ba580c2008-11-19 05:08:23 +0000433 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattner271d4c22008-11-24 05:29:24 +0000434 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000435 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
436 // "invalid use of nonstatic data member 'x'"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000437 return Diag(Loc, diag::err_invalid_non_static_member_use)
Chris Lattner271d4c22008-11-24 05:29:24 +0000438 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000439
440 if (FD->isInvalidDecl())
441 return true;
442
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +0000443 // FIXME: Handle 'mutable'.
444 return new DeclRefExpr(FD,
445 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000446 }
447
Chris Lattner271d4c22008-11-24 05:29:24 +0000448 return Diag(Loc, diag::err_invalid_non_static_member_use)
449 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000450 }
Chris Lattner4b009652007-07-25 00:24:17 +0000451 if (isa<TypedefDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000452 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremenek42730c52008-01-07 19:49:32 +0000453 if (isa<ObjCInterfaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000454 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000455 if (isa<NamespaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000456 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000457
Steve Naroffd6163f32008-09-05 22:11:13 +0000458 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000459 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
460 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
461
Steve Naroffd6163f32008-09-05 22:11:13 +0000462 ValueDecl *VD = cast<ValueDecl>(D);
463
464 // check if referencing an identifier with __attribute__((deprecated)).
465 if (VD->getAttr<DeprecatedAttr>())
Chris Lattner271d4c22008-11-24 05:29:24 +0000466 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Steve Naroffd6163f32008-09-05 22:11:13 +0000467
468 // Only create DeclRefExpr's for valid Decl's.
469 if (VD->isInvalidDecl())
470 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000471
472 // If the identifier reference is inside a block, and it refers to a value
473 // that is outside the block, create a BlockDeclRefExpr instead of a
474 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
475 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000476 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000477 // We do not do this for things like enum constants, global variables, etc,
478 // as they do not get snapshotted.
479 //
480 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000481 // The BlocksAttr indicates the variable is bound by-reference.
482 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000483 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
484 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000485
486 // Variable will be bound by-copy, make it const within the closure.
487 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000488 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
489 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000490 }
491 // If this reference is not in a block or if the referenced variable is
492 // within the block, create a normal DeclRefExpr.
Douglas Gregor3fb675a2008-10-22 04:14:44 +0000493 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Chris Lattner4b009652007-07-25 00:24:17 +0000494}
495
Chris Lattner69909292008-08-10 01:53:14 +0000496Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000497 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000498 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000499
500 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000501 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000502 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
503 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
504 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000505 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000506
507 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000508 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000509 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000510
Chris Lattner7e637512008-01-12 08:14:25 +0000511 // Pre-defined identifiers are of type char[x], where x is the length of the
512 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000513 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000514 if (getCurFunctionDecl())
515 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000516 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000517 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000518
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000519 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000520 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000521 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000522 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000523}
524
Steve Naroff87d58b42007-09-16 03:34:24 +0000525Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000526 llvm::SmallString<16> CharBuffer;
527 CharBuffer.resize(Tok.getLength());
528 const char *ThisTokBegin = &CharBuffer[0];
529 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
530
531 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
532 Tok.getLocation(), PP);
533 if (Literal.hadError())
534 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000535
536 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
537
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000538 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
539 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000540}
541
Steve Naroff87d58b42007-09-16 03:34:24 +0000542Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000543 // fast path for a single digit (which is quite common). A single digit
544 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
545 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000546 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000547
Chris Lattner8cd0e932008-03-05 18:54:05 +0000548 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000549 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000550 Context.IntTy,
551 Tok.getLocation()));
552 }
553 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000554 // Add padding so that NumericLiteralParser can overread by one character.
555 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000556 const char *ThisTokBegin = &IntegerBuffer[0];
557
558 // Get the spelling of the token, which eliminates trigraphs, etc.
559 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000560
Chris Lattner4b009652007-07-25 00:24:17 +0000561 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
562 Tok.getLocation(), PP);
563 if (Literal.hadError)
564 return ExprResult(true);
565
Chris Lattner1de66eb2007-08-26 03:42:43 +0000566 Expr *Res;
567
568 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000569 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000570 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000571 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000572 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000573 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000574 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000575 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000576
577 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
578
Ted Kremenekddedbe22007-11-29 00:56:49 +0000579 // isExact will be set by GetFloatValue().
580 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000581 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000582 Ty, Tok.getLocation());
583
Chris Lattner1de66eb2007-08-26 03:42:43 +0000584 } else if (!Literal.isIntegerLiteral()) {
585 return ExprResult(true);
586 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000587 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000588
Neil Booth7421e9c2007-08-29 22:00:19 +0000589 // long long is a C99 feature.
590 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000591 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000592 Diag(Tok.getLocation(), diag::ext_longlong);
593
Chris Lattner4b009652007-07-25 00:24:17 +0000594 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000595 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000596
597 if (Literal.GetIntegerValue(ResultVal)) {
598 // If this value didn't fit into uintmax_t, warn and force to ull.
599 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000600 Ty = Context.UnsignedLongLongTy;
601 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000602 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000603 } else {
604 // If this value fits into a ULL, try to figure out what else it fits into
605 // according to the rules of C99 6.4.4.1p5.
606
607 // Octal, Hexadecimal, and integers with a U suffix are allowed to
608 // be an unsigned int.
609 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
610
611 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000612 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000613 if (!Literal.isLong && !Literal.isLongLong) {
614 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000615 unsigned IntSize = Context.Target.getIntWidth();
616
Chris Lattner4b009652007-07-25 00:24:17 +0000617 // Does it fit in a unsigned int?
618 if (ResultVal.isIntN(IntSize)) {
619 // Does it fit in a signed int?
620 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000621 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000622 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000623 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000624 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000625 }
Chris Lattner4b009652007-07-25 00:24:17 +0000626 }
627
628 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000629 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000630 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000631
632 // Does it fit in a unsigned long?
633 if (ResultVal.isIntN(LongSize)) {
634 // Does it fit in a signed long?
635 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000636 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000637 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000638 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000639 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000640 }
Chris Lattner4b009652007-07-25 00:24:17 +0000641 }
642
643 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000644 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000645 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000646
647 // Does it fit in a unsigned long long?
648 if (ResultVal.isIntN(LongLongSize)) {
649 // Does it fit in a signed long long?
650 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000651 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000652 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000653 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000654 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000655 }
656 }
657
658 // If we still couldn't decide a type, we probably have something that
659 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000660 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000661 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000662 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000663 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000664 }
Chris Lattnere4068872008-05-09 05:59:00 +0000665
666 if (ResultVal.getBitWidth() != Width)
667 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000668 }
669
Chris Lattner48d7f382008-04-02 04:24:33 +0000670 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000671 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000672
673 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
674 if (Literal.isImaginary)
675 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
676
677 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000678}
679
Steve Naroff87d58b42007-09-16 03:34:24 +0000680Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000681 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000682 Expr *E = (Expr *)Val;
683 assert((E != 0) && "ActOnParenExpr() missing expr");
684 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000685}
686
687/// The UsualUnaryConversions() function is *not* called by this routine.
688/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000689bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
690 SourceLocation OpLoc,
691 const SourceRange &ExprRange,
692 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000693 // C99 6.5.3.4p1:
694 if (isa<FunctionType>(exprType) && isSizeof)
695 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000696 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +0000697 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000698 Diag(OpLoc, diag::ext_sizeof_void_type)
699 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
700 else if (exprType->isIncompleteType())
701 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
702 diag::err_alignof_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000703 << exprType << ExprRange;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000704
705 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000706}
707
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000708/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
709/// the same for @c alignof and @c __alignof
710/// Note that the ArgRange is invalid if isType is false.
711Action::ExprResult
712Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
713 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +0000714 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000715 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000716
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000717 QualType ArgTy;
718 SourceRange Range;
719 if (isType) {
720 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
721 Range = ArgRange;
722 } else {
723 // Get the end location.
724 Expr *ArgEx = (Expr *)TyOrEx;
725 Range = ArgEx->getSourceRange();
726 ArgTy = ArgEx->getType();
727 }
728
729 // Verify that the operand is valid.
730 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +0000731 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000732
733 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
734 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
735 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +0000736}
737
Chris Lattner5110ad52007-08-24 21:41:10 +0000738QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000739 DefaultFunctionArrayConversion(V);
740
Chris Lattnera16e42d2007-08-26 05:39:26 +0000741 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000742 if (const ComplexType *CT = V->getType()->getAsComplexType())
743 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000744
745 // Otherwise they pass through real integer and floating point types here.
746 if (V->getType()->isArithmeticType())
747 return V->getType();
748
749 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +0000750 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000751 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000752}
753
754
Chris Lattner4b009652007-07-25 00:24:17 +0000755
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000756Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000757 tok::TokenKind Kind,
758 ExprTy *Input) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000759 Expr *Arg = (Expr *)Input;
760
Chris Lattner4b009652007-07-25 00:24:17 +0000761 UnaryOperator::Opcode Opc;
762 switch (Kind) {
763 default: assert(0 && "Unknown unary op!");
764 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
765 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
766 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000767
768 if (getLangOptions().CPlusPlus &&
769 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
770 // Which overloaded operator?
771 OverloadedOperatorKind OverOp =
772 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
773
774 // C++ [over.inc]p1:
775 //
776 // [...] If the function is a member function with one
777 // parameter (which shall be of type int) or a non-member
778 // function with two parameters (the second of which shall be
779 // of type int), it defines the postfix increment operator ++
780 // for objects of that type. When the postfix increment is
781 // called as a result of using the ++ operator, the int
782 // argument will have value zero.
783 Expr *Args[2] = {
784 Arg,
785 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
786 /*isSigned=*/true),
787 Context.IntTy, SourceLocation())
788 };
789
790 // Build the candidate set for overloading
791 OverloadCandidateSet CandidateSet;
792 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
793
794 // Perform overload resolution.
795 OverloadCandidateSet::iterator Best;
796 switch (BestViableFunction(CandidateSet, Best)) {
797 case OR_Success: {
798 // We found a built-in operator or an overloaded operator.
799 FunctionDecl *FnDecl = Best->Function;
800
801 if (FnDecl) {
802 // We matched an overloaded operator. Build a call to that
803 // operator.
804
805 // Convert the arguments.
806 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
807 if (PerformObjectArgumentInitialization(Arg, Method))
808 return true;
809 } else {
810 // Convert the arguments.
811 if (PerformCopyInitialization(Arg,
812 FnDecl->getParamDecl(0)->getType(),
813 "passing"))
814 return true;
815 }
816
817 // Determine the result type
818 QualType ResultTy
819 = FnDecl->getType()->getAsFunctionType()->getResultType();
820 ResultTy = ResultTy.getNonReferenceType();
821
822 // Build the actual expression node.
823 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
824 SourceLocation());
825 UsualUnaryConversions(FnExpr);
826
827 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
828 } else {
829 // We matched a built-in operator. Convert the arguments, then
830 // break out so that we will build the appropriate built-in
831 // operator node.
832 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
833 "passing"))
834 return true;
835
836 break;
837 }
838 }
839
840 case OR_No_Viable_Function:
841 // No viable function; fall through to handling this as a
842 // built-in operator, which will produce an error message for us.
843 break;
844
845 case OR_Ambiguous:
846 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
847 << UnaryOperator::getOpcodeStr(Opc)
848 << Arg->getSourceRange();
849 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
850 return true;
851 }
852
853 // Either we found no viable overloaded operator or we matched a
854 // built-in operator. In either case, fall through to trying to
855 // build a built-in operation.
856 }
857
858 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000859 if (result.isNull())
860 return true;
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000861 return new UnaryOperator(Arg, Opc, result, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000862}
863
864Action::ExprResult Sema::
Douglas Gregor80723c52008-11-19 17:17:41 +0000865ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000866 ExprTy *Idx, SourceLocation RLoc) {
867 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
868
Douglas Gregor80723c52008-11-19 17:17:41 +0000869 if (getLangOptions().CPlusPlus &&
870 LHSExp->getType()->isRecordType() ||
871 LHSExp->getType()->isEnumeralType() ||
872 RHSExp->getType()->isRecordType() ||
873 RHSExp->getType()->isRecordType()) {
874 // Add the appropriate overloaded operators (C++ [over.match.oper])
875 // to the candidate set.
876 OverloadCandidateSet CandidateSet;
877 Expr *Args[2] = { LHSExp, RHSExp };
878 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
879
880 // Perform overload resolution.
881 OverloadCandidateSet::iterator Best;
882 switch (BestViableFunction(CandidateSet, Best)) {
883 case OR_Success: {
884 // We found a built-in operator or an overloaded operator.
885 FunctionDecl *FnDecl = Best->Function;
886
887 if (FnDecl) {
888 // We matched an overloaded operator. Build a call to that
889 // operator.
890
891 // Convert the arguments.
892 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
893 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
894 PerformCopyInitialization(RHSExp,
895 FnDecl->getParamDecl(0)->getType(),
896 "passing"))
897 return true;
898 } else {
899 // Convert the arguments.
900 if (PerformCopyInitialization(LHSExp,
901 FnDecl->getParamDecl(0)->getType(),
902 "passing") ||
903 PerformCopyInitialization(RHSExp,
904 FnDecl->getParamDecl(1)->getType(),
905 "passing"))
906 return true;
907 }
908
909 // Determine the result type
910 QualType ResultTy
911 = FnDecl->getType()->getAsFunctionType()->getResultType();
912 ResultTy = ResultTy.getNonReferenceType();
913
914 // Build the actual expression node.
915 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
916 SourceLocation());
917 UsualUnaryConversions(FnExpr);
918
919 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
920 } else {
921 // We matched a built-in operator. Convert the arguments, then
922 // break out so that we will build the appropriate built-in
923 // operator node.
924 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
925 "passing") ||
926 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
927 "passing"))
928 return true;
929
930 break;
931 }
932 }
933
934 case OR_No_Viable_Function:
935 // No viable function; fall through to handling this as a
936 // built-in operator, which will produce an error message for us.
937 break;
938
939 case OR_Ambiguous:
940 Diag(LLoc, diag::err_ovl_ambiguous_oper)
941 << "[]"
942 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
943 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
944 return true;
945 }
946
947 // Either we found no viable overloaded operator or we matched a
948 // built-in operator. In either case, fall through to trying to
949 // build a built-in operation.
950 }
951
Chris Lattner4b009652007-07-25 00:24:17 +0000952 // Perform default conversions.
953 DefaultFunctionArrayConversion(LHSExp);
954 DefaultFunctionArrayConversion(RHSExp);
955
956 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
957
958 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000959 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000960 // in the subscript position. As a result, we need to derive the array base
961 // and index from the expression types.
962 Expr *BaseExpr, *IndexExpr;
963 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000964 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000965 BaseExpr = LHSExp;
966 IndexExpr = RHSExp;
967 // FIXME: need to deal with const...
968 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000969 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000970 // Handle the uncommon case of "123[Ptr]".
971 BaseExpr = RHSExp;
972 IndexExpr = LHSExp;
973 // FIXME: need to deal with const...
974 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000975 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
976 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000977 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000978
979 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000980 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
981 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +0000982 return Diag(LLoc, diag::err_ext_vector_component_access)
983 << SourceRange(LLoc, RLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000984 // FIXME: need to deal with const...
985 ResultType = VTy->getElementType();
986 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000987 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
988 << RHSExp->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +0000989 }
990 // C99 6.5.2.1p1
991 if (!IndexExpr->getType()->isIntegerType())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000992 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
993 << IndexExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +0000994
995 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
996 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000997 // void (*)(int)) and pointers to incomplete types. Functions are not
998 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000999 if (!ResultType->isObjectType())
1000 return Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001001 diag::err_typecheck_subscript_not_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001002 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001003
1004 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
1005}
1006
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001007QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001008CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001009 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001010 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001011
1012 // This flag determines whether or not the component is to be treated as a
1013 // special name, or a regular GLSL-style component access.
1014 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001015
1016 // The vector accessor can't exceed the number of elements.
1017 const char *compStr = CompName.getName();
1018 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001019 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001020 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001021 return QualType();
1022 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001023
1024 // Check that we've found one of the special components, or that the component
1025 // names must come from the same set.
1026 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1027 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1028 SpecialComponent = true;
1029 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001030 do
1031 compStr++;
1032 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1033 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1034 do
1035 compStr++;
1036 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1037 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1038 do
1039 compStr++;
1040 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1041 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001042
Nate Begemanc8e51f82008-05-09 06:41:27 +00001043 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001044 // We didn't get to the end of the string. This means the component names
1045 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001046 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1047 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001048 return QualType();
1049 }
1050 // Each component accessor can't exceed the vector type.
1051 compStr = CompName.getName();
1052 while (*compStr) {
1053 if (vecType->isAccessorWithinNumElements(*compStr))
1054 compStr++;
1055 else
1056 break;
1057 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001058 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001059 // We didn't get to the end of the string. This means a component accessor
1060 // exceeds the number of elements in the vector.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001061 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001062 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001063 return QualType();
1064 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001065
1066 // If we have a special component name, verify that the current vector length
1067 // is an even number, since all special component names return exactly half
1068 // the elements.
1069 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001070 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001071 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001072 return QualType();
1073 }
1074
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001075 // The component accessor looks fine - now we need to compute the actual type.
1076 // The vector type is implied by the component accessor. For example,
1077 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001078 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1079 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner65cae292008-11-19 08:23:25 +00001080 : CompName.getLength();
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001081 if (CompSize == 1)
1082 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001083
Nate Begemanaf6ed502008-04-18 23:10:10 +00001084 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001085 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001086 // diagostics look bad. We want extended vector types to appear built-in.
1087 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1088 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1089 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001090 }
1091 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001092}
1093
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001094/// constructSetterName - Return the setter name for the given
1095/// identifier, i.e. "set" + Name where the initial character of Name
1096/// has been capitalized.
1097// FIXME: Merge with same routine in Parser. But where should this
1098// live?
1099static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1100 const IdentifierInfo *Name) {
1101 llvm::SmallString<100> SelectorName;
1102 SelectorName = "set";
1103 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1104 SelectorName[3] = toupper(SelectorName[3]);
1105 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1106}
1107
Chris Lattner4b009652007-07-25 00:24:17 +00001108Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001109ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001110 tok::TokenKind OpKind, SourceLocation MemberLoc,
1111 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001112 Expr *BaseExpr = static_cast<Expr *>(Base);
1113 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001114
1115 // Perform default conversions.
1116 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +00001117
Steve Naroff2cb66382007-07-26 03:11:44 +00001118 QualType BaseType = BaseExpr->getType();
1119 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001120
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001121 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1122 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001123 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001124 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001125 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001126 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
1127 return BuildOverloadedArrowExpr(BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroff2cb66382007-07-26 03:11:44 +00001128 else
Chris Lattner8ba580c2008-11-19 05:08:23 +00001129 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001130 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001131 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001132
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001133 // Handle field access to simple records. This also handles access to fields
1134 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001135 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001136 RecordDecl *RDecl = RTy->getDecl();
1137 if (RTy->isIncompleteType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001138 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattner271d4c22008-11-24 05:29:24 +00001139 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroff2cb66382007-07-26 03:11:44 +00001140 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001141 FieldDecl *MemberDecl = RDecl->getMember(&Member);
1142 if (!MemberDecl)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001143 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner65cae292008-11-19 08:23:25 +00001144 << &Member << BaseExpr->getSourceRange();
Eli Friedman76b49832008-02-06 22:48:16 +00001145
1146 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +00001147 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +00001148 QualType MemberType = MemberDecl->getType();
1149 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +00001150 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +00001151 if (CXXFieldDecl *CXXMember = dyn_cast<CXXFieldDecl>(MemberDecl)) {
1152 if (CXXMember->isMutable())
1153 combinedQualifiers &= ~QualType::Const;
1154 }
Eli Friedman76b49832008-02-06 22:48:16 +00001155 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1156
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001157 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +00001158 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +00001159 }
1160
Chris Lattnere9d71612008-07-21 04:59:05 +00001161 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1162 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001163 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
1164 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001165 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +00001166 OpKind == tok::arrow);
Chris Lattner8ba580c2008-11-19 05:08:23 +00001167 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattner271d4c22008-11-24 05:29:24 +00001168 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattner8ba580c2008-11-19 05:08:23 +00001169 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001170 }
1171
Chris Lattnere9d71612008-07-21 04:59:05 +00001172 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1173 // pointer to a (potentially qualified) interface type.
1174 const PointerType *PTy;
1175 const ObjCInterfaceType *IFTy;
1176 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1177 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1178 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001179
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001180 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001181 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1182 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1183
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001184 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001185 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1186 E = IFTy->qual_end(); I != E; ++I)
1187 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1188 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001189
1190 // If that failed, look for an "implicit" property by seeing if the nullary
1191 // selector is implemented.
1192
1193 // FIXME: The logic for looking up nullary and unary selectors should be
1194 // shared with the code in ActOnInstanceMessage.
1195
1196 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1197 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1198
1199 // If this reference is in an @implementation, check for 'private' methods.
1200 if (!Getter)
1201 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1202 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1203 if (ObjCImplementationDecl *ImpDecl =
1204 ObjCImplementations[ClassDecl->getIdentifier()])
1205 Getter = ImpDecl->getInstanceMethod(Sel);
1206
Steve Naroff04151f32008-10-22 19:16:27 +00001207 // Look through local category implementations associated with the class.
1208 if (!Getter) {
1209 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1210 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1211 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1212 }
1213 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001214 if (Getter) {
1215 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001216 // will look for the matching setter, in case it is needed.
1217 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1218 &Member);
1219 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1220 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1221 if (!Setter) {
1222 // If this reference is in an @implementation, also check for 'private'
1223 // methods.
1224 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1225 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1226 if (ObjCImplementationDecl *ImpDecl =
1227 ObjCImplementations[ClassDecl->getIdentifier()])
1228 Setter = ImpDecl->getInstanceMethod(SetterSel);
1229 }
1230 // Look through local category implementations associated with the class.
1231 if (!Setter) {
1232 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1233 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1234 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1235 }
1236 }
1237
1238 // FIXME: we must check that the setter has property type.
1239 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00001240 MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001241 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001242 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001243 // Handle properties on qualified "id" protocols.
1244 const ObjCQualifiedIdType *QIdTy;
1245 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1246 // Check protocols on qualified interfaces.
1247 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1248 E = QIdTy->qual_end(); I != E; ++I)
1249 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1250 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1251 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001252 // Handle 'field access' to vectors, such as 'V.xx'.
1253 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1254 // Component access limited to variables (reject vec4.rg.g).
1255 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1256 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001257 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1258 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001259 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1260 if (ret.isNull())
1261 return true;
1262 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1263 }
1264
Chris Lattner8ba580c2008-11-19 05:08:23 +00001265 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001266 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001267}
1268
Steve Naroff87d58b42007-09-16 03:34:24 +00001269/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001270/// This provides the location of the left/right parens and a list of comma
1271/// locations.
1272Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001273ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001274 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001275 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1276 Expr *Fn = static_cast<Expr *>(fn);
1277 Expr **Args = reinterpret_cast<Expr**>(args);
1278 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001279 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001280 OverloadedFunctionDecl *Ovl = NULL;
1281
1282 // If we're directly calling a function or a set of overloaded
1283 // functions, get the appropriate declaration.
1284 {
1285 DeclRefExpr *DRExpr = NULL;
1286 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1287 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1288 else
1289 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1290
1291 if (DRExpr) {
1292 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1293 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1294 }
1295 }
1296
1297 // If we have a set of overloaded functions, perform overload
1298 // resolution to pick the function.
1299 if (Ovl) {
1300 OverloadCandidateSet CandidateSet;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001301 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
Douglas Gregor10f3c502008-11-19 21:05:33 +00001302 OverloadCandidateSet::iterator Best;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001303 switch (BestViableFunction(CandidateSet, Best)) {
1304 case OR_Success:
1305 {
1306 // Success! Let the remainder of this function build a call to
1307 // the function selected by overload resolution.
1308 FDecl = Best->Function;
1309 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1310 Fn->getSourceRange().getBegin());
1311 delete Fn;
1312 Fn = NewFn;
1313 }
1314 break;
1315
1316 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00001317 Diag(Fn->getSourceRange().getBegin(),
1318 diag::err_ovl_no_viable_function_in_call)
Chris Lattner271d4c22008-11-24 05:29:24 +00001319 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00001320 << Fn->getSourceRange();
1321 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord2baafd2008-10-21 16:13:35 +00001322 return true;
1323
1324 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00001325 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Chris Lattner271d4c22008-11-24 05:29:24 +00001326 << Ovl->getDeclName() << Fn->getSourceRange();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001327 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1328 return true;
1329 }
1330 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001331
Douglas Gregor10f3c502008-11-19 21:05:33 +00001332 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
1333 return BuildCallToObjectOfClassType(Fn, LParenLoc, Args, NumArgs,
1334 CommaLocs, RParenLoc);
1335
Chris Lattner3e254fb2008-04-08 04:40:51 +00001336 // Promote the function operand.
1337 UsualUnaryConversions(Fn);
1338
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001339 // Make the call expr early, before semantic checks. This guarantees cleanup
1340 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001341 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001342 Context.BoolTy, RParenLoc));
Steve Naroffd6163f32008-09-05 22:11:13 +00001343 const FunctionType *FuncT;
1344 if (!Fn->getType()->isBlockPointerType()) {
1345 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1346 // have type pointer to function".
1347 const PointerType *PT = Fn->getType()->getAsPointerType();
1348 if (PT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001349 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001350 << Fn->getType() << Fn->getSourceRange();
Steve Naroffd6163f32008-09-05 22:11:13 +00001351 FuncT = PT->getPointeeType()->getAsFunctionType();
1352 } else { // This is a block call.
1353 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1354 getAsFunctionType();
1355 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001356 if (FuncT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001357 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001358 << Fn->getType() << Fn->getSourceRange();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001359
1360 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001361 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001362
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001363 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001364 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1365 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001366 unsigned NumArgsInProto = Proto->getNumArgs();
1367 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001368
Chris Lattner3e254fb2008-04-08 04:40:51 +00001369 // If too few arguments are available (and we don't have default
1370 // arguments for the remaining parameters), don't make the call.
1371 if (NumArgs < NumArgsInProto) {
Chris Lattner66beaba2008-11-21 18:44:24 +00001372 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1373 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1374 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1375 // Use default arguments for missing arguments
1376 NumArgsToCheck = NumArgsInProto;
1377 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001378 }
1379
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001380 // If too many are passed and not variadic, error on the extras and drop
1381 // them.
1382 if (NumArgs > NumArgsInProto) {
1383 if (!Proto->isVariadic()) {
Chris Lattner66beaba2008-11-21 18:44:24 +00001384 Diag(Args[NumArgsInProto]->getLocStart(),
1385 diag::err_typecheck_call_too_many_args)
1386 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
Chris Lattner8ba580c2008-11-19 05:08:23 +00001387 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1388 Args[NumArgs-1]->getLocEnd());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001389 // This deletes the extra arguments.
1390 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001391 }
1392 NumArgsToCheck = NumArgsInProto;
1393 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001394
Chris Lattner4b009652007-07-25 00:24:17 +00001395 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001396 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001397 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001398
1399 Expr *Arg;
1400 if (i < NumArgs)
1401 Arg = Args[i];
1402 else
1403 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001404 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001405
Douglas Gregor81c29152008-10-29 00:13:59 +00001406 // Pass the argument.
1407 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner005ed752008-01-04 18:04:52 +00001408 return true;
Douglas Gregor81c29152008-10-29 00:13:59 +00001409
1410 TheCall->setArg(i, Arg);
Chris Lattner4b009652007-07-25 00:24:17 +00001411 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001412
1413 // If this is a variadic call, handle args passed through "...".
1414 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001415 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001416 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1417 Expr *Arg = Args[i];
1418 DefaultArgumentPromotion(Arg);
1419 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001420 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001421 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001422 } else {
1423 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1424
Steve Naroffdb65e052007-08-28 23:30:39 +00001425 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001426 for (unsigned i = 0; i != NumArgs; i++) {
1427 Expr *Arg = Args[i];
1428 DefaultArgumentPromotion(Arg);
1429 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001430 }
Chris Lattner4b009652007-07-25 00:24:17 +00001431 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001432
Chris Lattner2e64c072007-08-10 20:18:51 +00001433 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001434 if (FDecl)
1435 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001436
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001437 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001438}
1439
1440Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001441ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001442 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001443 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001444 QualType literalType = QualType::getFromOpaquePtr(Ty);
1445 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001446 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001447 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001448
Eli Friedman8c2173d2008-05-20 05:22:08 +00001449 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001450 if (literalType->isVariableArrayType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001451 return Diag(LParenLoc, diag::err_variable_object_no_init)
1452 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001453 } else if (literalType->isIncompleteType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001454 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +00001455 << literalType
Chris Lattner8ba580c2008-11-19 05:08:23 +00001456 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001457 }
1458
Douglas Gregor6428e762008-11-05 15:29:30 +00001459 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Chris Lattner271d4c22008-11-24 05:29:24 +00001460 DeclarationName()))
Steve Naroff92590f92008-01-09 20:58:06 +00001461 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001462
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001463 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001464 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001465 if (CheckForConstantInitializer(literalExpr, literalType))
1466 return true;
1467 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001468 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1469 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001470}
1471
1472Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001473ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001474 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001475 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001476 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001477
Steve Naroff0acc9c92007-09-15 18:49:24 +00001478 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001479 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001480
Chris Lattner71ca8c82008-10-26 23:43:26 +00001481 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1482 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001483 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1484 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001485}
1486
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001487/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001488bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001489 UsualUnaryConversions(castExpr);
1490
1491 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1492 // type needs to be scalar.
1493 if (castType->isVoidType()) {
1494 // Cast to void allows any expr type.
1495 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1496 // GCC struct/union extension: allow cast to self.
1497 if (Context.getCanonicalType(castType) !=
1498 Context.getCanonicalType(castExpr->getType()) ||
1499 (!castType->isStructureType() && !castType->isUnionType())) {
1500 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001501 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001502 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001503 }
1504
1505 // accept this, but emit an ext-warn.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001506 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001507 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001508 } else if (!castExpr->getType()->isScalarType() &&
1509 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001510 return Diag(castExpr->getLocStart(),
1511 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001512 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001513 } else if (castExpr->getType()->isVectorType()) {
1514 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1515 return true;
1516 } else if (castType->isVectorType()) {
1517 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1518 return true;
1519 }
1520 return false;
1521}
1522
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001523bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001524 assert(VectorTy->isVectorType() && "Not a vector type!");
1525
1526 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001527 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001528 return Diag(R.getBegin(),
1529 Ty->isVectorType() ?
1530 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00001531 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001532 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001533 } else
1534 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001535 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001536 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001537
1538 return false;
1539}
1540
Chris Lattner4b009652007-07-25 00:24:17 +00001541Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001542ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001543 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001544 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001545
1546 Expr *castExpr = static_cast<Expr*>(Op);
1547 QualType castType = QualType::getFromOpaquePtr(Ty);
1548
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001549 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1550 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00001551 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001552}
1553
Chris Lattner98a425c2007-11-26 01:40:58 +00001554/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1555/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001556inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1557 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1558 UsualUnaryConversions(cond);
1559 UsualUnaryConversions(lex);
1560 UsualUnaryConversions(rex);
1561 QualType condT = cond->getType();
1562 QualType lexT = lex->getType();
1563 QualType rexT = rex->getType();
1564
1565 // first, check the condition.
1566 if (!condT->isScalarType()) { // C99 6.5.15p2
Chris Lattner4bfd2232008-11-24 06:25:27 +00001567 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
Chris Lattner4b009652007-07-25 00:24:17 +00001568 return QualType();
1569 }
Chris Lattner992ae932008-01-06 22:42:25 +00001570
1571 // Now check the two expressions.
1572
1573 // If both operands have arithmetic type, do the usual arithmetic conversions
1574 // to find a common type: C99 6.5.15p3,5.
1575 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001576 UsualArithmeticConversions(lex, rex);
1577 return lex->getType();
1578 }
Chris Lattner992ae932008-01-06 22:42:25 +00001579
1580 // If both operands are the same structure or union type, the result is that
1581 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001582 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001583 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001584 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001585 // "If both the operands have structure or union type, the result has
1586 // that type." This implies that CV qualifiers are dropped.
1587 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001588 }
Chris Lattner992ae932008-01-06 22:42:25 +00001589
1590 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001591 // The following || allows only one side to be void (a GCC-ism).
1592 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001593 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001594 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
1595 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00001596 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001597 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
1598 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00001599 ImpCastExprToType(lex, Context.VoidTy);
1600 ImpCastExprToType(rex, Context.VoidTy);
1601 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001602 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001603 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1604 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001605 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1606 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001607 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001608 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001609 return lexT;
1610 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001611 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1612 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001613 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001614 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001615 return rexT;
1616 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001617 // Handle the case where both operands are pointers before we handle null
1618 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001619 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1620 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1621 // get the "pointed to" types
1622 QualType lhptee = LHSPT->getPointeeType();
1623 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001624
Chris Lattner71225142007-07-31 21:27:01 +00001625 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1626 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001627 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001628 // Figure out necessary qualifiers (C99 6.5.15p6)
1629 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001630 QualType destType = Context.getPointerType(destPointee);
1631 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1632 ImpCastExprToType(rex, destType); // promote to void*
1633 return destType;
1634 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001635 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001636 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001637 QualType destType = Context.getPointerType(destPointee);
1638 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1639 ImpCastExprToType(rex, destType); // promote to void*
1640 return destType;
1641 }
Chris Lattner4b009652007-07-25 00:24:17 +00001642
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001643 QualType compositeType = lexT;
1644
1645 // If either type is an Objective-C object type then check
1646 // compatibility according to Objective-C.
1647 if (Context.isObjCObjectPointerType(lexT) ||
1648 Context.isObjCObjectPointerType(rexT)) {
1649 // If both operands are interfaces and either operand can be
1650 // assigned to the other, use that type as the composite
1651 // type. This allows
1652 // xxx ? (A*) a : (B*) b
1653 // where B is a subclass of A.
1654 //
1655 // Additionally, as for assignment, if either type is 'id'
1656 // allow silent coercion. Finally, if the types are
1657 // incompatible then make sure to use 'id' as the composite
1658 // type so the result is acceptable for sending messages to.
1659
1660 // FIXME: This code should not be localized to here. Also this
1661 // should use a compatible check instead of abusing the
1662 // canAssignObjCInterfaces code.
1663 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1664 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1665 if (LHSIface && RHSIface &&
1666 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1667 compositeType = lexT;
1668 } else if (LHSIface && RHSIface &&
1669 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1670 compositeType = rexT;
1671 } else if (Context.isObjCIdType(lhptee) ||
1672 Context.isObjCIdType(rhptee)) {
1673 // FIXME: This code looks wrong, because isObjCIdType checks
1674 // the struct but getObjCIdType returns the pointer to
1675 // struct. This is horrible and should be fixed.
1676 compositeType = Context.getObjCIdType();
1677 } else {
1678 QualType incompatTy = Context.getObjCIdType();
1679 ImpCastExprToType(lex, incompatTy);
1680 ImpCastExprToType(rex, incompatTy);
1681 return incompatTy;
1682 }
1683 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1684 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00001685 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001686 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001687 // In this situation, we assume void* type. No especially good
1688 // reason, but this is what gcc does, and we do have to pick
1689 // to get a consistent AST.
1690 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001691 ImpCastExprToType(lex, incompatTy);
1692 ImpCastExprToType(rex, incompatTy);
1693 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001694 }
1695 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001696 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1697 // differently qualified versions of compatible types, the result type is
1698 // a pointer to an appropriately qualified version of the *composite*
1699 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001700 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001701 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001702 ImpCastExprToType(lex, compositeType);
1703 ImpCastExprToType(rex, compositeType);
1704 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001705 }
Chris Lattner4b009652007-07-25 00:24:17 +00001706 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001707 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1708 // evaluates to "struct objc_object *" (and is handled above when comparing
1709 // id with statically typed objects).
1710 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1711 // GCC allows qualified id and any Objective-C type to devolve to
1712 // id. Currently localizing to here until clear this should be
1713 // part of ObjCQualifiedIdTypesAreCompatible.
1714 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1715 (lexT->isObjCQualifiedIdType() &&
1716 Context.isObjCObjectPointerType(rexT)) ||
1717 (rexT->isObjCQualifiedIdType() &&
1718 Context.isObjCObjectPointerType(lexT))) {
1719 // FIXME: This is not the correct composite type. This only
1720 // happens to work because id can more or less be used anywhere,
1721 // however this may change the type of method sends.
1722 // FIXME: gcc adds some type-checking of the arguments and emits
1723 // (confusing) incompatible comparison warnings in some
1724 // cases. Investigate.
1725 QualType compositeType = Context.getObjCIdType();
1726 ImpCastExprToType(lex, compositeType);
1727 ImpCastExprToType(rex, compositeType);
1728 return compositeType;
1729 }
1730 }
1731
Steve Naroff3eac7692008-09-10 19:17:48 +00001732 // Selection between block pointer types is ok as long as they are the same.
1733 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1734 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1735 return lexT;
1736
Chris Lattner992ae932008-01-06 22:42:25 +00001737 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00001738 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001739 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001740 return QualType();
1741}
1742
Steve Naroff87d58b42007-09-16 03:34:24 +00001743/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001744/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001745Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001746 SourceLocation ColonLoc,
1747 ExprTy *Cond, ExprTy *LHS,
1748 ExprTy *RHS) {
1749 Expr *CondExpr = (Expr *) Cond;
1750 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001751
1752 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1753 // was the condition.
1754 bool isLHSNull = LHSExpr == 0;
1755 if (isLHSNull)
1756 LHSExpr = CondExpr;
1757
Chris Lattner4b009652007-07-25 00:24:17 +00001758 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1759 RHSExpr, QuestionLoc);
1760 if (result.isNull())
1761 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001762 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1763 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001764}
1765
Chris Lattner4b009652007-07-25 00:24:17 +00001766
1767// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1768// being closely modeled after the C99 spec:-). The odd characteristic of this
1769// routine is it effectively iqnores the qualifiers on the top level pointee.
1770// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1771// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001772Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001773Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1774 QualType lhptee, rhptee;
1775
1776 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001777 lhptee = lhsType->getAsPointerType()->getPointeeType();
1778 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001779
1780 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001781 lhptee = Context.getCanonicalType(lhptee);
1782 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001783
Chris Lattner005ed752008-01-04 18:04:52 +00001784 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001785
1786 // C99 6.5.16.1p1: This following citation is common to constraints
1787 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1788 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001789 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001790 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001791 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001792
1793 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1794 // incomplete type and the other is a pointer to a qualified or unqualified
1795 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001796 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001797 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001798 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001799
1800 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001801 assert(rhptee->isFunctionType());
1802 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001803 }
1804
1805 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001806 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001807 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001808
1809 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001810 assert(lhptee->isFunctionType());
1811 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001812 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001813
1814 // Check for ObjC interfaces
1815 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1816 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1817 if (LHSIface && RHSIface &&
1818 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1819 return ConvTy;
1820
1821 // ID acts sort of like void* for ObjC interfaces
1822 if (LHSIface && Context.isObjCIdType(rhptee))
1823 return ConvTy;
1824 if (RHSIface && Context.isObjCIdType(lhptee))
1825 return ConvTy;
1826
Chris Lattner4b009652007-07-25 00:24:17 +00001827 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1828 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001829 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1830 rhptee.getUnqualifiedType()))
1831 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001832 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001833}
1834
Steve Naroff3454b6c2008-09-04 15:10:53 +00001835/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1836/// block pointer types are compatible or whether a block and normal pointer
1837/// are compatible. It is more restrict than comparing two function pointer
1838// types.
1839Sema::AssignConvertType
1840Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1841 QualType rhsType) {
1842 QualType lhptee, rhptee;
1843
1844 // get the "pointed to" type (ignoring qualifiers at the top level)
1845 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1846 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1847
1848 // make sure we operate on the canonical type
1849 lhptee = Context.getCanonicalType(lhptee);
1850 rhptee = Context.getCanonicalType(rhptee);
1851
1852 AssignConvertType ConvTy = Compatible;
1853
1854 // For blocks we enforce that qualifiers are identical.
1855 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1856 ConvTy = CompatiblePointerDiscardsQualifiers;
1857
1858 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1859 return IncompatibleBlockPointer;
1860 return ConvTy;
1861}
1862
Chris Lattner4b009652007-07-25 00:24:17 +00001863/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1864/// has code to accommodate several GCC extensions when type checking
1865/// pointers. Here are some objectionable examples that GCC considers warnings:
1866///
1867/// int a, *pint;
1868/// short *pshort;
1869/// struct foo *pfoo;
1870///
1871/// pint = pshort; // warning: assignment from incompatible pointer type
1872/// a = pint; // warning: assignment makes integer from pointer without a cast
1873/// pint = a; // warning: assignment makes pointer from integer without a cast
1874/// pint = pfoo; // warning: assignment from incompatible pointer type
1875///
1876/// As a result, the code for dealing with pointers is more complex than the
1877/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001878///
Chris Lattner005ed752008-01-04 18:04:52 +00001879Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001880Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001881 // Get canonical types. We're not formatting these types, just comparing
1882 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001883 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1884 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001885
1886 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001887 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001888
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001889 // If the left-hand side is a reference type, then we are in a
1890 // (rare!) case where we've allowed the use of references in C,
1891 // e.g., as a parameter type in a built-in function. In this case,
1892 // just make sure that the type referenced is compatible with the
1893 // right-hand side type. The caller is responsible for adjusting
1894 // lhsType so that the resulting expression does not have reference
1895 // type.
1896 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
1897 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001898 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001899 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001900 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001901
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001902 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1903 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001904 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001905 // Relax integer conversions like we do for pointers below.
1906 if (rhsType->isIntegerType())
1907 return IntToPointer;
1908 if (lhsType->isIntegerType())
1909 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00001910 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001911 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001912
Nate Begemanc5f0f652008-07-14 18:02:46 +00001913 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001914 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001915 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1916 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001917 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001918
Nate Begemanc5f0f652008-07-14 18:02:46 +00001919 // If we are allowing lax vector conversions, and LHS and RHS are both
1920 // vectors, the total size only needs to be the same. This is a bitcast;
1921 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001922 if (getLangOptions().LaxVectorConversions &&
1923 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001924 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1925 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001926 }
1927 return Incompatible;
1928 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001929
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001930 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001931 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001932
Chris Lattner390564e2008-04-07 06:49:41 +00001933 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001934 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001935 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001936
Chris Lattner390564e2008-04-07 06:49:41 +00001937 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001938 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001939
Steve Naroffa982c712008-09-29 18:10:17 +00001940 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00001941 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff3454b6c2008-09-04 15:10:53 +00001942 return BlockVoidPointer;
Steve Naroffa982c712008-09-29 18:10:17 +00001943
1944 // Treat block pointers as objects.
1945 if (getLangOptions().ObjC1 &&
1946 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1947 return Compatible;
1948 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001949 return Incompatible;
1950 }
1951
1952 if (isa<BlockPointerType>(lhsType)) {
1953 if (rhsType->isIntegerType())
1954 return IntToPointer;
1955
Steve Naroffa982c712008-09-29 18:10:17 +00001956 // Treat block pointers as objects.
1957 if (getLangOptions().ObjC1 &&
1958 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1959 return Compatible;
1960
Steve Naroff3454b6c2008-09-04 15:10:53 +00001961 if (rhsType->isBlockPointerType())
1962 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1963
1964 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1965 if (RHSPT->getPointeeType()->isVoidType())
1966 return BlockVoidPointer;
1967 }
Chris Lattner1853da22008-01-04 23:18:45 +00001968 return Incompatible;
1969 }
1970
Chris Lattner390564e2008-04-07 06:49:41 +00001971 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001972 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001973 if (lhsType == Context.BoolTy)
1974 return Compatible;
1975
1976 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001977 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001978
Chris Lattner390564e2008-04-07 06:49:41 +00001979 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001980 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001981
1982 if (isa<BlockPointerType>(lhsType) &&
1983 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1984 return BlockVoidPointer;
Chris Lattner1853da22008-01-04 23:18:45 +00001985 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001986 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001987
Chris Lattner1853da22008-01-04 23:18:45 +00001988 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001989 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001990 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001991 }
1992 return Incompatible;
1993}
1994
Chris Lattner005ed752008-01-04 18:04:52 +00001995Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001996Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001997 if (getLangOptions().CPlusPlus) {
1998 if (!lhsType->isRecordType()) {
1999 // C++ 5.17p3: If the left operand is not of class type, the
2000 // expression is implicitly converted (C++ 4) to the
2001 // cv-unqualified type of the left operand.
Douglas Gregorbb461502008-10-24 04:54:22 +00002002 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002003 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002004 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002005 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002006 }
2007
2008 // FIXME: Currently, we fall through and treat C++ classes like C
2009 // structures.
2010 }
2011
Steve Naroffcdee22d2007-11-27 17:58:44 +00002012 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2013 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002014 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2015 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002016 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002017 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002018 return Compatible;
2019 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002020
2021 // We don't allow conversion of non-null-pointer constants to integers.
2022 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2023 return IntToBlockPointer;
2024
Chris Lattner5f505bf2007-10-16 02:55:40 +00002025 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002026 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002027 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002028 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002029 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002030 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002031 if (!lhsType->isReferenceType())
2032 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002033
Chris Lattner005ed752008-01-04 18:04:52 +00002034 Sema::AssignConvertType result =
2035 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002036
2037 // C99 6.5.16.1p2: The value of the right operand is converted to the
2038 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002039 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2040 // so that we can use references in built-in functions even in C.
2041 // The getNonReferenceType() call makes sure that the resulting expression
2042 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002043 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002044 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002045 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002046}
2047
Chris Lattner005ed752008-01-04 18:04:52 +00002048Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002049Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2050 return CheckAssignmentConstraints(lhsType, rhsType);
2051}
2052
Chris Lattner1eafdea2008-11-18 01:30:42 +00002053QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002054 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002055 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002056 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002057 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002058}
2059
Chris Lattner1eafdea2008-11-18 01:30:42 +00002060inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002061 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002062 // For conversion purposes, we ignore any qualifiers.
2063 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002064 QualType lhsType =
2065 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2066 QualType rhsType =
2067 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002068
Nate Begemanc5f0f652008-07-14 18:02:46 +00002069 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002070 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002071 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002072
Nate Begemanc5f0f652008-07-14 18:02:46 +00002073 // Handle the case of a vector & extvector type of the same size and element
2074 // type. It would be nice if we only had one vector type someday.
2075 if (getLangOptions().LaxVectorConversions)
2076 if (const VectorType *LV = lhsType->getAsVectorType())
2077 if (const VectorType *RV = rhsType->getAsVectorType())
2078 if (LV->getElementType() == RV->getElementType() &&
2079 LV->getNumElements() == RV->getNumElements())
2080 return lhsType->isExtVectorType() ? lhsType : rhsType;
2081
2082 // If the lhs is an extended vector and the rhs is a scalar of the same type
2083 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002084 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002085 QualType eltType = V->getElementType();
2086
2087 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2088 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2089 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002090 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002091 return lhsType;
2092 }
2093 }
2094
Nate Begemanc5f0f652008-07-14 18:02:46 +00002095 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002096 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002097 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002098 QualType eltType = V->getElementType();
2099
2100 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2101 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2102 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002103 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002104 return rhsType;
2105 }
2106 }
2107
Chris Lattner4b009652007-07-25 00:24:17 +00002108 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002109 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002110 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002111 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002112 return QualType();
2113}
2114
2115inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002116 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002117{
2118 QualType lhsType = lex->getType(), rhsType = rex->getType();
2119
2120 if (lhsType->isVectorType() || rhsType->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002121 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002122
Steve Naroff8f708362007-08-24 19:07:16 +00002123 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002124
Chris Lattner4b009652007-07-25 00:24:17 +00002125 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002126 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002127 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002128}
2129
2130inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002131 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002132{
2133 QualType lhsType = lex->getType(), rhsType = rex->getType();
2134
Steve Naroff8f708362007-08-24 19:07:16 +00002135 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002136
Chris Lattner4b009652007-07-25 00:24:17 +00002137 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002138 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002139 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002140}
2141
2142inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002143 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002144{
2145 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002146 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002147
Steve Naroff8f708362007-08-24 19:07:16 +00002148 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002149
Chris Lattner4b009652007-07-25 00:24:17 +00002150 // handle the common case first (both operands are arithmetic).
2151 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002152 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002153
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002154 // Put any potential pointer into PExp
2155 Expr* PExp = lex, *IExp = rex;
2156 if (IExp->getType()->isPointerType())
2157 std::swap(PExp, IExp);
2158
2159 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2160 if (IExp->getType()->isIntegerType()) {
2161 // Check for arithmetic on pointers to incomplete types
2162 if (!PTy->getPointeeType()->isObjectType()) {
2163 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002164 Diag(Loc, diag::ext_gnu_void_ptr)
2165 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002166 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002167 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002168 << lex->getType() << lex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002169 return QualType();
2170 }
2171 }
2172 return PExp->getType();
2173 }
2174 }
2175
Chris Lattner1eafdea2008-11-18 01:30:42 +00002176 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002177}
2178
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002179// C99 6.5.6
2180QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002181 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002182 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002183 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002184
Steve Naroff8f708362007-08-24 19:07:16 +00002185 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002186
Chris Lattnerf6da2912007-12-09 21:53:25 +00002187 // Enforce type constraints: C99 6.5.6p3.
2188
2189 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002190 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002191 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002192
2193 // Either ptr - int or ptr - ptr.
2194 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002195 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002196
Chris Lattnerf6da2912007-12-09 21:53:25 +00002197 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002198 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002199 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002200 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002201 Diag(Loc, diag::ext_gnu_void_ptr)
2202 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002203 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002204 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002205 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002206 return QualType();
2207 }
2208 }
2209
2210 // The result type of a pointer-int computation is the pointer type.
2211 if (rex->getType()->isIntegerType())
2212 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002213
Chris Lattnerf6da2912007-12-09 21:53:25 +00002214 // Handle pointer-pointer subtractions.
2215 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002216 QualType rpointee = RHSPTy->getPointeeType();
2217
Chris Lattnerf6da2912007-12-09 21:53:25 +00002218 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002219 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002220 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002221 if (rpointee->isVoidType()) {
2222 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002223 Diag(Loc, diag::ext_gnu_void_ptr)
2224 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002225 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002226 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002227 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002228 return QualType();
2229 }
2230 }
2231
2232 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002233 if (!Context.typesAreCompatible(
2234 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2235 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002236 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002237 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002238 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002239 return QualType();
2240 }
2241
2242 return Context.getPointerDiffType();
2243 }
2244 }
2245
Chris Lattner1eafdea2008-11-18 01:30:42 +00002246 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002247}
2248
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002249// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002250QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002251 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002252 // C99 6.5.7p2: Each of the operands shall have integer type.
2253 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002254 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002255
Chris Lattner2c8bff72007-12-12 05:47:28 +00002256 // Shifts don't perform usual arithmetic conversions, they just do integer
2257 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002258 if (!isCompAssign)
2259 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002260 UsualUnaryConversions(rex);
2261
2262 // "The type of the result is that of the promoted left operand."
2263 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002264}
2265
Eli Friedman0d9549b2008-08-22 00:56:42 +00002266static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2267 ASTContext& Context) {
2268 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2269 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2270 // ID acts sort of like void* for ObjC interfaces
2271 if (LHSIface && Context.isObjCIdType(RHS))
2272 return true;
2273 if (RHSIface && Context.isObjCIdType(LHS))
2274 return true;
2275 if (!LHSIface || !RHSIface)
2276 return false;
2277 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2278 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2279}
2280
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002281// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002282QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002283 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002284 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002285 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002286
Chris Lattner254f3bc2007-08-26 01:18:55 +00002287 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002288 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2289 UsualArithmeticConversions(lex, rex);
2290 else {
2291 UsualUnaryConversions(lex);
2292 UsualUnaryConversions(rex);
2293 }
Chris Lattner4b009652007-07-25 00:24:17 +00002294 QualType lType = lex->getType();
2295 QualType rType = rex->getType();
2296
Ted Kremenek486509e2007-10-29 17:13:39 +00002297 // For non-floating point types, check for self-comparisons of the form
2298 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2299 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002300 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002301 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2302 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002303 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002304 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002305 }
2306
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002307 // The result of comparisons is 'bool' in C++, 'int' in C.
2308 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2309
Chris Lattner254f3bc2007-08-26 01:18:55 +00002310 if (isRelational) {
2311 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002312 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002313 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002314 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002315 if (lType->isFloatingType()) {
2316 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002317 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002318 }
2319
Chris Lattner254f3bc2007-08-26 01:18:55 +00002320 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002321 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002322 }
Chris Lattner4b009652007-07-25 00:24:17 +00002323
Chris Lattner22be8422007-08-26 01:10:14 +00002324 bool LHSIsNull = lex->isNullPointerConstant(Context);
2325 bool RHSIsNull = rex->isNullPointerConstant(Context);
2326
Chris Lattner254f3bc2007-08-26 01:18:55 +00002327 // All of the following pointer related warnings are GCC extensions, except
2328 // when handling null pointer constants. One day, we can consider making them
2329 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002330 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002331 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002332 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002333 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002334 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002335
Steve Naroff3b435622007-11-13 14:57:38 +00002336 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002337 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2338 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002339 RCanPointeeTy.getUnqualifiedType()) &&
2340 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002341 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002342 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002343 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002344 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002345 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002346 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002347 // Handle block pointer types.
2348 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2349 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2350 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2351
2352 if (!LHSIsNull && !RHSIsNull &&
2353 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002354 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002355 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002356 }
2357 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002358 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002359 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002360 // Allow block pointers to be compared with null pointer constants.
2361 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2362 (lType->isPointerType() && rType->isBlockPointerType())) {
2363 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002364 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002365 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002366 }
2367 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002368 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002369 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002370
Steve Naroff936c4362008-06-03 14:04:54 +00002371 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002372 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002373 const PointerType *LPT = lType->getAsPointerType();
2374 const PointerType *RPT = rType->getAsPointerType();
2375 bool LPtrToVoid = LPT ?
2376 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2377 bool RPtrToVoid = RPT ?
2378 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2379
2380 if (!LPtrToVoid && !RPtrToVoid &&
2381 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002382 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002383 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002384 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002385 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002386 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002387 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002388 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002389 }
Steve Naroff936c4362008-06-03 14:04:54 +00002390 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2391 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002392 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002393 } else {
2394 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002395 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002396 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002397 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002398 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002399 }
Steve Naroff936c4362008-06-03 14:04:54 +00002400 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002401 }
Steve Naroff936c4362008-06-03 14:04:54 +00002402 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2403 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002404 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002405 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002406 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002407 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002408 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002409 }
Steve Naroff936c4362008-06-03 14:04:54 +00002410 if (lType->isIntegerType() &&
2411 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002412 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002413 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002414 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002415 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002416 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002417 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002418 // Handle block pointers.
2419 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2420 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002421 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002422 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002423 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002424 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002425 }
2426 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2427 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002428 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002429 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002430 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002431 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002432 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002433 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002434}
2435
Nate Begemanc5f0f652008-07-14 18:02:46 +00002436/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2437/// operates on extended vector types. Instead of producing an IntTy result,
2438/// like a scalar comparison, a vector comparison produces a vector of integer
2439/// types.
2440QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002441 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002442 bool isRelational) {
2443 // Check to make sure we're operating on vectors of the same type and width,
2444 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002445 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002446 if (vType.isNull())
2447 return vType;
2448
2449 QualType lType = lex->getType();
2450 QualType rType = rex->getType();
2451
2452 // For non-floating point types, check for self-comparisons of the form
2453 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2454 // often indicate logic errors in the program.
2455 if (!lType->isFloatingType()) {
2456 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2457 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2458 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002459 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002460 }
2461
2462 // Check for comparisons of floating point operands using != and ==.
2463 if (!isRelational && lType->isFloatingType()) {
2464 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002465 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002466 }
2467
2468 // Return the type for the comparison, which is the same as vector type for
2469 // integer vectors, or an integer type of identical size and number of
2470 // elements for floating point vectors.
2471 if (lType->isIntegerType())
2472 return lType;
2473
2474 const VectorType *VTy = lType->getAsVectorType();
2475
2476 // FIXME: need to deal with non-32b int / non-64b long long
2477 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2478 if (TypeSize == 32) {
2479 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2480 }
2481 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2482 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2483}
2484
Chris Lattner4b009652007-07-25 00:24:17 +00002485inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002486 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002487{
2488 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002489 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002490
Steve Naroff8f708362007-08-24 19:07:16 +00002491 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002492
2493 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002494 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002495 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002496}
2497
2498inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00002499 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00002500{
2501 UsualUnaryConversions(lex);
2502 UsualUnaryConversions(rex);
2503
Eli Friedmanbea3f842008-05-13 20:16:47 +00002504 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002505 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002506 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002507}
2508
Chris Lattner4c2642c2008-11-18 01:22:49 +00002509/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2510/// emit an error and return true. If so, return false.
2511static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2512 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2513 if (IsLV == Expr::MLV_Valid)
2514 return false;
2515
2516 unsigned Diag = 0;
2517 bool NeedType = false;
2518 switch (IsLV) { // C99 6.5.16p2
2519 default: assert(0 && "Unknown result from isModifiableLvalue!");
2520 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00002521 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002522 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2523 NeedType = true;
2524 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002525 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002526 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2527 NeedType = true;
2528 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00002529 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002530 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2531 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002532 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002533 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2534 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002535 case Expr::MLV_IncompleteType:
2536 case Expr::MLV_IncompleteVoidType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002537 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2538 NeedType = true;
2539 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002540 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002541 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2542 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00002543 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002544 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2545 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00002546 case Expr::MLV_ReadonlyProperty:
2547 Diag = diag::error_readonly_property_assignment;
2548 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00002549 case Expr::MLV_NoSetterProperty:
2550 Diag = diag::error_nosetter_property_assignment;
2551 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002552 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002553
Chris Lattner4c2642c2008-11-18 01:22:49 +00002554 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002555 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002556 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00002557 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002558 return true;
2559}
2560
2561
2562
2563// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00002564QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
2565 SourceLocation Loc,
2566 QualType CompoundType) {
2567 // Verify that LHS is a modifiable lvalue, and emit error if not.
2568 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00002569 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00002570
2571 QualType LHSType = LHS->getType();
2572 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00002573
Chris Lattner005ed752008-01-04 18:04:52 +00002574 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002575 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00002576 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002577 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner34c85082008-08-21 18:04:13 +00002578
2579 // If the RHS is a unary plus or minus, check to see if they = and + are
2580 // right next to each other. If so, the user may have typo'd "x =+ 4"
2581 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002582 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00002583 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2584 RHSCheck = ICE->getSubExpr();
2585 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2586 if ((UO->getOpcode() == UnaryOperator::Plus ||
2587 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00002588 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00002589 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002590 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00002591 Diag(Loc, diag::warn_not_compound_assign)
2592 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
2593 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00002594 }
2595 } else {
2596 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00002597 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00002598 }
Chris Lattner005ed752008-01-04 18:04:52 +00002599
Chris Lattner1eafdea2008-11-18 01:30:42 +00002600 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
2601 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00002602 return QualType();
2603
Chris Lattner4b009652007-07-25 00:24:17 +00002604 // C99 6.5.16p3: The type of an assignment expression is the type of the
2605 // left operand unless the left operand has qualified type, in which case
2606 // it is the unqualified version of the type of the left operand.
2607 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2608 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002609 // C++ 5.17p1: the type of the assignment expression is that of its left
2610 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002611 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002612}
2613
Chris Lattner1eafdea2008-11-18 01:30:42 +00002614// C99 6.5.17
2615QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
2616 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00002617
2618 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002619 DefaultFunctionArrayConversion(RHS);
2620 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002621}
2622
2623/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2624/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Chris Lattnere65182c2008-11-21 07:05:48 +00002625QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc) {
2626 QualType ResType = Op->getType();
2627 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002628
Steve Naroffd30e1932007-08-24 17:20:07 +00002629 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattnere65182c2008-11-21 07:05:48 +00002630 if (ResType->isRealType()) {
2631 // OK!
2632 } else if (const PointerType *PT = ResType->getAsPointerType()) {
2633 // C99 6.5.2.4p2, 6.5.6p2
2634 if (PT->getPointeeType()->isObjectType()) {
2635 // Pointer to object is ok!
2636 } else if (PT->getPointeeType()->isVoidType()) {
2637 // Pointer to void is extension.
2638 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
2639 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +00002640 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002641 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002642 return QualType();
2643 }
Chris Lattnere65182c2008-11-21 07:05:48 +00002644 } else if (ResType->isComplexType()) {
2645 // C99 does not support ++/-- on complex types, we allow as an extension.
2646 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002647 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002648 } else {
2649 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002650 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002651 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002652 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002653 // At this point, we know we have a real, complex or pointer type.
2654 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00002655 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00002656 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00002657 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00002658}
2659
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002660/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002661/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002662/// where the declaration is needed for type checking. We only need to
2663/// handle cases when the expression references a function designator
2664/// or is an lvalue. Here are some examples:
2665/// - &(x) => x
2666/// - &*****f => f for f a function designator.
2667/// - &s.xx => s
2668/// - &s.zz[1].yy -> s, if zz is an array
2669/// - *(x + 1) -> x, if x is an array
2670/// - &"123"[2] -> 0
2671/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002672static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002673 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002674 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002675 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002676 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002677 // Fields cannot be declared with a 'register' storage class.
2678 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002679 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002680 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002681 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002682 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002683 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002684
Douglas Gregord2baafd2008-10-21 16:13:35 +00002685 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002686 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002687 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002688 return 0;
2689 else
2690 return VD;
2691 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002692 case Stmt::UnaryOperatorClass: {
2693 UnaryOperator *UO = cast<UnaryOperator>(E);
2694
2695 switch(UO->getOpcode()) {
2696 case UnaryOperator::Deref: {
2697 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002698 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2699 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2700 if (!VD || VD->getType()->isPointerType())
2701 return 0;
2702 return VD;
2703 }
2704 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002705 }
2706 case UnaryOperator::Real:
2707 case UnaryOperator::Imag:
2708 case UnaryOperator::Extension:
2709 return getPrimaryDecl(UO->getSubExpr());
2710 default:
2711 return 0;
2712 }
2713 }
2714 case Stmt::BinaryOperatorClass: {
2715 BinaryOperator *BO = cast<BinaryOperator>(E);
2716
2717 // Handle cases involving pointer arithmetic. The result of an
2718 // Assign or AddAssign is not an lvalue so they can be ignored.
2719
2720 // (x + n) or (n + x) => x
2721 if (BO->getOpcode() == BinaryOperator::Add) {
2722 if (BO->getLHS()->getType()->isPointerType()) {
2723 return getPrimaryDecl(BO->getLHS());
2724 } else if (BO->getRHS()->getType()->isPointerType()) {
2725 return getPrimaryDecl(BO->getRHS());
2726 }
2727 }
2728
2729 return 0;
2730 }
Chris Lattner4b009652007-07-25 00:24:17 +00002731 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002732 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002733 case Stmt::ImplicitCastExprClass:
2734 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002735 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002736 default:
2737 return 0;
2738 }
2739}
2740
2741/// CheckAddressOfOperand - The operand of & must be either a function
2742/// designator or an lvalue designating an object. If it is an lvalue, the
2743/// object cannot be declared with storage class register or be a bit field.
2744/// Note: The usual conversions are *not* applied to the operand of the &
2745/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00002746/// In C++, the operand might be an overloaded function name, in which case
2747/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00002748QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002749 if (getLangOptions().C99) {
2750 // Implement C99-only parts of addressof rules.
2751 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2752 if (uOp->getOpcode() == UnaryOperator::Deref)
2753 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2754 // (assuming the deref expression is valid).
2755 return uOp->getSubExpr()->getType();
2756 }
2757 // Technically, there should be a check for array subscript
2758 // expressions here, but the result of one is always an lvalue anyway.
2759 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002760 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002761 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002762
2763 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002764 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2765 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00002766 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
2767 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002768 return QualType();
2769 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002770 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2771 if (MemExpr->getMemberDecl()->isBitField()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002772 Diag(OpLoc, diag::err_typecheck_address_of)
2773 << "bit-field" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00002774 return QualType();
2775 }
2776 // Check for Apple extension for accessing vector components.
2777 } else if (isa<ArraySubscriptExpr>(op) &&
2778 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002779 Diag(OpLoc, diag::err_typecheck_address_of)
2780 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00002781 return QualType();
2782 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002783 // We have an lvalue with a decl. Make sure the decl is not declared
2784 // with the register storage-class specifier.
2785 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2786 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002787 Diag(OpLoc, diag::err_typecheck_address_of)
2788 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002789 return QualType();
2790 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00002791 } else if (isa<OverloadedFunctionDecl>(dcl))
2792 return Context.OverloadTy;
2793 else
Chris Lattner4b009652007-07-25 00:24:17 +00002794 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002795 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002796
Chris Lattner4b009652007-07-25 00:24:17 +00002797 // If the operand has type "type", the result has type "pointer to type".
2798 return Context.getPointerType(op->getType());
2799}
2800
Chris Lattnerda5c0872008-11-23 09:13:29 +00002801QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
2802 UsualUnaryConversions(Op);
2803 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002804
Chris Lattnerda5c0872008-11-23 09:13:29 +00002805 // Note that per both C89 and C99, this is always legal, even if ptype is an
2806 // incomplete type or void. It would be possible to warn about dereferencing
2807 // a void pointer, but it's completely well-defined, and such a warning is
2808 // unlikely to catch any mistakes.
2809 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00002810 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00002811
Chris Lattner77d52da2008-11-20 06:06:08 +00002812 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002813 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002814 return QualType();
2815}
2816
2817static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2818 tok::TokenKind Kind) {
2819 BinaryOperator::Opcode Opc;
2820 switch (Kind) {
2821 default: assert(0 && "Unknown binop!");
2822 case tok::star: Opc = BinaryOperator::Mul; break;
2823 case tok::slash: Opc = BinaryOperator::Div; break;
2824 case tok::percent: Opc = BinaryOperator::Rem; break;
2825 case tok::plus: Opc = BinaryOperator::Add; break;
2826 case tok::minus: Opc = BinaryOperator::Sub; break;
2827 case tok::lessless: Opc = BinaryOperator::Shl; break;
2828 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2829 case tok::lessequal: Opc = BinaryOperator::LE; break;
2830 case tok::less: Opc = BinaryOperator::LT; break;
2831 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2832 case tok::greater: Opc = BinaryOperator::GT; break;
2833 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2834 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2835 case tok::amp: Opc = BinaryOperator::And; break;
2836 case tok::caret: Opc = BinaryOperator::Xor; break;
2837 case tok::pipe: Opc = BinaryOperator::Or; break;
2838 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2839 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2840 case tok::equal: Opc = BinaryOperator::Assign; break;
2841 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2842 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2843 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2844 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2845 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2846 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2847 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2848 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2849 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2850 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2851 case tok::comma: Opc = BinaryOperator::Comma; break;
2852 }
2853 return Opc;
2854}
2855
2856static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2857 tok::TokenKind Kind) {
2858 UnaryOperator::Opcode Opc;
2859 switch (Kind) {
2860 default: assert(0 && "Unknown unary op!");
2861 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2862 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2863 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2864 case tok::star: Opc = UnaryOperator::Deref; break;
2865 case tok::plus: Opc = UnaryOperator::Plus; break;
2866 case tok::minus: Opc = UnaryOperator::Minus; break;
2867 case tok::tilde: Opc = UnaryOperator::Not; break;
2868 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002869 case tok::kw___real: Opc = UnaryOperator::Real; break;
2870 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2871 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2872 }
2873 return Opc;
2874}
2875
Douglas Gregord7f915e2008-11-06 23:29:22 +00002876/// CreateBuiltinBinOp - Creates a new built-in binary operation with
2877/// operator @p Opc at location @c TokLoc. This routine only supports
2878/// built-in operations; ActOnBinOp handles overloaded operators.
2879Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
2880 unsigned Op,
2881 Expr *lhs, Expr *rhs) {
2882 QualType ResultTy; // Result type of the binary operator.
2883 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2884 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
2885
2886 switch (Opc) {
2887 default:
2888 assert(0 && "Unknown binary expr!");
2889 case BinaryOperator::Assign:
2890 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
2891 break;
2892 case BinaryOperator::Mul:
2893 case BinaryOperator::Div:
2894 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
2895 break;
2896 case BinaryOperator::Rem:
2897 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
2898 break;
2899 case BinaryOperator::Add:
2900 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
2901 break;
2902 case BinaryOperator::Sub:
2903 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
2904 break;
2905 case BinaryOperator::Shl:
2906 case BinaryOperator::Shr:
2907 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
2908 break;
2909 case BinaryOperator::LE:
2910 case BinaryOperator::LT:
2911 case BinaryOperator::GE:
2912 case BinaryOperator::GT:
2913 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
2914 break;
2915 case BinaryOperator::EQ:
2916 case BinaryOperator::NE:
2917 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
2918 break;
2919 case BinaryOperator::And:
2920 case BinaryOperator::Xor:
2921 case BinaryOperator::Or:
2922 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
2923 break;
2924 case BinaryOperator::LAnd:
2925 case BinaryOperator::LOr:
2926 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
2927 break;
2928 case BinaryOperator::MulAssign:
2929 case BinaryOperator::DivAssign:
2930 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
2931 if (!CompTy.isNull())
2932 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2933 break;
2934 case BinaryOperator::RemAssign:
2935 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
2936 if (!CompTy.isNull())
2937 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2938 break;
2939 case BinaryOperator::AddAssign:
2940 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
2941 if (!CompTy.isNull())
2942 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2943 break;
2944 case BinaryOperator::SubAssign:
2945 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
2946 if (!CompTy.isNull())
2947 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2948 break;
2949 case BinaryOperator::ShlAssign:
2950 case BinaryOperator::ShrAssign:
2951 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
2952 if (!CompTy.isNull())
2953 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2954 break;
2955 case BinaryOperator::AndAssign:
2956 case BinaryOperator::XorAssign:
2957 case BinaryOperator::OrAssign:
2958 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
2959 if (!CompTy.isNull())
2960 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2961 break;
2962 case BinaryOperator::Comma:
2963 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
2964 break;
2965 }
2966 if (ResultTy.isNull())
2967 return true;
2968 if (CompTy.isNull())
2969 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
2970 else
2971 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
2972}
2973
Chris Lattner4b009652007-07-25 00:24:17 +00002974// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002975Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
2976 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002977 ExprTy *LHS, ExprTy *RHS) {
2978 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2979 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2980
Steve Naroff87d58b42007-09-16 03:34:24 +00002981 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2982 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002983
Douglas Gregord7f915e2008-11-06 23:29:22 +00002984 if (getLangOptions().CPlusPlus &&
2985 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
2986 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002987 // If this is one of the assignment operators, we only perform
2988 // overload resolution if the left-hand side is a class or
2989 // enumeration type (C++ [expr.ass]p3).
2990 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
2991 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
2992 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
2993 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00002994
2995 // Determine which overloaded operator we're dealing with.
2996 static const OverloadedOperatorKind OverOps[] = {
2997 OO_Star, OO_Slash, OO_Percent,
2998 OO_Plus, OO_Minus,
2999 OO_LessLess, OO_GreaterGreater,
3000 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3001 OO_EqualEqual, OO_ExclaimEqual,
3002 OO_Amp,
3003 OO_Caret,
3004 OO_Pipe,
3005 OO_AmpAmp,
3006 OO_PipePipe,
3007 OO_Equal, OO_StarEqual,
3008 OO_SlashEqual, OO_PercentEqual,
3009 OO_PlusEqual, OO_MinusEqual,
3010 OO_LessLessEqual, OO_GreaterGreaterEqual,
3011 OO_AmpEqual, OO_CaretEqual,
3012 OO_PipeEqual,
3013 OO_Comma
3014 };
3015 OverloadedOperatorKind OverOp = OverOps[Opc];
3016
Douglas Gregor5ed15042008-11-18 23:14:02 +00003017 // Add the appropriate overloaded operators (C++ [over.match.oper])
3018 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003019 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003020 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003021 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003022
3023 // Perform overload resolution.
3024 OverloadCandidateSet::iterator Best;
3025 switch (BestViableFunction(CandidateSet, Best)) {
3026 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003027 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003028 FunctionDecl *FnDecl = Best->Function;
3029
Douglas Gregor70d26122008-11-12 17:17:38 +00003030 if (FnDecl) {
3031 // We matched an overloaded operator. Build a call to that
3032 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003033
Douglas Gregor70d26122008-11-12 17:17:38 +00003034 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003035 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3036 if (PerformObjectArgumentInitialization(lhs, Method) ||
3037 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3038 "passing"))
3039 return true;
3040 } else {
3041 // Convert the arguments.
3042 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3043 "passing") ||
3044 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3045 "passing"))
3046 return true;
3047 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003048
Douglas Gregor70d26122008-11-12 17:17:38 +00003049 // Determine the result type
3050 QualType ResultTy
3051 = FnDecl->getType()->getAsFunctionType()->getResultType();
3052 ResultTy = ResultTy.getNonReferenceType();
3053
3054 // Build the actual expression node.
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003055 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3056 SourceLocation());
3057 UsualUnaryConversions(FnExpr);
3058
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003059 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregor70d26122008-11-12 17:17:38 +00003060 } else {
3061 // We matched a built-in operator. Convert the arguments, then
3062 // break out so that we will build the appropriate built-in
3063 // operator node.
3064 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
3065 "passing") ||
3066 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
3067 "passing"))
3068 return true;
3069
3070 break;
3071 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003072 }
3073
3074 case OR_No_Viable_Function:
3075 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003076 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003077 break;
3078
3079 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003080 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3081 << BinaryOperator::getOpcodeStr(Opc)
3082 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003083 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3084 return true;
3085 }
3086
Douglas Gregor70d26122008-11-12 17:17:38 +00003087 // Either we found no viable overloaded operator or we matched a
3088 // built-in operator. In either case, fall through to trying to
3089 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003090 }
Chris Lattner4b009652007-07-25 00:24:17 +00003091
Douglas Gregord7f915e2008-11-06 23:29:22 +00003092 // Build a built-in binary operation.
3093 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003094}
3095
3096// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003097Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3098 tok::TokenKind Op, ExprTy *input) {
Chris Lattner4b009652007-07-25 00:24:17 +00003099 Expr *Input = (Expr*)input;
3100 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003101
3102 if (getLangOptions().CPlusPlus &&
3103 (Input->getType()->isRecordType()
3104 || Input->getType()->isEnumeralType())) {
3105 // Determine which overloaded operator we're dealing with.
3106 static const OverloadedOperatorKind OverOps[] = {
3107 OO_None, OO_None,
3108 OO_PlusPlus, OO_MinusMinus,
3109 OO_Amp, OO_Star,
3110 OO_Plus, OO_Minus,
3111 OO_Tilde, OO_Exclaim,
3112 OO_None, OO_None,
3113 OO_None,
3114 OO_None
3115 };
3116 OverloadedOperatorKind OverOp = OverOps[Opc];
3117
3118 // Add the appropriate overloaded operators (C++ [over.match.oper])
3119 // to the candidate set.
3120 OverloadCandidateSet CandidateSet;
3121 if (OverOp != OO_None)
3122 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3123
3124 // Perform overload resolution.
3125 OverloadCandidateSet::iterator Best;
3126 switch (BestViableFunction(CandidateSet, Best)) {
3127 case OR_Success: {
3128 // We found a built-in operator or an overloaded operator.
3129 FunctionDecl *FnDecl = Best->Function;
3130
3131 if (FnDecl) {
3132 // We matched an overloaded operator. Build a call to that
3133 // operator.
3134
3135 // Convert the arguments.
3136 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3137 if (PerformObjectArgumentInitialization(Input, Method))
3138 return true;
3139 } else {
3140 // Convert the arguments.
3141 if (PerformCopyInitialization(Input,
3142 FnDecl->getParamDecl(0)->getType(),
3143 "passing"))
3144 return true;
3145 }
3146
3147 // Determine the result type
3148 QualType ResultTy
3149 = FnDecl->getType()->getAsFunctionType()->getResultType();
3150 ResultTy = ResultTy.getNonReferenceType();
3151
3152 // Build the actual expression node.
3153 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3154 SourceLocation());
3155 UsualUnaryConversions(FnExpr);
3156
3157 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3158 } else {
3159 // We matched a built-in operator. Convert the arguments, then
3160 // break out so that we will build the appropriate built-in
3161 // operator node.
3162 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0],
3163 "passing"))
3164 return true;
3165
3166 break;
3167 }
3168 }
3169
3170 case OR_No_Viable_Function:
3171 // No viable function; fall through to handling this as a
3172 // built-in operator, which will produce an error message for us.
3173 break;
3174
3175 case OR_Ambiguous:
3176 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3177 << UnaryOperator::getOpcodeStr(Opc)
3178 << Input->getSourceRange();
3179 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3180 return true;
3181 }
3182
3183 // Either we found no viable overloaded operator or we matched a
3184 // built-in operator. In either case, fall through to trying to
3185 // build a built-in operation.
3186 }
3187
Chris Lattner4b009652007-07-25 00:24:17 +00003188 QualType resultType;
3189 switch (Opc) {
3190 default:
3191 assert(0 && "Unimplemented unary expr!");
3192 case UnaryOperator::PreInc:
3193 case UnaryOperator::PreDec:
3194 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
3195 break;
3196 case UnaryOperator::AddrOf:
3197 resultType = CheckAddressOfOperand(Input, OpLoc);
3198 break;
3199 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003200 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003201 resultType = CheckIndirectionOperand(Input, OpLoc);
3202 break;
3203 case UnaryOperator::Plus:
3204 case UnaryOperator::Minus:
3205 UsualUnaryConversions(Input);
3206 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003207 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3208 break;
3209 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3210 resultType->isEnumeralType())
3211 break;
3212 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3213 Opc == UnaryOperator::Plus &&
3214 resultType->isPointerType())
3215 break;
3216
Chris Lattner77d52da2008-11-20 06:06:08 +00003217 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003218 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003219 case UnaryOperator::Not: // bitwise complement
3220 UsualUnaryConversions(Input);
3221 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003222 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3223 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3224 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003225 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003226 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003227 else if (!resultType->isIntegerType())
Chris Lattner77d52da2008-11-20 06:06:08 +00003228 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003229 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003230 break;
3231 case UnaryOperator::LNot: // logical negation
3232 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3233 DefaultFunctionArrayConversion(Input);
3234 resultType = Input->getType();
3235 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattner77d52da2008-11-20 06:06:08 +00003236 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003237 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003238 // LNot always has type int. C99 6.5.3.3p5.
3239 resultType = Context.IntTy;
3240 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003241 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003242 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003243 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003244 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003245 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003246 resultType = Input->getType();
3247 break;
3248 }
3249 if (resultType.isNull())
3250 return true;
3251 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3252}
3253
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003254/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3255Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003256 SourceLocation LabLoc,
3257 IdentifierInfo *LabelII) {
3258 // Look up the record for this label identifier.
3259 LabelStmt *&LabelDecl = LabelMap[LabelII];
3260
Daniel Dunbar879788d2008-08-04 16:51:22 +00003261 // If we haven't seen this label yet, create a forward reference. It
3262 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003263 if (LabelDecl == 0)
3264 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3265
3266 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003267 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3268 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003269}
3270
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003271Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003272 SourceLocation RPLoc) { // "({..})"
3273 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3274 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3275 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3276
3277 // FIXME: there are a variety of strange constraints to enforce here, for
3278 // example, it is not possible to goto into a stmt expression apparently.
3279 // More semantic analysis is needed.
3280
3281 // FIXME: the last statement in the compount stmt has its value used. We
3282 // should not warn about it being unused.
3283
3284 // If there are sub stmts in the compound stmt, take the type of the last one
3285 // as the type of the stmtexpr.
3286 QualType Ty = Context.VoidTy;
3287
Chris Lattner200964f2008-07-26 19:51:01 +00003288 if (!Compound->body_empty()) {
3289 Stmt *LastStmt = Compound->body_back();
3290 // If LastStmt is a label, skip down through into the body.
3291 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3292 LastStmt = Label->getSubStmt();
3293
3294 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003295 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003296 }
Chris Lattner4b009652007-07-25 00:24:17 +00003297
3298 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3299}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003300
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003301Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003302 SourceLocation TypeLoc,
3303 TypeTy *argty,
3304 OffsetOfComponent *CompPtr,
3305 unsigned NumComponents,
3306 SourceLocation RPLoc) {
3307 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3308 assert(!ArgTy.isNull() && "Missing type argument!");
3309
3310 // We must have at least one component that refers to the type, and the first
3311 // one is known to be a field designator. Verify that the ArgTy represents
3312 // a struct/union/class.
3313 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003314 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003315
3316 // Otherwise, create a compound literal expression as the base, and
3317 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003318 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003319
Chris Lattnerb37522e2007-08-31 21:49:13 +00003320 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3321 // GCC extension, diagnose them.
3322 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003323 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3324 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003325
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003326 for (unsigned i = 0; i != NumComponents; ++i) {
3327 const OffsetOfComponent &OC = CompPtr[i];
3328 if (OC.isBrackets) {
3329 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003330 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003331 if (!AT) {
3332 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003333 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003334 }
3335
Chris Lattner2af6a802007-08-30 17:59:59 +00003336 // FIXME: C++: Verify that operator[] isn't overloaded.
3337
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003338 // C99 6.5.2.1p1
3339 Expr *Idx = static_cast<Expr*>(OC.U.E);
3340 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003341 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3342 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003343
3344 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3345 continue;
3346 }
3347
3348 const RecordType *RC = Res->getType()->getAsRecordType();
3349 if (!RC) {
3350 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003351 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003352 }
3353
3354 // Get the decl corresponding to this.
3355 RecordDecl *RD = RC->getDecl();
3356 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
3357 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003358 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3359 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003360
3361 // FIXME: C++: Verify that MemberDecl isn't a static field.
3362 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003363 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3364 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003365 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3366 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003367 }
3368
3369 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3370 BuiltinLoc);
3371}
3372
3373
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003374Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003375 TypeTy *arg1, TypeTy *arg2,
3376 SourceLocation RPLoc) {
3377 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3378 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3379
3380 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3381
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003382 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003383}
3384
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003385Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003386 ExprTy *expr1, ExprTy *expr2,
3387 SourceLocation RPLoc) {
3388 Expr *CondExpr = static_cast<Expr*>(cond);
3389 Expr *LHSExpr = static_cast<Expr*>(expr1);
3390 Expr *RHSExpr = static_cast<Expr*>(expr2);
3391
3392 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3393
3394 // The conditional expression is required to be a constant expression.
3395 llvm::APSInt condEval(32);
3396 SourceLocation ExpLoc;
3397 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003398 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3399 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00003400
3401 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3402 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3403 RHSExpr->getType();
3404 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3405}
3406
Steve Naroff52a81c02008-09-03 18:15:37 +00003407//===----------------------------------------------------------------------===//
3408// Clang Extensions.
3409//===----------------------------------------------------------------------===//
3410
3411/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003412void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003413 // Analyze block parameters.
3414 BlockSemaInfo *BSI = new BlockSemaInfo();
3415
3416 // Add BSI to CurBlock.
3417 BSI->PrevBlockInfo = CurBlock;
3418 CurBlock = BSI;
3419
3420 BSI->ReturnType = 0;
3421 BSI->TheScope = BlockScope;
3422
Steve Naroff52059382008-10-10 01:28:17 +00003423 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
3424 PushDeclContext(BSI->TheDecl);
3425}
3426
3427void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003428 // Analyze arguments to block.
3429 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3430 "Not a function declarator!");
3431 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3432
Steve Naroff52059382008-10-10 01:28:17 +00003433 CurBlock->hasPrototype = FTI.hasPrototype;
3434 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003435
3436 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3437 // no arguments, not a function that takes a single void argument.
3438 if (FTI.hasPrototype &&
3439 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3440 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3441 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3442 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003443 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003444 } else if (FTI.hasPrototype) {
3445 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003446 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3447 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003448 }
Steve Naroff52059382008-10-10 01:28:17 +00003449 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3450
3451 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3452 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3453 // If this has an identifier, add it to the scope stack.
3454 if ((*AI)->getIdentifier())
3455 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003456}
3457
3458/// ActOnBlockError - If there is an error parsing a block, this callback
3459/// is invoked to pop the information about the block from the action impl.
3460void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3461 // Ensure that CurBlock is deleted.
3462 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3463
3464 // Pop off CurBlock, handle nested blocks.
3465 CurBlock = CurBlock->PrevBlockInfo;
3466
3467 // FIXME: Delete the ParmVarDecl objects as well???
3468
3469}
3470
3471/// ActOnBlockStmtExpr - This is called when the body of a block statement
3472/// literal was successfully completed. ^(int x){...}
3473Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3474 Scope *CurScope) {
3475 // Ensure that CurBlock is deleted.
3476 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3477 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3478
Steve Naroff52059382008-10-10 01:28:17 +00003479 PopDeclContext();
3480
Steve Naroff52a81c02008-09-03 18:15:37 +00003481 // Pop off CurBlock, handle nested blocks.
3482 CurBlock = CurBlock->PrevBlockInfo;
3483
3484 QualType RetTy = Context.VoidTy;
3485 if (BSI->ReturnType)
3486 RetTy = QualType(BSI->ReturnType, 0);
3487
3488 llvm::SmallVector<QualType, 8> ArgTypes;
3489 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3490 ArgTypes.push_back(BSI->Params[i]->getType());
3491
3492 QualType BlockTy;
3493 if (!BSI->hasPrototype)
3494 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3495 else
3496 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003497 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003498
3499 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003500
Steve Naroff95029d92008-10-08 18:44:00 +00003501 BSI->TheDecl->setBody(Body.take());
3502 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003503}
3504
Nate Begemanbd881ef2008-01-30 20:50:20 +00003505/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003506/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003507/// The number of arguments has already been validated to match the number of
3508/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003509static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3510 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003511 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003512 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003513 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3514 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003515
3516 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003517 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003518 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003519 return true;
3520}
3521
3522Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3523 SourceLocation *CommaLocs,
3524 SourceLocation BuiltinLoc,
3525 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003526 // __builtin_overload requires at least 2 arguments
3527 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003528 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3529 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003530
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003531 // The first argument is required to be a constant expression. It tells us
3532 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003533 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003534 Expr *NParamsExpr = Args[0];
3535 llvm::APSInt constEval(32);
3536 SourceLocation ExpLoc;
3537 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003538 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3539 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003540
3541 // Verify that the number of parameters is > 0
3542 unsigned NumParams = constEval.getZExtValue();
3543 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003544 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3545 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003546 // Verify that we have at least 1 + NumParams arguments to the builtin.
3547 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003548 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3549 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003550
3551 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003552 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003553 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003554 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3555 // UsualUnaryConversions will convert the function DeclRefExpr into a
3556 // pointer to function.
3557 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003558 const FunctionTypeProto *FnType = 0;
3559 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3560 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003561
3562 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3563 // parameters, and the number of parameters must match the value passed to
3564 // the builtin.
3565 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003566 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
3567 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003568
3569 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003570 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003571 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003572 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003573 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003574 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
3575 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00003576 // Remember our match, and continue processing the remaining arguments
3577 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003578 OE = new OverloadExpr(Args, NumArgs, i,
3579 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003580 BuiltinLoc, RParenLoc);
3581 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003582 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003583 // Return the newly created OverloadExpr node, if we succeded in matching
3584 // exactly one of the candidate functions.
3585 if (OE)
3586 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003587
3588 // If we didn't find a matching function Expr in the __builtin_overload list
3589 // the return an error.
3590 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003591 for (unsigned i = 0; i != NumParams; ++i) {
3592 if (i != 0) typeNames += ", ";
3593 typeNames += Args[i+1]->getType().getAsString();
3594 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003595
Chris Lattner77d52da2008-11-20 06:06:08 +00003596 return Diag(BuiltinLoc, diag::err_overload_no_match)
3597 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003598}
3599
Anders Carlsson36760332007-10-15 20:28:48 +00003600Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3601 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003602 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003603 Expr *E = static_cast<Expr*>(expr);
3604 QualType T = QualType::getFromOpaquePtr(type);
3605
3606 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003607
3608 // Get the va_list type
3609 QualType VaListType = Context.getBuiltinVaListType();
3610 // Deal with implicit array decay; for example, on x86-64,
3611 // va_list is an array, but it's supposed to decay to
3612 // a pointer for va_arg.
3613 if (VaListType->isArrayType())
3614 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003615 // Make sure the input expression also decays appropriately.
3616 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003617
3618 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003619 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00003620 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003621 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00003622
3623 // FIXME: Warn if a non-POD type is passed in.
3624
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003625 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003626}
3627
Chris Lattner005ed752008-01-04 18:04:52 +00003628bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3629 SourceLocation Loc,
3630 QualType DstType, QualType SrcType,
3631 Expr *SrcExpr, const char *Flavor) {
3632 // Decode the result (notice that AST's are still created for extensions).
3633 bool isInvalid = false;
3634 unsigned DiagKind;
3635 switch (ConvTy) {
3636 default: assert(0 && "Unknown conversion type");
3637 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003638 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003639 DiagKind = diag::ext_typecheck_convert_pointer_int;
3640 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003641 case IntToPointer:
3642 DiagKind = diag::ext_typecheck_convert_int_pointer;
3643 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003644 case IncompatiblePointer:
3645 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3646 break;
3647 case FunctionVoidPointer:
3648 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3649 break;
3650 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003651 // If the qualifiers lost were because we were applying the
3652 // (deprecated) C++ conversion from a string literal to a char*
3653 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3654 // Ideally, this check would be performed in
3655 // CheckPointerTypesForAssignment. However, that would require a
3656 // bit of refactoring (so that the second argument is an
3657 // expression, rather than a type), which should be done as part
3658 // of a larger effort to fix CheckPointerTypesForAssignment for
3659 // C++ semantics.
3660 if (getLangOptions().CPlusPlus &&
3661 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3662 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003663 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3664 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003665 case IntToBlockPointer:
3666 DiagKind = diag::err_int_to_block_pointer;
3667 break;
3668 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003669 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003670 break;
3671 case BlockVoidPointer:
3672 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3673 break;
Steve Naroff19608432008-10-14 22:18:38 +00003674 case IncompatibleObjCQualifiedId:
3675 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3676 // it can give a more specific diagnostic.
3677 DiagKind = diag::warn_incompatible_qualified_id;
3678 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003679 case Incompatible:
3680 DiagKind = diag::err_typecheck_convert_incompatible;
3681 isInvalid = true;
3682 break;
3683 }
3684
Chris Lattner271d4c22008-11-24 05:29:24 +00003685 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
3686 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00003687 return isInvalid;
3688}