blob: ace5bcd5b70e14cbfc236456ca5c14902cbfb13e [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)
420 << Name.getAsString() << 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 Lattner8ba580c2008-11-19 05:08:23 +0000425 return Diag(Loc, diag::err_undeclared_var_use) << Name.getAsString();
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)
434 << FD->getName();
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)
438 << FD->getName();
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 Lattner8ba580c2008-11-19 05:08:23 +0000448 return Diag(Loc, diag::err_invalid_non_static_member_use) << FD->getName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000449 }
Chris Lattner4b009652007-07-25 00:24:17 +0000450 if (isa<TypedefDecl>(D))
Chris Lattner8ba580c2008-11-19 05:08:23 +0000451 return Diag(Loc, diag::err_unexpected_typedef) << Name.getAsString();
Ted Kremenek42730c52008-01-07 19:49:32 +0000452 if (isa<ObjCInterfaceDecl>(D))
Chris Lattner8ba580c2008-11-19 05:08:23 +0000453 return Diag(Loc, diag::err_unexpected_interface) << Name.getAsString();
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000454 if (isa<NamespaceDecl>(D))
Chris Lattner8ba580c2008-11-19 05:08:23 +0000455 return Diag(Loc, diag::err_unexpected_namespace) << Name.getAsString();
Chris Lattner4b009652007-07-25 00:24:17 +0000456
Steve Naroffd6163f32008-09-05 22:11:13 +0000457 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000458 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
459 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
460
Steve Naroffd6163f32008-09-05 22:11:13 +0000461 ValueDecl *VD = cast<ValueDecl>(D);
462
463 // check if referencing an identifier with __attribute__((deprecated)).
464 if (VD->getAttr<DeprecatedAttr>())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000465 Diag(Loc, diag::warn_deprecated) << VD->getName();
Steve Naroffd6163f32008-09-05 22:11:13 +0000466
467 // Only create DeclRefExpr's for valid Decl's.
468 if (VD->isInvalidDecl())
469 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000470
471 // If the identifier reference is inside a block, and it refers to a value
472 // that is outside the block, create a BlockDeclRefExpr instead of a
473 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
474 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000475 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000476 // We do not do this for things like enum constants, global variables, etc,
477 // as they do not get snapshotted.
478 //
479 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000480 // The BlocksAttr indicates the variable is bound by-reference.
481 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000482 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
483 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000484
485 // Variable will be bound by-copy, make it const within the closure.
486 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000487 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
488 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000489 }
490 // If this reference is not in a block or if the referenced variable is
491 // within the block, create a normal DeclRefExpr.
Douglas Gregor3fb675a2008-10-22 04:14:44 +0000492 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Chris Lattner4b009652007-07-25 00:24:17 +0000493}
494
Chris Lattner69909292008-08-10 01:53:14 +0000495Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000496 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000497 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000498
499 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000500 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000501 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
502 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
503 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000504 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000505
506 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000507 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000508 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000509
Chris Lattner7e637512008-01-12 08:14:25 +0000510 // Pre-defined identifiers are of type char[x], where x is the length of the
511 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000512 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000513 if (getCurFunctionDecl())
514 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000515 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000516 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000517
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000518 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000519 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000520 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000521 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000522}
523
Steve Naroff87d58b42007-09-16 03:34:24 +0000524Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000525 llvm::SmallString<16> CharBuffer;
526 CharBuffer.resize(Tok.getLength());
527 const char *ThisTokBegin = &CharBuffer[0];
528 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
529
530 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
531 Tok.getLocation(), PP);
532 if (Literal.hadError())
533 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000534
535 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
536
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000537 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
538 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000539}
540
Steve Naroff87d58b42007-09-16 03:34:24 +0000541Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000542 // fast path for a single digit (which is quite common). A single digit
543 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
544 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000545 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000546
Chris Lattner8cd0e932008-03-05 18:54:05 +0000547 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000548 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000549 Context.IntTy,
550 Tok.getLocation()));
551 }
552 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000553 // Add padding so that NumericLiteralParser can overread by one character.
554 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000555 const char *ThisTokBegin = &IntegerBuffer[0];
556
557 // Get the spelling of the token, which eliminates trigraphs, etc.
558 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000559
Chris Lattner4b009652007-07-25 00:24:17 +0000560 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
561 Tok.getLocation(), PP);
562 if (Literal.hadError)
563 return ExprResult(true);
564
Chris Lattner1de66eb2007-08-26 03:42:43 +0000565 Expr *Res;
566
567 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000568 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000569 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000570 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000571 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000572 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000573 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000574 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000575
576 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
577
Ted Kremenekddedbe22007-11-29 00:56:49 +0000578 // isExact will be set by GetFloatValue().
579 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000580 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000581 Ty, Tok.getLocation());
582
Chris Lattner1de66eb2007-08-26 03:42:43 +0000583 } else if (!Literal.isIntegerLiteral()) {
584 return ExprResult(true);
585 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000586 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000587
Neil Booth7421e9c2007-08-29 22:00:19 +0000588 // long long is a C99 feature.
589 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000590 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000591 Diag(Tok.getLocation(), diag::ext_longlong);
592
Chris Lattner4b009652007-07-25 00:24:17 +0000593 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000594 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000595
596 if (Literal.GetIntegerValue(ResultVal)) {
597 // If this value didn't fit into uintmax_t, warn and force to ull.
598 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000599 Ty = Context.UnsignedLongLongTy;
600 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000601 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000602 } else {
603 // If this value fits into a ULL, try to figure out what else it fits into
604 // according to the rules of C99 6.4.4.1p5.
605
606 // Octal, Hexadecimal, and integers with a U suffix are allowed to
607 // be an unsigned int.
608 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
609
610 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000611 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000612 if (!Literal.isLong && !Literal.isLongLong) {
613 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000614 unsigned IntSize = Context.Target.getIntWidth();
615
Chris Lattner4b009652007-07-25 00:24:17 +0000616 // Does it fit in a unsigned int?
617 if (ResultVal.isIntN(IntSize)) {
618 // Does it fit in a signed int?
619 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000620 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000621 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000622 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000623 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000624 }
Chris Lattner4b009652007-07-25 00:24:17 +0000625 }
626
627 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000628 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000629 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000630
631 // Does it fit in a unsigned long?
632 if (ResultVal.isIntN(LongSize)) {
633 // Does it fit in a signed long?
634 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000635 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000636 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000637 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000638 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000639 }
Chris Lattner4b009652007-07-25 00:24:17 +0000640 }
641
642 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000643 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000644 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000645
646 // Does it fit in a unsigned long long?
647 if (ResultVal.isIntN(LongLongSize)) {
648 // Does it fit in a signed long long?
649 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000650 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000651 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000652 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000653 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000654 }
655 }
656
657 // If we still couldn't decide a type, we probably have something that
658 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000659 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000660 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000661 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000662 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000663 }
Chris Lattnere4068872008-05-09 05:59:00 +0000664
665 if (ResultVal.getBitWidth() != Width)
666 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000667 }
668
Chris Lattner48d7f382008-04-02 04:24:33 +0000669 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000670 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000671
672 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
673 if (Literal.isImaginary)
674 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
675
676 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000677}
678
Steve Naroff87d58b42007-09-16 03:34:24 +0000679Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000680 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000681 Expr *E = (Expr *)Val;
682 assert((E != 0) && "ActOnParenExpr() missing expr");
683 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000684}
685
686/// The UsualUnaryConversions() function is *not* called by this routine.
687/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000688bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
689 SourceLocation OpLoc,
690 const SourceRange &ExprRange,
691 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000692 // C99 6.5.3.4p1:
693 if (isa<FunctionType>(exprType) && isSizeof)
694 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000695 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +0000696 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000697 Diag(OpLoc, diag::ext_sizeof_void_type)
698 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
699 else if (exprType->isIncompleteType())
700 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
701 diag::err_alignof_incomplete_type)
702 << exprType.getAsString() << ExprRange;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000703
704 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000705}
706
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000707/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
708/// the same for @c alignof and @c __alignof
709/// Note that the ArgRange is invalid if isType is false.
710Action::ExprResult
711Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
712 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +0000713 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000714 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000715
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000716 QualType ArgTy;
717 SourceRange Range;
718 if (isType) {
719 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
720 Range = ArgRange;
721 } else {
722 // Get the end location.
723 Expr *ArgEx = (Expr *)TyOrEx;
724 Range = ArgEx->getSourceRange();
725 ArgTy = ArgEx->getType();
726 }
727
728 // Verify that the operand is valid.
729 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +0000730 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000731
732 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
733 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
734 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +0000735}
736
Chris Lattner5110ad52007-08-24 21:41:10 +0000737QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000738 DefaultFunctionArrayConversion(V);
739
Chris Lattnera16e42d2007-08-26 05:39:26 +0000740 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000741 if (const ComplexType *CT = V->getType()->getAsComplexType())
742 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000743
744 // Otherwise they pass through real integer and floating point types here.
745 if (V->getType()->isArithmeticType())
746 return V->getType();
747
748 // Reject anything else.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000749 Diag(Loc, diag::err_realimag_invalid_type) << V->getType().getAsString();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000750 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000751}
752
753
Chris Lattner4b009652007-07-25 00:24:17 +0000754
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000755Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000756 tok::TokenKind Kind,
757 ExprTy *Input) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000758 Expr *Arg = (Expr *)Input;
759
Chris Lattner4b009652007-07-25 00:24:17 +0000760 UnaryOperator::Opcode Opc;
761 switch (Kind) {
762 default: assert(0 && "Unknown unary op!");
763 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
764 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
765 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000766
767 if (getLangOptions().CPlusPlus &&
768 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
769 // Which overloaded operator?
770 OverloadedOperatorKind OverOp =
771 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
772
773 // C++ [over.inc]p1:
774 //
775 // [...] If the function is a member function with one
776 // parameter (which shall be of type int) or a non-member
777 // function with two parameters (the second of which shall be
778 // of type int), it defines the postfix increment operator ++
779 // for objects of that type. When the postfix increment is
780 // called as a result of using the ++ operator, the int
781 // argument will have value zero.
782 Expr *Args[2] = {
783 Arg,
784 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
785 /*isSigned=*/true),
786 Context.IntTy, SourceLocation())
787 };
788
789 // Build the candidate set for overloading
790 OverloadCandidateSet CandidateSet;
791 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
792
793 // Perform overload resolution.
794 OverloadCandidateSet::iterator Best;
795 switch (BestViableFunction(CandidateSet, Best)) {
796 case OR_Success: {
797 // We found a built-in operator or an overloaded operator.
798 FunctionDecl *FnDecl = Best->Function;
799
800 if (FnDecl) {
801 // We matched an overloaded operator. Build a call to that
802 // operator.
803
804 // Convert the arguments.
805 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
806 if (PerformObjectArgumentInitialization(Arg, Method))
807 return true;
808 } else {
809 // Convert the arguments.
810 if (PerformCopyInitialization(Arg,
811 FnDecl->getParamDecl(0)->getType(),
812 "passing"))
813 return true;
814 }
815
816 // Determine the result type
817 QualType ResultTy
818 = FnDecl->getType()->getAsFunctionType()->getResultType();
819 ResultTy = ResultTy.getNonReferenceType();
820
821 // Build the actual expression node.
822 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
823 SourceLocation());
824 UsualUnaryConversions(FnExpr);
825
826 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
827 } else {
828 // We matched a built-in operator. Convert the arguments, then
829 // break out so that we will build the appropriate built-in
830 // operator node.
831 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
832 "passing"))
833 return true;
834
835 break;
836 }
837 }
838
839 case OR_No_Viable_Function:
840 // No viable function; fall through to handling this as a
841 // built-in operator, which will produce an error message for us.
842 break;
843
844 case OR_Ambiguous:
845 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
846 << UnaryOperator::getOpcodeStr(Opc)
847 << Arg->getSourceRange();
848 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
849 return true;
850 }
851
852 // Either we found no viable overloaded operator or we matched a
853 // built-in operator. In either case, fall through to trying to
854 // build a built-in operation.
855 }
856
857 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000858 if (result.isNull())
859 return true;
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000860 return new UnaryOperator(Arg, Opc, result, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000861}
862
863Action::ExprResult Sema::
Douglas Gregor80723c52008-11-19 17:17:41 +0000864ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000865 ExprTy *Idx, SourceLocation RLoc) {
866 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
867
Douglas Gregor80723c52008-11-19 17:17:41 +0000868 if (getLangOptions().CPlusPlus &&
869 LHSExp->getType()->isRecordType() ||
870 LHSExp->getType()->isEnumeralType() ||
871 RHSExp->getType()->isRecordType() ||
872 RHSExp->getType()->isRecordType()) {
873 // Add the appropriate overloaded operators (C++ [over.match.oper])
874 // to the candidate set.
875 OverloadCandidateSet CandidateSet;
876 Expr *Args[2] = { LHSExp, RHSExp };
877 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
878
879 // Perform overload resolution.
880 OverloadCandidateSet::iterator Best;
881 switch (BestViableFunction(CandidateSet, Best)) {
882 case OR_Success: {
883 // We found a built-in operator or an overloaded operator.
884 FunctionDecl *FnDecl = Best->Function;
885
886 if (FnDecl) {
887 // We matched an overloaded operator. Build a call to that
888 // operator.
889
890 // Convert the arguments.
891 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
892 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
893 PerformCopyInitialization(RHSExp,
894 FnDecl->getParamDecl(0)->getType(),
895 "passing"))
896 return true;
897 } else {
898 // Convert the arguments.
899 if (PerformCopyInitialization(LHSExp,
900 FnDecl->getParamDecl(0)->getType(),
901 "passing") ||
902 PerformCopyInitialization(RHSExp,
903 FnDecl->getParamDecl(1)->getType(),
904 "passing"))
905 return true;
906 }
907
908 // Determine the result type
909 QualType ResultTy
910 = FnDecl->getType()->getAsFunctionType()->getResultType();
911 ResultTy = ResultTy.getNonReferenceType();
912
913 // Build the actual expression node.
914 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
915 SourceLocation());
916 UsualUnaryConversions(FnExpr);
917
918 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
919 } else {
920 // We matched a built-in operator. Convert the arguments, then
921 // break out so that we will build the appropriate built-in
922 // operator node.
923 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
924 "passing") ||
925 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
926 "passing"))
927 return true;
928
929 break;
930 }
931 }
932
933 case OR_No_Viable_Function:
934 // No viable function; fall through to handling this as a
935 // built-in operator, which will produce an error message for us.
936 break;
937
938 case OR_Ambiguous:
939 Diag(LLoc, diag::err_ovl_ambiguous_oper)
940 << "[]"
941 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
942 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
943 return true;
944 }
945
946 // Either we found no viable overloaded operator or we matched a
947 // built-in operator. In either case, fall through to trying to
948 // build a built-in operation.
949 }
950
Chris Lattner4b009652007-07-25 00:24:17 +0000951 // Perform default conversions.
952 DefaultFunctionArrayConversion(LHSExp);
953 DefaultFunctionArrayConversion(RHSExp);
954
955 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
956
957 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000958 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000959 // in the subscript position. As a result, we need to derive the array base
960 // and index from the expression types.
961 Expr *BaseExpr, *IndexExpr;
962 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000963 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000964 BaseExpr = LHSExp;
965 IndexExpr = RHSExp;
966 // FIXME: need to deal with const...
967 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000968 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000969 // Handle the uncommon case of "123[Ptr]".
970 BaseExpr = RHSExp;
971 IndexExpr = LHSExp;
972 // FIXME: need to deal with const...
973 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000974 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
975 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000976 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000977
978 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000979 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
980 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +0000981 return Diag(LLoc, diag::err_ext_vector_component_access)
982 << SourceRange(LLoc, RLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000983 // FIXME: need to deal with const...
984 ResultType = VTy->getElementType();
985 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000986 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
987 << RHSExp->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +0000988 }
989 // C99 6.5.2.1p1
990 if (!IndexExpr->getType()->isIntegerType())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000991 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
992 << IndexExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +0000993
994 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
995 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000996 // void (*)(int)) and pointers to incomplete types. Functions are not
997 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000998 if (!ResultType->isObjectType())
999 return Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001000 diag::err_typecheck_subscript_not_object)
1001 << BaseExpr->getType().getAsString() << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001002
1003 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
1004}
1005
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001006QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001007CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001008 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001009 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001010
1011 // This flag determines whether or not the component is to be treated as a
1012 // special name, or a regular GLSL-style component access.
1013 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001014
1015 // The vector accessor can't exceed the number of elements.
1016 const char *compStr = CompName.getName();
1017 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001018 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1019 << baseType.getAsString() << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001020 return QualType();
1021 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001022
1023 // Check that we've found one of the special components, or that the component
1024 // names must come from the same set.
1025 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1026 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1027 SpecialComponent = true;
1028 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001029 do
1030 compStr++;
1031 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1032 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1033 do
1034 compStr++;
1035 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1036 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1037 do
1038 compStr++;
1039 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1040 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001041
Nate Begemanc8e51f82008-05-09 06:41:27 +00001042 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001043 // We didn't get to the end of the string. This means the component names
1044 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001045 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1046 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001047 return QualType();
1048 }
1049 // Each component accessor can't exceed the vector type.
1050 compStr = CompName.getName();
1051 while (*compStr) {
1052 if (vecType->isAccessorWithinNumElements(*compStr))
1053 compStr++;
1054 else
1055 break;
1056 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001057 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001058 // We didn't get to the end of the string. This means a component accessor
1059 // exceeds the number of elements in the vector.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001060 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1061 << baseType.getAsString() << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001062 return QualType();
1063 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001064
1065 // If we have a special component name, verify that the current vector length
1066 // is an even number, since all special component names return exactly half
1067 // the elements.
1068 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001069 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
1070 << baseType.getAsString() << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001071 return QualType();
1072 }
1073
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001074 // The component accessor looks fine - now we need to compute the actual type.
1075 // The vector type is implied by the component accessor. For example,
1076 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001077 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1078 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner65cae292008-11-19 08:23:25 +00001079 : CompName.getLength();
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001080 if (CompSize == 1)
1081 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001082
Nate Begemanaf6ed502008-04-18 23:10:10 +00001083 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001084 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001085 // diagostics look bad. We want extended vector types to appear built-in.
1086 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1087 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1088 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001089 }
1090 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001091}
1092
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001093/// constructSetterName - Return the setter name for the given
1094/// identifier, i.e. "set" + Name where the initial character of Name
1095/// has been capitalized.
1096// FIXME: Merge with same routine in Parser. But where should this
1097// live?
1098static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1099 const IdentifierInfo *Name) {
Chris Lattner65cae292008-11-19 08:23:25 +00001100 llvm::SmallString<100> SelectorName;
Chris Lattner01f03cf2008-11-20 07:09:32 +00001101 SelectorName = "set";
Chris Lattner65cae292008-11-19 08:23:25 +00001102 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001103 SelectorName[3] = toupper(SelectorName[3]);
Chris Lattner65cae292008-11-19 08:23:25 +00001104 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001105}
1106
Chris Lattner4b009652007-07-25 00:24:17 +00001107Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001108ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001109 tok::TokenKind OpKind, SourceLocation MemberLoc,
1110 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001111 Expr *BaseExpr = static_cast<Expr *>(Base);
1112 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001113
1114 // Perform default conversions.
1115 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +00001116
Steve Naroff2cb66382007-07-26 03:11:44 +00001117 QualType BaseType = BaseExpr->getType();
1118 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001119
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001120 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1121 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001122 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001123 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001124 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001125 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
1126 return BuildOverloadedArrowExpr(BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroff2cb66382007-07-26 03:11:44 +00001127 else
Chris Lattner8ba580c2008-11-19 05:08:23 +00001128 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1129 << BaseType.getAsString() << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001130 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001131
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001132 // Handle field access to simple records. This also handles access to fields
1133 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001134 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001135 RecordDecl *RDecl = RTy->getDecl();
1136 if (RTy->isIncompleteType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001137 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
1138 << RDecl->getName() << BaseExpr->getSourceRange();
Steve Naroff2cb66382007-07-26 03:11:44 +00001139 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001140 FieldDecl *MemberDecl = RDecl->getMember(&Member);
1141 if (!MemberDecl)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001142 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner65cae292008-11-19 08:23:25 +00001143 << &Member << BaseExpr->getSourceRange();
Eli Friedman76b49832008-02-06 22:48:16 +00001144
1145 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +00001146 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +00001147 QualType MemberType = MemberDecl->getType();
1148 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +00001149 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +00001150 if (CXXFieldDecl *CXXMember = dyn_cast<CXXFieldDecl>(MemberDecl)) {
1151 if (CXXMember->isMutable())
1152 combinedQualifiers &= ~QualType::Const;
1153 }
Eli Friedman76b49832008-02-06 22:48:16 +00001154 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1155
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001156 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +00001157 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +00001158 }
1159
Chris Lattnere9d71612008-07-21 04:59:05 +00001160 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1161 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001162 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
1163 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001164 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +00001165 OpKind == tok::arrow);
Chris Lattner8ba580c2008-11-19 05:08:23 +00001166 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattner65cae292008-11-19 08:23:25 +00001167 << IFTy->getDecl()->getName() << &Member
Chris Lattner8ba580c2008-11-19 05:08:23 +00001168 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001169 }
1170
Chris Lattnere9d71612008-07-21 04:59:05 +00001171 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1172 // pointer to a (potentially qualified) interface type.
1173 const PointerType *PTy;
1174 const ObjCInterfaceType *IFTy;
1175 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1176 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1177 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001178
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001179 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001180 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1181 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1182
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001183 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001184 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1185 E = IFTy->qual_end(); I != E; ++I)
1186 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1187 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001188
1189 // If that failed, look for an "implicit" property by seeing if the nullary
1190 // selector is implemented.
1191
1192 // FIXME: The logic for looking up nullary and unary selectors should be
1193 // shared with the code in ActOnInstanceMessage.
1194
1195 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1196 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1197
1198 // If this reference is in an @implementation, check for 'private' methods.
1199 if (!Getter)
1200 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1201 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1202 if (ObjCImplementationDecl *ImpDecl =
1203 ObjCImplementations[ClassDecl->getIdentifier()])
1204 Getter = ImpDecl->getInstanceMethod(Sel);
1205
Steve Naroff04151f32008-10-22 19:16:27 +00001206 // Look through local category implementations associated with the class.
1207 if (!Getter) {
1208 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1209 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1210 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1211 }
1212 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001213 if (Getter) {
1214 // If we found a getter then this may be a valid dot-reference, we
1215 // need to also look for the matching setter.
1216 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1217 &Member);
1218 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1219 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1220
1221 if (!Setter) {
1222 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1223 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1224 if (ObjCImplementationDecl *ImpDecl =
1225 ObjCImplementations[ClassDecl->getIdentifier()])
1226 Setter = ImpDecl->getInstanceMethod(SetterSel);
1227 }
1228
1229 // FIXME: There are some issues here. First, we are not
1230 // diagnosing accesses to read-only properties because we do not
1231 // know if this is a getter or setter yet. Second, we are
1232 // checking that the type of the setter matches the type we
1233 // expect.
1234 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1235 MemberLoc, BaseExpr);
1236 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001237 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001238 // Handle properties on qualified "id" protocols.
1239 const ObjCQualifiedIdType *QIdTy;
1240 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1241 // Check protocols on qualified interfaces.
1242 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1243 E = QIdTy->qual_end(); I != E; ++I)
1244 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1245 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1246 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001247 // Handle 'field access' to vectors, such as 'V.xx'.
1248 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1249 // Component access limited to variables (reject vec4.rg.g).
1250 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1251 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001252 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1253 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001254 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1255 if (ret.isNull())
1256 return true;
1257 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1258 }
1259
Chris Lattner8ba580c2008-11-19 05:08:23 +00001260 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
1261 << BaseType.getAsString() << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001262}
1263
Steve Naroff87d58b42007-09-16 03:34:24 +00001264/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001265/// This provides the location of the left/right parens and a list of comma
1266/// locations.
1267Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001268ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001269 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001270 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1271 Expr *Fn = static_cast<Expr *>(fn);
1272 Expr **Args = reinterpret_cast<Expr**>(args);
1273 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001274 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001275 OverloadedFunctionDecl *Ovl = NULL;
1276
1277 // If we're directly calling a function or a set of overloaded
1278 // functions, get the appropriate declaration.
1279 {
1280 DeclRefExpr *DRExpr = NULL;
1281 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1282 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1283 else
1284 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1285
1286 if (DRExpr) {
1287 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1288 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1289 }
1290 }
1291
1292 // If we have a set of overloaded functions, perform overload
1293 // resolution to pick the function.
1294 if (Ovl) {
1295 OverloadCandidateSet CandidateSet;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001296 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
Douglas Gregor10f3c502008-11-19 21:05:33 +00001297 OverloadCandidateSet::iterator Best;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001298 switch (BestViableFunction(CandidateSet, Best)) {
1299 case OR_Success:
1300 {
1301 // Success! Let the remainder of this function build a call to
1302 // the function selected by overload resolution.
1303 FDecl = Best->Function;
1304 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1305 Fn->getSourceRange().getBegin());
1306 delete Fn;
1307 Fn = NewFn;
1308 }
1309 break;
1310
1311 case OR_No_Viable_Function:
1312 if (CandidateSet.empty())
1313 Diag(Fn->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001314 diag::err_ovl_no_viable_function_in_call)
1315 << Ovl->getName() << Fn->getSourceRange();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001316 else {
1317 Diag(Fn->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001318 diag::err_ovl_no_viable_function_in_call_with_cands)
1319 << Ovl->getName() << Fn->getSourceRange();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001320 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1321 }
1322 return true;
1323
1324 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00001325 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
1326 << Ovl->getName() << 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)
1350 << 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)
1358 << 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 Lattner97316c02008-04-10 02:22:51 +00001372 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001373 // Use default arguments for missing arguments
1374 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +00001375 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001376 } else
Steve Naroffd6163f32008-09-05 22:11:13 +00001377 return Diag(RParenLoc,
1378 !Fn->getType()->isBlockPointerType()
1379 ? diag::err_typecheck_call_too_few_args
Chris Lattner8ba580c2008-11-19 05:08:23 +00001380 : diag::err_typecheck_block_too_few_args)
1381 << Fn->getSourceRange();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001382 }
1383
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001384 // If too many are passed and not variadic, error on the extras and drop
1385 // them.
1386 if (NumArgs > NumArgsInProto) {
1387 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001388 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffd6163f32008-09-05 22:11:13 +00001389 !Fn->getType()->isBlockPointerType()
1390 ? diag::err_typecheck_call_too_many_args
Chris Lattner8ba580c2008-11-19 05:08:23 +00001391 : diag::err_typecheck_block_too_many_args)
1392 << Fn->getSourceRange()
1393 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1394 Args[NumArgs-1]->getLocEnd());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001395 // This deletes the extra arguments.
1396 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001397 }
1398 NumArgsToCheck = NumArgsInProto;
1399 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001400
Chris Lattner4b009652007-07-25 00:24:17 +00001401 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001402 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001403 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001404
1405 Expr *Arg;
1406 if (i < NumArgs)
1407 Arg = Args[i];
1408 else
1409 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001410 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001411
Douglas Gregor81c29152008-10-29 00:13:59 +00001412 // Pass the argument.
1413 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner005ed752008-01-04 18:04:52 +00001414 return true;
Douglas Gregor81c29152008-10-29 00:13:59 +00001415
1416 TheCall->setArg(i, Arg);
Chris Lattner4b009652007-07-25 00:24:17 +00001417 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001418
1419 // If this is a variadic call, handle args passed through "...".
1420 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001421 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001422 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1423 Expr *Arg = Args[i];
1424 DefaultArgumentPromotion(Arg);
1425 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001426 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001427 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001428 } else {
1429 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1430
Steve Naroffdb65e052007-08-28 23:30:39 +00001431 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001432 for (unsigned i = 0; i != NumArgs; i++) {
1433 Expr *Arg = Args[i];
1434 DefaultArgumentPromotion(Arg);
1435 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001436 }
Chris Lattner4b009652007-07-25 00:24:17 +00001437 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001438
Chris Lattner2e64c072007-08-10 20:18:51 +00001439 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001440 if (FDecl)
1441 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001442
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001443 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001444}
1445
1446Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001447ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001448 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001449 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001450 QualType literalType = QualType::getFromOpaquePtr(Ty);
1451 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001452 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001453 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001454
Eli Friedman8c2173d2008-05-20 05:22:08 +00001455 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001456 if (literalType->isVariableArrayType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001457 return Diag(LParenLoc, diag::err_variable_object_no_init)
1458 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001459 } else if (literalType->isIncompleteType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001460 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
1461 << literalType.getAsString()
1462 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001463 }
1464
Douglas Gregor6428e762008-11-05 15:29:30 +00001465 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
1466 "temporary"))
Steve Naroff92590f92008-01-09 20:58:06 +00001467 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001468
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001469 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001470 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001471 if (CheckForConstantInitializer(literalExpr, literalType))
1472 return true;
1473 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001474 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1475 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001476}
1477
1478Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001479ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001480 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001481 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001482 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001483
Steve Naroff0acc9c92007-09-15 18:49:24 +00001484 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001485 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001486
Chris Lattner71ca8c82008-10-26 23:43:26 +00001487 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1488 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001489 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1490 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001491}
1492
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001493/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001494bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001495 UsualUnaryConversions(castExpr);
1496
1497 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1498 // type needs to be scalar.
1499 if (castType->isVoidType()) {
1500 // Cast to void allows any expr type.
1501 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1502 // GCC struct/union extension: allow cast to self.
1503 if (Context.getCanonicalType(castType) !=
1504 Context.getCanonicalType(castExpr->getType()) ||
1505 (!castType->isStructureType() && !castType->isUnionType())) {
1506 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001507 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
1508 << castType.getAsString() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001509 }
1510
1511 // accept this, but emit an ext-warn.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001512 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
1513 << castType.getAsString() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001514 } else if (!castExpr->getType()->isScalarType() &&
1515 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001516 return Diag(castExpr->getLocStart(),
1517 diag::err_typecheck_expect_scalar_operand)
1518 << castExpr->getType().getAsString() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001519 } else if (castExpr->getType()->isVectorType()) {
1520 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1521 return true;
1522 } else if (castType->isVectorType()) {
1523 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1524 return true;
1525 }
1526 return false;
1527}
1528
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001529bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001530 assert(VectorTy->isVectorType() && "Not a vector type!");
1531
1532 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001533 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001534 return Diag(R.getBegin(),
1535 Ty->isVectorType() ?
1536 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00001537 diag::err_invalid_conversion_between_vector_and_integer)
1538 << VectorTy.getAsString() << Ty.getAsString() << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001539 } else
1540 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001541 diag::err_invalid_conversion_between_vector_and_scalar)
1542 << VectorTy.getAsString() << Ty.getAsString() << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001543
1544 return false;
1545}
1546
Chris Lattner4b009652007-07-25 00:24:17 +00001547Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001548ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001549 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001550 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001551
1552 Expr *castExpr = static_cast<Expr*>(Op);
1553 QualType castType = QualType::getFromOpaquePtr(Ty);
1554
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001555 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1556 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00001557 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001558}
1559
Chris Lattner98a425c2007-11-26 01:40:58 +00001560/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1561/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001562inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1563 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1564 UsualUnaryConversions(cond);
1565 UsualUnaryConversions(lex);
1566 UsualUnaryConversions(rex);
1567 QualType condT = cond->getType();
1568 QualType lexT = lex->getType();
1569 QualType rexT = rex->getType();
1570
1571 // first, check the condition.
1572 if (!condT->isScalarType()) { // C99 6.5.15p2
Chris Lattner10f2c2e2008-11-20 06:38:18 +00001573 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
1574 << condT.getAsString();
Chris Lattner4b009652007-07-25 00:24:17 +00001575 return QualType();
1576 }
Chris Lattner992ae932008-01-06 22:42:25 +00001577
1578 // Now check the two expressions.
1579
1580 // If both operands have arithmetic type, do the usual arithmetic conversions
1581 // to find a common type: C99 6.5.15p3,5.
1582 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001583 UsualArithmeticConversions(lex, rex);
1584 return lex->getType();
1585 }
Chris Lattner992ae932008-01-06 22:42:25 +00001586
1587 // If both operands are the same structure or union type, the result is that
1588 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001589 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001590 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001591 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001592 // "If both the operands have structure or union type, the result has
1593 // that type." This implies that CV qualifiers are dropped.
1594 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001595 }
Chris Lattner992ae932008-01-06 22:42:25 +00001596
1597 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001598 // The following || allows only one side to be void (a GCC-ism).
1599 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001600 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001601 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
1602 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00001603 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001604 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
1605 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00001606 ImpCastExprToType(lex, Context.VoidTy);
1607 ImpCastExprToType(rex, Context.VoidTy);
1608 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001609 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001610 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1611 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001612 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1613 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001614 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001615 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001616 return lexT;
1617 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001618 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1619 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001620 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001621 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001622 return rexT;
1623 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001624 // Handle the case where both operands are pointers before we handle null
1625 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001626 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1627 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1628 // get the "pointed to" types
1629 QualType lhptee = LHSPT->getPointeeType();
1630 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001631
Chris Lattner71225142007-07-31 21:27:01 +00001632 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1633 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001634 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001635 // Figure out necessary qualifiers (C99 6.5.15p6)
1636 QualType destPointee=lhptee.getQualifiedType(rhptee.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 Lattner9db553e2008-04-02 06:59:01 +00001642 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001643 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001644 QualType destType = Context.getPointerType(destPointee);
1645 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1646 ImpCastExprToType(rex, destType); // promote to void*
1647 return destType;
1648 }
Chris Lattner4b009652007-07-25 00:24:17 +00001649
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001650 QualType compositeType = lexT;
1651
1652 // If either type is an Objective-C object type then check
1653 // compatibility according to Objective-C.
1654 if (Context.isObjCObjectPointerType(lexT) ||
1655 Context.isObjCObjectPointerType(rexT)) {
1656 // If both operands are interfaces and either operand can be
1657 // assigned to the other, use that type as the composite
1658 // type. This allows
1659 // xxx ? (A*) a : (B*) b
1660 // where B is a subclass of A.
1661 //
1662 // Additionally, as for assignment, if either type is 'id'
1663 // allow silent coercion. Finally, if the types are
1664 // incompatible then make sure to use 'id' as the composite
1665 // type so the result is acceptable for sending messages to.
1666
1667 // FIXME: This code should not be localized to here. Also this
1668 // should use a compatible check instead of abusing the
1669 // canAssignObjCInterfaces code.
1670 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1671 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1672 if (LHSIface && RHSIface &&
1673 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1674 compositeType = lexT;
1675 } else if (LHSIface && RHSIface &&
1676 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1677 compositeType = rexT;
1678 } else if (Context.isObjCIdType(lhptee) ||
1679 Context.isObjCIdType(rhptee)) {
1680 // FIXME: This code looks wrong, because isObjCIdType checks
1681 // the struct but getObjCIdType returns the pointer to
1682 // struct. This is horrible and should be fixed.
1683 compositeType = Context.getObjCIdType();
1684 } else {
1685 QualType incompatTy = Context.getObjCIdType();
1686 ImpCastExprToType(lex, incompatTy);
1687 ImpCastExprToType(rex, incompatTy);
1688 return incompatTy;
1689 }
1690 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1691 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00001692 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
1693 << lexT.getAsString() << rexT.getAsString()
1694 << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001695 // In this situation, we assume void* type. No especially good
1696 // reason, but this is what gcc does, and we do have to pick
1697 // to get a consistent AST.
1698 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001699 ImpCastExprToType(lex, incompatTy);
1700 ImpCastExprToType(rex, incompatTy);
1701 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001702 }
1703 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001704 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1705 // differently qualified versions of compatible types, the result type is
1706 // a pointer to an appropriately qualified version of the *composite*
1707 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001708 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001709 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001710 ImpCastExprToType(lex, compositeType);
1711 ImpCastExprToType(rex, compositeType);
1712 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001713 }
Chris Lattner4b009652007-07-25 00:24:17 +00001714 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001715 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1716 // evaluates to "struct objc_object *" (and is handled above when comparing
1717 // id with statically typed objects).
1718 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1719 // GCC allows qualified id and any Objective-C type to devolve to
1720 // id. Currently localizing to here until clear this should be
1721 // part of ObjCQualifiedIdTypesAreCompatible.
1722 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1723 (lexT->isObjCQualifiedIdType() &&
1724 Context.isObjCObjectPointerType(rexT)) ||
1725 (rexT->isObjCQualifiedIdType() &&
1726 Context.isObjCObjectPointerType(lexT))) {
1727 // FIXME: This is not the correct composite type. This only
1728 // happens to work because id can more or less be used anywhere,
1729 // however this may change the type of method sends.
1730 // FIXME: gcc adds some type-checking of the arguments and emits
1731 // (confusing) incompatible comparison warnings in some
1732 // cases. Investigate.
1733 QualType compositeType = Context.getObjCIdType();
1734 ImpCastExprToType(lex, compositeType);
1735 ImpCastExprToType(rex, compositeType);
1736 return compositeType;
1737 }
1738 }
1739
Steve Naroff3eac7692008-09-10 19:17:48 +00001740 // Selection between block pointer types is ok as long as they are the same.
1741 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1742 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1743 return lexT;
1744
Chris Lattner992ae932008-01-06 22:42:25 +00001745 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00001746 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
1747 << lexT.getAsString() << rexT.getAsString()
1748 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001749 return QualType();
1750}
1751
Steve Naroff87d58b42007-09-16 03:34:24 +00001752/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001753/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001754Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001755 SourceLocation ColonLoc,
1756 ExprTy *Cond, ExprTy *LHS,
1757 ExprTy *RHS) {
1758 Expr *CondExpr = (Expr *) Cond;
1759 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001760
1761 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1762 // was the condition.
1763 bool isLHSNull = LHSExpr == 0;
1764 if (isLHSNull)
1765 LHSExpr = CondExpr;
1766
Chris Lattner4b009652007-07-25 00:24:17 +00001767 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1768 RHSExpr, QuestionLoc);
1769 if (result.isNull())
1770 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001771 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1772 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001773}
1774
Chris Lattner4b009652007-07-25 00:24:17 +00001775
1776// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1777// being closely modeled after the C99 spec:-). The odd characteristic of this
1778// routine is it effectively iqnores the qualifiers on the top level pointee.
1779// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1780// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001781Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001782Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1783 QualType lhptee, rhptee;
1784
1785 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001786 lhptee = lhsType->getAsPointerType()->getPointeeType();
1787 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001788
1789 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001790 lhptee = Context.getCanonicalType(lhptee);
1791 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001792
Chris Lattner005ed752008-01-04 18:04:52 +00001793 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001794
1795 // C99 6.5.16.1p1: This following citation is common to constraints
1796 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1797 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001798 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001799 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001800 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001801
1802 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1803 // incomplete type and the other is a pointer to a qualified or unqualified
1804 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001805 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001806 if (rhptee->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(rhptee->isFunctionType());
1811 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001812 }
1813
1814 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001815 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001816 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001817
1818 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001819 assert(lhptee->isFunctionType());
1820 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001821 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001822
1823 // Check for ObjC interfaces
1824 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1825 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1826 if (LHSIface && RHSIface &&
1827 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1828 return ConvTy;
1829
1830 // ID acts sort of like void* for ObjC interfaces
1831 if (LHSIface && Context.isObjCIdType(rhptee))
1832 return ConvTy;
1833 if (RHSIface && Context.isObjCIdType(lhptee))
1834 return ConvTy;
1835
Chris Lattner4b009652007-07-25 00:24:17 +00001836 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1837 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001838 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1839 rhptee.getUnqualifiedType()))
1840 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001841 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001842}
1843
Steve Naroff3454b6c2008-09-04 15:10:53 +00001844/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1845/// block pointer types are compatible or whether a block and normal pointer
1846/// are compatible. It is more restrict than comparing two function pointer
1847// types.
1848Sema::AssignConvertType
1849Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1850 QualType rhsType) {
1851 QualType lhptee, rhptee;
1852
1853 // get the "pointed to" type (ignoring qualifiers at the top level)
1854 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1855 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1856
1857 // make sure we operate on the canonical type
1858 lhptee = Context.getCanonicalType(lhptee);
1859 rhptee = Context.getCanonicalType(rhptee);
1860
1861 AssignConvertType ConvTy = Compatible;
1862
1863 // For blocks we enforce that qualifiers are identical.
1864 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1865 ConvTy = CompatiblePointerDiscardsQualifiers;
1866
1867 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1868 return IncompatibleBlockPointer;
1869 return ConvTy;
1870}
1871
Chris Lattner4b009652007-07-25 00:24:17 +00001872/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1873/// has code to accommodate several GCC extensions when type checking
1874/// pointers. Here are some objectionable examples that GCC considers warnings:
1875///
1876/// int a, *pint;
1877/// short *pshort;
1878/// struct foo *pfoo;
1879///
1880/// pint = pshort; // warning: assignment from incompatible pointer type
1881/// a = pint; // warning: assignment makes integer from pointer without a cast
1882/// pint = a; // warning: assignment makes pointer from integer without a cast
1883/// pint = pfoo; // warning: assignment from incompatible pointer type
1884///
1885/// As a result, the code for dealing with pointers is more complex than the
1886/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001887///
Chris Lattner005ed752008-01-04 18:04:52 +00001888Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001889Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001890 // Get canonical types. We're not formatting these types, just comparing
1891 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001892 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1893 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001894
1895 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001896 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001897
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001898 // If the left-hand side is a reference type, then we are in a
1899 // (rare!) case where we've allowed the use of references in C,
1900 // e.g., as a parameter type in a built-in function. In this case,
1901 // just make sure that the type referenced is compatible with the
1902 // right-hand side type. The caller is responsible for adjusting
1903 // lhsType so that the resulting expression does not have reference
1904 // type.
1905 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
1906 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001907 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001908 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001909 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001910
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001911 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1912 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001913 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001914 // Relax integer conversions like we do for pointers below.
1915 if (rhsType->isIntegerType())
1916 return IntToPointer;
1917 if (lhsType->isIntegerType())
1918 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00001919 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001920 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001921
Nate Begemanc5f0f652008-07-14 18:02:46 +00001922 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001923 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001924 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1925 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001926 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001927
Nate Begemanc5f0f652008-07-14 18:02:46 +00001928 // If we are allowing lax vector conversions, and LHS and RHS are both
1929 // vectors, the total size only needs to be the same. This is a bitcast;
1930 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001931 if (getLangOptions().LaxVectorConversions &&
1932 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001933 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1934 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001935 }
1936 return Incompatible;
1937 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001938
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001939 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001940 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001941
Chris Lattner390564e2008-04-07 06:49:41 +00001942 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001943 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001944 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001945
Chris Lattner390564e2008-04-07 06:49:41 +00001946 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001947 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001948
Steve Naroffa982c712008-09-29 18:10:17 +00001949 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00001950 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff3454b6c2008-09-04 15:10:53 +00001951 return BlockVoidPointer;
Steve Naroffa982c712008-09-29 18:10:17 +00001952
1953 // Treat block pointers as objects.
1954 if (getLangOptions().ObjC1 &&
1955 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1956 return Compatible;
1957 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001958 return Incompatible;
1959 }
1960
1961 if (isa<BlockPointerType>(lhsType)) {
1962 if (rhsType->isIntegerType())
1963 return IntToPointer;
1964
Steve Naroffa982c712008-09-29 18:10:17 +00001965 // Treat block pointers as objects.
1966 if (getLangOptions().ObjC1 &&
1967 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1968 return Compatible;
1969
Steve Naroff3454b6c2008-09-04 15:10:53 +00001970 if (rhsType->isBlockPointerType())
1971 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1972
1973 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1974 if (RHSPT->getPointeeType()->isVoidType())
1975 return BlockVoidPointer;
1976 }
Chris Lattner1853da22008-01-04 23:18:45 +00001977 return Incompatible;
1978 }
1979
Chris Lattner390564e2008-04-07 06:49:41 +00001980 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001981 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001982 if (lhsType == Context.BoolTy)
1983 return Compatible;
1984
1985 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001986 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001987
Chris Lattner390564e2008-04-07 06:49:41 +00001988 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001989 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001990
1991 if (isa<BlockPointerType>(lhsType) &&
1992 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1993 return BlockVoidPointer;
Chris Lattner1853da22008-01-04 23:18:45 +00001994 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001995 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001996
Chris Lattner1853da22008-01-04 23:18:45 +00001997 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001998 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001999 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002000 }
2001 return Incompatible;
2002}
2003
Chris Lattner005ed752008-01-04 18:04:52 +00002004Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002005Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002006 if (getLangOptions().CPlusPlus) {
2007 if (!lhsType->isRecordType()) {
2008 // C++ 5.17p3: If the left operand is not of class type, the
2009 // expression is implicitly converted (C++ 4) to the
2010 // cv-unqualified type of the left operand.
Douglas Gregorbb461502008-10-24 04:54:22 +00002011 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002012 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002013 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002014 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002015 }
2016
2017 // FIXME: Currently, we fall through and treat C++ classes like C
2018 // structures.
2019 }
2020
Steve Naroffcdee22d2007-11-27 17:58:44 +00002021 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2022 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002023 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2024 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002025 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002026 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002027 return Compatible;
2028 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002029
2030 // We don't allow conversion of non-null-pointer constants to integers.
2031 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2032 return IntToBlockPointer;
2033
Chris Lattner5f505bf2007-10-16 02:55:40 +00002034 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002035 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002036 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002037 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002038 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002039 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002040 if (!lhsType->isReferenceType())
2041 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002042
Chris Lattner005ed752008-01-04 18:04:52 +00002043 Sema::AssignConvertType result =
2044 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002045
2046 // C99 6.5.16.1p2: The value of the right operand is converted to the
2047 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002048 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2049 // so that we can use references in built-in functions even in C.
2050 // The getNonReferenceType() call makes sure that the resulting expression
2051 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002052 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002053 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002054 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002055}
2056
Chris Lattner005ed752008-01-04 18:04:52 +00002057Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002058Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2059 return CheckAssignmentConstraints(lhsType, rhsType);
2060}
2061
Chris Lattner1eafdea2008-11-18 01:30:42 +00002062QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002063 Diag(Loc, diag::err_typecheck_invalid_operands)
2064 << lex->getType().getAsString() << rex->getType().getAsString()
2065 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002066 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002067}
2068
Chris Lattner1eafdea2008-11-18 01:30:42 +00002069inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002070 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002071 // For conversion purposes, we ignore any qualifiers.
2072 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002073 QualType lhsType =
2074 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2075 QualType rhsType =
2076 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002077
Nate Begemanc5f0f652008-07-14 18:02:46 +00002078 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002079 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002080 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002081
Nate Begemanc5f0f652008-07-14 18:02:46 +00002082 // Handle the case of a vector & extvector type of the same size and element
2083 // type. It would be nice if we only had one vector type someday.
2084 if (getLangOptions().LaxVectorConversions)
2085 if (const VectorType *LV = lhsType->getAsVectorType())
2086 if (const VectorType *RV = rhsType->getAsVectorType())
2087 if (LV->getElementType() == RV->getElementType() &&
2088 LV->getNumElements() == RV->getNumElements())
2089 return lhsType->isExtVectorType() ? lhsType : rhsType;
2090
2091 // If the lhs is an extended vector and the rhs is a scalar of the same type
2092 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002093 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002094 QualType eltType = V->getElementType();
2095
2096 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2097 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2098 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002099 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002100 return lhsType;
2101 }
2102 }
2103
Nate Begemanc5f0f652008-07-14 18:02:46 +00002104 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002105 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002106 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002107 QualType eltType = V->getElementType();
2108
2109 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2110 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2111 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002112 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002113 return rhsType;
2114 }
2115 }
2116
Chris Lattner4b009652007-07-25 00:24:17 +00002117 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002118 Diag(Loc, diag::err_typecheck_vector_not_convertable)
2119 << lex->getType().getAsString() << rex->getType().getAsString()
2120 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002121 return QualType();
2122}
2123
2124inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002125 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002126{
2127 QualType lhsType = lex->getType(), rhsType = rex->getType();
2128
2129 if (lhsType->isVectorType() || rhsType->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002130 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002131
Steve Naroff8f708362007-08-24 19:07:16 +00002132 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002133
Chris Lattner4b009652007-07-25 00:24:17 +00002134 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002135 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002136 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002137}
2138
2139inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002140 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002141{
2142 QualType lhsType = lex->getType(), rhsType = rex->getType();
2143
Steve Naroff8f708362007-08-24 19:07:16 +00002144 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002145
Chris Lattner4b009652007-07-25 00:24:17 +00002146 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002147 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002148 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002149}
2150
2151inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002152 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002153{
2154 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002155 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002156
Steve Naroff8f708362007-08-24 19:07:16 +00002157 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002158
Chris Lattner4b009652007-07-25 00:24:17 +00002159 // handle the common case first (both operands are arithmetic).
2160 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002161 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002162
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002163 // Put any potential pointer into PExp
2164 Expr* PExp = lex, *IExp = rex;
2165 if (IExp->getType()->isPointerType())
2166 std::swap(PExp, IExp);
2167
2168 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2169 if (IExp->getType()->isIntegerType()) {
2170 // Check for arithmetic on pointers to incomplete types
2171 if (!PTy->getPointeeType()->isObjectType()) {
2172 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002173 Diag(Loc, diag::ext_gnu_void_ptr)
2174 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002175 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002176 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
2177 << lex->getType().getAsString() << lex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002178 return QualType();
2179 }
2180 }
2181 return PExp->getType();
2182 }
2183 }
2184
Chris Lattner1eafdea2008-11-18 01:30:42 +00002185 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002186}
2187
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002188// C99 6.5.6
2189QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002190 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002191 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002192 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002193
Steve Naroff8f708362007-08-24 19:07:16 +00002194 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002195
Chris Lattnerf6da2912007-12-09 21:53:25 +00002196 // Enforce type constraints: C99 6.5.6p3.
2197
2198 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002199 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002200 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002201
2202 // Either ptr - int or ptr - ptr.
2203 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002204 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002205
Chris Lattnerf6da2912007-12-09 21:53:25 +00002206 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002207 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002208 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002209 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002210 Diag(Loc, diag::ext_gnu_void_ptr)
2211 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002212 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002213 Diag(Loc, diag::err_typecheck_sub_ptr_object)
2214 << lex->getType().getAsString() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002215 return QualType();
2216 }
2217 }
2218
2219 // The result type of a pointer-int computation is the pointer type.
2220 if (rex->getType()->isIntegerType())
2221 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002222
Chris Lattnerf6da2912007-12-09 21:53:25 +00002223 // Handle pointer-pointer subtractions.
2224 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002225 QualType rpointee = RHSPTy->getPointeeType();
2226
Chris Lattnerf6da2912007-12-09 21:53:25 +00002227 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002228 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002229 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002230 if (rpointee->isVoidType()) {
2231 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002232 Diag(Loc, diag::ext_gnu_void_ptr)
2233 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002234 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002235 Diag(Loc, diag::err_typecheck_sub_ptr_object)
2236 << rex->getType().getAsString() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002237 return QualType();
2238 }
2239 }
2240
2241 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002242 if (!Context.typesAreCompatible(
2243 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2244 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002245 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
2246 << lex->getType().getAsString() << rex->getType().getAsString()
2247 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002248 return QualType();
2249 }
2250
2251 return Context.getPointerDiffType();
2252 }
2253 }
2254
Chris Lattner1eafdea2008-11-18 01:30:42 +00002255 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002256}
2257
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002258// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002259QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002260 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002261 // C99 6.5.7p2: Each of the operands shall have integer type.
2262 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002263 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002264
Chris Lattner2c8bff72007-12-12 05:47:28 +00002265 // Shifts don't perform usual arithmetic conversions, they just do integer
2266 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002267 if (!isCompAssign)
2268 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002269 UsualUnaryConversions(rex);
2270
2271 // "The type of the result is that of the promoted left operand."
2272 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002273}
2274
Eli Friedman0d9549b2008-08-22 00:56:42 +00002275static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2276 ASTContext& Context) {
2277 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2278 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2279 // ID acts sort of like void* for ObjC interfaces
2280 if (LHSIface && Context.isObjCIdType(RHS))
2281 return true;
2282 if (RHSIface && Context.isObjCIdType(LHS))
2283 return true;
2284 if (!LHSIface || !RHSIface)
2285 return false;
2286 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2287 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2288}
2289
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002290// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002291QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002292 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002293 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002294 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002295
Chris Lattner254f3bc2007-08-26 01:18:55 +00002296 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002297 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2298 UsualArithmeticConversions(lex, rex);
2299 else {
2300 UsualUnaryConversions(lex);
2301 UsualUnaryConversions(rex);
2302 }
Chris Lattner4b009652007-07-25 00:24:17 +00002303 QualType lType = lex->getType();
2304 QualType rType = rex->getType();
2305
Ted Kremenek486509e2007-10-29 17:13:39 +00002306 // For non-floating point types, check for self-comparisons of the form
2307 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2308 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002309 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002310 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2311 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002312 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002313 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002314 }
2315
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002316 // The result of comparisons is 'bool' in C++, 'int' in C.
2317 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2318
Chris Lattner254f3bc2007-08-26 01:18:55 +00002319 if (isRelational) {
2320 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002321 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002322 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002323 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002324 if (lType->isFloatingType()) {
2325 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002326 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002327 }
2328
Chris Lattner254f3bc2007-08-26 01:18:55 +00002329 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002330 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002331 }
Chris Lattner4b009652007-07-25 00:24:17 +00002332
Chris Lattner22be8422007-08-26 01:10:14 +00002333 bool LHSIsNull = lex->isNullPointerConstant(Context);
2334 bool RHSIsNull = rex->isNullPointerConstant(Context);
2335
Chris Lattner254f3bc2007-08-26 01:18:55 +00002336 // All of the following pointer related warnings are GCC extensions, except
2337 // when handling null pointer constants. One day, we can consider making them
2338 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002339 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002340 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002341 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002342 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002343 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002344
Steve Naroff3b435622007-11-13 14:57:38 +00002345 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002346 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2347 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002348 RCanPointeeTy.getUnqualifiedType()) &&
2349 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002350 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
2351 << lType.getAsString() << rType.getAsString()
2352 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002353 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002354 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002355 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002356 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002357 // Handle block pointer types.
2358 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2359 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2360 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2361
2362 if (!LHSIsNull && !RHSIsNull &&
2363 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002364 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
2365 << lType.getAsString() << rType.getAsString()
2366 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002367 }
2368 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002369 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002370 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002371 // Allow block pointers to be compared with null pointer constants.
2372 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2373 (lType->isPointerType() && rType->isBlockPointerType())) {
2374 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002375 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
2376 << lType.getAsString() << rType.getAsString()
2377 << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002378 }
2379 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002380 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002381 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002382
Steve Naroff936c4362008-06-03 14:04:54 +00002383 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002384 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002385 const PointerType *LPT = lType->getAsPointerType();
2386 const PointerType *RPT = rType->getAsPointerType();
2387 bool LPtrToVoid = LPT ?
2388 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2389 bool RPtrToVoid = RPT ?
2390 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2391
2392 if (!LPtrToVoid && !RPtrToVoid &&
2393 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002394 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
2395 << lType.getAsString() << rType.getAsString()
2396 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002397 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002398 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002399 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002400 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002401 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002402 }
Steve Naroff936c4362008-06-03 14:04:54 +00002403 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2404 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002405 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002406 } else {
2407 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002408 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
2409 << lType.getAsString() << rType.getAsString()
2410 << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002411 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002412 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002413 }
Steve Naroff936c4362008-06-03 14:04:54 +00002414 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002415 }
Steve Naroff936c4362008-06-03 14:04:54 +00002416 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2417 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002418 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002419 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
2420 << lType.getAsString() << rType.getAsString()
2421 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002422 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002423 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002424 }
Steve Naroff936c4362008-06-03 14:04:54 +00002425 if (lType->isIntegerType() &&
2426 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002427 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002428 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
2429 << lType.getAsString() << rType.getAsString()
2430 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002431 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002432 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002433 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002434 // Handle block pointers.
2435 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2436 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002437 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
2438 << lType.getAsString() << rType.getAsString()
2439 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002440 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002441 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002442 }
2443 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2444 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002445 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
2446 << lType.getAsString() << rType.getAsString()
2447 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002448 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002449 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002450 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002451 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002452}
2453
Nate Begemanc5f0f652008-07-14 18:02:46 +00002454/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2455/// operates on extended vector types. Instead of producing an IntTy result,
2456/// like a scalar comparison, a vector comparison produces a vector of integer
2457/// types.
2458QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002459 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002460 bool isRelational) {
2461 // Check to make sure we're operating on vectors of the same type and width,
2462 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002463 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002464 if (vType.isNull())
2465 return vType;
2466
2467 QualType lType = lex->getType();
2468 QualType rType = rex->getType();
2469
2470 // For non-floating point types, check for self-comparisons of the form
2471 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2472 // often indicate logic errors in the program.
2473 if (!lType->isFloatingType()) {
2474 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2475 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2476 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002477 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002478 }
2479
2480 // Check for comparisons of floating point operands using != and ==.
2481 if (!isRelational && lType->isFloatingType()) {
2482 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002483 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002484 }
2485
2486 // Return the type for the comparison, which is the same as vector type for
2487 // integer vectors, or an integer type of identical size and number of
2488 // elements for floating point vectors.
2489 if (lType->isIntegerType())
2490 return lType;
2491
2492 const VectorType *VTy = lType->getAsVectorType();
2493
2494 // FIXME: need to deal with non-32b int / non-64b long long
2495 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2496 if (TypeSize == 32) {
2497 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2498 }
2499 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2500 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2501}
2502
Chris Lattner4b009652007-07-25 00:24:17 +00002503inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002504 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002505{
2506 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002507 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002508
Steve Naroff8f708362007-08-24 19:07:16 +00002509 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002510
2511 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002512 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002513 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002514}
2515
2516inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00002517 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00002518{
2519 UsualUnaryConversions(lex);
2520 UsualUnaryConversions(rex);
2521
Eli Friedmanbea3f842008-05-13 20:16:47 +00002522 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002523 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002524 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002525}
2526
Chris Lattner4c2642c2008-11-18 01:22:49 +00002527/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2528/// emit an error and return true. If so, return false.
2529static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2530 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2531 if (IsLV == Expr::MLV_Valid)
2532 return false;
2533
2534 unsigned Diag = 0;
2535 bool NeedType = false;
2536 switch (IsLV) { // C99 6.5.16p2
2537 default: assert(0 && "Unknown result from isModifiableLvalue!");
2538 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00002539 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002540 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2541 NeedType = true;
2542 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002543 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002544 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2545 NeedType = true;
2546 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00002547 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002548 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2549 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002550 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002551 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2552 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002553 case Expr::MLV_IncompleteType:
2554 case Expr::MLV_IncompleteVoidType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002555 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2556 NeedType = true;
2557 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002558 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002559 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2560 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00002561 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002562 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2563 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002564 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002565
Chris Lattner4c2642c2008-11-18 01:22:49 +00002566 if (NeedType)
Chris Lattner9d2cf082008-11-19 05:27:50 +00002567 S.Diag(Loc, Diag) << E->getType().getAsString() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002568 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00002569 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002570 return true;
2571}
2572
2573
2574
2575// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00002576QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
2577 SourceLocation Loc,
2578 QualType CompoundType) {
2579 // Verify that LHS is a modifiable lvalue, and emit error if not.
2580 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00002581 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00002582
2583 QualType LHSType = LHS->getType();
2584 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00002585
Chris Lattner005ed752008-01-04 18:04:52 +00002586 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002587 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00002588 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002589 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner34c85082008-08-21 18:04:13 +00002590
2591 // If the RHS is a unary plus or minus, check to see if they = and + are
2592 // right next to each other. If so, the user may have typo'd "x =+ 4"
2593 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002594 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00002595 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2596 RHSCheck = ICE->getSubExpr();
2597 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2598 if ((UO->getOpcode() == UnaryOperator::Plus ||
2599 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00002600 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00002601 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002602 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00002603 Diag(Loc, diag::warn_not_compound_assign)
2604 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
2605 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00002606 }
2607 } else {
2608 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00002609 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00002610 }
Chris Lattner005ed752008-01-04 18:04:52 +00002611
Chris Lattner1eafdea2008-11-18 01:30:42 +00002612 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
2613 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00002614 return QualType();
2615
Chris Lattner4b009652007-07-25 00:24:17 +00002616 // C99 6.5.16p3: The type of an assignment expression is the type of the
2617 // left operand unless the left operand has qualified type, in which case
2618 // it is the unqualified version of the type of the left operand.
2619 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2620 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002621 // C++ 5.17p1: the type of the assignment expression is that of its left
2622 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002623 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002624}
2625
Chris Lattner1eafdea2008-11-18 01:30:42 +00002626// C99 6.5.17
2627QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
2628 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00002629
2630 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002631 DefaultFunctionArrayConversion(RHS);
2632 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002633}
2634
2635/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2636/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Chris Lattnere65182c2008-11-21 07:05:48 +00002637QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc) {
2638 QualType ResType = Op->getType();
2639 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002640
Steve Naroffd30e1932007-08-24 17:20:07 +00002641 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattnere65182c2008-11-21 07:05:48 +00002642 if (ResType->isRealType()) {
2643 // OK!
2644 } else if (const PointerType *PT = ResType->getAsPointerType()) {
2645 // C99 6.5.2.4p2, 6.5.6p2
2646 if (PT->getPointeeType()->isObjectType()) {
2647 // Pointer to object is ok!
2648 } else if (PT->getPointeeType()->isVoidType()) {
2649 // Pointer to void is extension.
2650 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
2651 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +00002652 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattnere65182c2008-11-21 07:05:48 +00002653 << ResType.getAsString() << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002654 return QualType();
2655 }
Chris Lattnere65182c2008-11-21 07:05:48 +00002656 } else if (ResType->isComplexType()) {
2657 // C99 does not support ++/-- on complex types, we allow as an extension.
2658 Diag(OpLoc, diag::ext_integer_increment_complex)
2659 << ResType.getAsString() << Op->getSourceRange();
2660 } else {
2661 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
2662 << ResType.getAsString() << Op->getSourceRange();
2663 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002664 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002665 // At this point, we know we have a real, complex or pointer type.
2666 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00002667 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00002668 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00002669 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00002670}
2671
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002672/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002673/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002674/// where the declaration is needed for type checking. We only need to
2675/// handle cases when the expression references a function designator
2676/// or is an lvalue. Here are some examples:
2677/// - &(x) => x
2678/// - &*****f => f for f a function designator.
2679/// - &s.xx => s
2680/// - &s.zz[1].yy -> s, if zz is an array
2681/// - *(x + 1) -> x, if x is an array
2682/// - &"123"[2] -> 0
2683/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002684static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002685 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002686 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002687 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002688 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002689 // Fields cannot be declared with a 'register' storage class.
2690 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002691 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002692 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002693 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002694 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002695 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002696
Douglas Gregord2baafd2008-10-21 16:13:35 +00002697 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002698 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002699 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002700 return 0;
2701 else
2702 return VD;
2703 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002704 case Stmt::UnaryOperatorClass: {
2705 UnaryOperator *UO = cast<UnaryOperator>(E);
2706
2707 switch(UO->getOpcode()) {
2708 case UnaryOperator::Deref: {
2709 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002710 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2711 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2712 if (!VD || VD->getType()->isPointerType())
2713 return 0;
2714 return VD;
2715 }
2716 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002717 }
2718 case UnaryOperator::Real:
2719 case UnaryOperator::Imag:
2720 case UnaryOperator::Extension:
2721 return getPrimaryDecl(UO->getSubExpr());
2722 default:
2723 return 0;
2724 }
2725 }
2726 case Stmt::BinaryOperatorClass: {
2727 BinaryOperator *BO = cast<BinaryOperator>(E);
2728
2729 // Handle cases involving pointer arithmetic. The result of an
2730 // Assign or AddAssign is not an lvalue so they can be ignored.
2731
2732 // (x + n) or (n + x) => x
2733 if (BO->getOpcode() == BinaryOperator::Add) {
2734 if (BO->getLHS()->getType()->isPointerType()) {
2735 return getPrimaryDecl(BO->getLHS());
2736 } else if (BO->getRHS()->getType()->isPointerType()) {
2737 return getPrimaryDecl(BO->getRHS());
2738 }
2739 }
2740
2741 return 0;
2742 }
Chris Lattner4b009652007-07-25 00:24:17 +00002743 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002744 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002745 case Stmt::ImplicitCastExprClass:
2746 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002747 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002748 default:
2749 return 0;
2750 }
2751}
2752
2753/// CheckAddressOfOperand - The operand of & must be either a function
2754/// designator or an lvalue designating an object. If it is an lvalue, the
2755/// object cannot be declared with storage class register or be a bit field.
2756/// Note: The usual conversions are *not* applied to the operand of the &
2757/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00002758/// In C++, the operand might be an overloaded function name, in which case
2759/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00002760QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002761 if (getLangOptions().C99) {
2762 // Implement C99-only parts of addressof rules.
2763 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2764 if (uOp->getOpcode() == UnaryOperator::Deref)
2765 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2766 // (assuming the deref expression is valid).
2767 return uOp->getSubExpr()->getType();
2768 }
2769 // Technically, there should be a check for array subscript
2770 // expressions here, but the result of one is always an lvalue anyway.
2771 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002772 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002773 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002774
2775 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002776 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2777 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00002778 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
2779 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002780 return QualType();
2781 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002782 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2783 if (MemExpr->getMemberDecl()->isBitField()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002784 Diag(OpLoc, diag::err_typecheck_address_of)
2785 << "bit-field" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00002786 return QualType();
2787 }
2788 // Check for Apple extension for accessing vector components.
2789 } else if (isa<ArraySubscriptExpr>(op) &&
2790 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002791 Diag(OpLoc, diag::err_typecheck_address_of)
2792 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00002793 return QualType();
2794 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002795 // We have an lvalue with a decl. Make sure the decl is not declared
2796 // with the register storage-class specifier.
2797 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2798 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002799 Diag(OpLoc, diag::err_typecheck_address_of)
2800 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002801 return QualType();
2802 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00002803 } else if (isa<OverloadedFunctionDecl>(dcl))
2804 return Context.OverloadTy;
2805 else
Chris Lattner4b009652007-07-25 00:24:17 +00002806 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002807 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002808
Chris Lattner4b009652007-07-25 00:24:17 +00002809 // If the operand has type "type", the result has type "pointer to type".
2810 return Context.getPointerType(op->getType());
2811}
2812
2813QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2814 UsualUnaryConversions(op);
2815 QualType qType = op->getType();
2816
Chris Lattner7931f4a2007-07-31 16:53:04 +00002817 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002818 // Note that per both C89 and C99, this is always legal, even
2819 // if ptype is an incomplete type or void.
2820 // It would be possible to warn about dereferencing a
2821 // void pointer, but it's completely well-defined,
2822 // and such a warning is unlikely to catch any mistakes.
2823 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002824 }
Chris Lattner77d52da2008-11-20 06:06:08 +00002825 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
2826 << qType.getAsString() << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002827 return QualType();
2828}
2829
2830static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2831 tok::TokenKind Kind) {
2832 BinaryOperator::Opcode Opc;
2833 switch (Kind) {
2834 default: assert(0 && "Unknown binop!");
2835 case tok::star: Opc = BinaryOperator::Mul; break;
2836 case tok::slash: Opc = BinaryOperator::Div; break;
2837 case tok::percent: Opc = BinaryOperator::Rem; break;
2838 case tok::plus: Opc = BinaryOperator::Add; break;
2839 case tok::minus: Opc = BinaryOperator::Sub; break;
2840 case tok::lessless: Opc = BinaryOperator::Shl; break;
2841 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2842 case tok::lessequal: Opc = BinaryOperator::LE; break;
2843 case tok::less: Opc = BinaryOperator::LT; break;
2844 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2845 case tok::greater: Opc = BinaryOperator::GT; break;
2846 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2847 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2848 case tok::amp: Opc = BinaryOperator::And; break;
2849 case tok::caret: Opc = BinaryOperator::Xor; break;
2850 case tok::pipe: Opc = BinaryOperator::Or; break;
2851 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2852 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2853 case tok::equal: Opc = BinaryOperator::Assign; break;
2854 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2855 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2856 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2857 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2858 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2859 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2860 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2861 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2862 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2863 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2864 case tok::comma: Opc = BinaryOperator::Comma; break;
2865 }
2866 return Opc;
2867}
2868
2869static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2870 tok::TokenKind Kind) {
2871 UnaryOperator::Opcode Opc;
2872 switch (Kind) {
2873 default: assert(0 && "Unknown unary op!");
2874 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2875 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2876 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2877 case tok::star: Opc = UnaryOperator::Deref; break;
2878 case tok::plus: Opc = UnaryOperator::Plus; break;
2879 case tok::minus: Opc = UnaryOperator::Minus; break;
2880 case tok::tilde: Opc = UnaryOperator::Not; break;
2881 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002882 case tok::kw___real: Opc = UnaryOperator::Real; break;
2883 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2884 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2885 }
2886 return Opc;
2887}
2888
Douglas Gregord7f915e2008-11-06 23:29:22 +00002889/// CreateBuiltinBinOp - Creates a new built-in binary operation with
2890/// operator @p Opc at location @c TokLoc. This routine only supports
2891/// built-in operations; ActOnBinOp handles overloaded operators.
2892Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
2893 unsigned Op,
2894 Expr *lhs, Expr *rhs) {
2895 QualType ResultTy; // Result type of the binary operator.
2896 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2897 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
2898
2899 switch (Opc) {
2900 default:
2901 assert(0 && "Unknown binary expr!");
2902 case BinaryOperator::Assign:
2903 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
2904 break;
2905 case BinaryOperator::Mul:
2906 case BinaryOperator::Div:
2907 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
2908 break;
2909 case BinaryOperator::Rem:
2910 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
2911 break;
2912 case BinaryOperator::Add:
2913 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
2914 break;
2915 case BinaryOperator::Sub:
2916 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
2917 break;
2918 case BinaryOperator::Shl:
2919 case BinaryOperator::Shr:
2920 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
2921 break;
2922 case BinaryOperator::LE:
2923 case BinaryOperator::LT:
2924 case BinaryOperator::GE:
2925 case BinaryOperator::GT:
2926 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
2927 break;
2928 case BinaryOperator::EQ:
2929 case BinaryOperator::NE:
2930 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
2931 break;
2932 case BinaryOperator::And:
2933 case BinaryOperator::Xor:
2934 case BinaryOperator::Or:
2935 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
2936 break;
2937 case BinaryOperator::LAnd:
2938 case BinaryOperator::LOr:
2939 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
2940 break;
2941 case BinaryOperator::MulAssign:
2942 case BinaryOperator::DivAssign:
2943 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
2944 if (!CompTy.isNull())
2945 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2946 break;
2947 case BinaryOperator::RemAssign:
2948 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
2949 if (!CompTy.isNull())
2950 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2951 break;
2952 case BinaryOperator::AddAssign:
2953 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
2954 if (!CompTy.isNull())
2955 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2956 break;
2957 case BinaryOperator::SubAssign:
2958 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
2959 if (!CompTy.isNull())
2960 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2961 break;
2962 case BinaryOperator::ShlAssign:
2963 case BinaryOperator::ShrAssign:
2964 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
2965 if (!CompTy.isNull())
2966 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2967 break;
2968 case BinaryOperator::AndAssign:
2969 case BinaryOperator::XorAssign:
2970 case BinaryOperator::OrAssign:
2971 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
2972 if (!CompTy.isNull())
2973 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2974 break;
2975 case BinaryOperator::Comma:
2976 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
2977 break;
2978 }
2979 if (ResultTy.isNull())
2980 return true;
2981 if (CompTy.isNull())
2982 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
2983 else
2984 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
2985}
2986
Chris Lattner4b009652007-07-25 00:24:17 +00002987// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002988Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
2989 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002990 ExprTy *LHS, ExprTy *RHS) {
2991 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2992 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2993
Steve Naroff87d58b42007-09-16 03:34:24 +00002994 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2995 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002996
Douglas Gregord7f915e2008-11-06 23:29:22 +00002997 if (getLangOptions().CPlusPlus &&
2998 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
2999 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003000 // If this is one of the assignment operators, we only perform
3001 // overload resolution if the left-hand side is a class or
3002 // enumeration type (C++ [expr.ass]p3).
3003 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3004 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3005 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3006 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003007
3008 // Determine which overloaded operator we're dealing with.
3009 static const OverloadedOperatorKind OverOps[] = {
3010 OO_Star, OO_Slash, OO_Percent,
3011 OO_Plus, OO_Minus,
3012 OO_LessLess, OO_GreaterGreater,
3013 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3014 OO_EqualEqual, OO_ExclaimEqual,
3015 OO_Amp,
3016 OO_Caret,
3017 OO_Pipe,
3018 OO_AmpAmp,
3019 OO_PipePipe,
3020 OO_Equal, OO_StarEqual,
3021 OO_SlashEqual, OO_PercentEqual,
3022 OO_PlusEqual, OO_MinusEqual,
3023 OO_LessLessEqual, OO_GreaterGreaterEqual,
3024 OO_AmpEqual, OO_CaretEqual,
3025 OO_PipeEqual,
3026 OO_Comma
3027 };
3028 OverloadedOperatorKind OverOp = OverOps[Opc];
3029
Douglas Gregor5ed15042008-11-18 23:14:02 +00003030 // Add the appropriate overloaded operators (C++ [over.match.oper])
3031 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003032 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003033 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003034 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003035
3036 // Perform overload resolution.
3037 OverloadCandidateSet::iterator Best;
3038 switch (BestViableFunction(CandidateSet, Best)) {
3039 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003040 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003041 FunctionDecl *FnDecl = Best->Function;
3042
Douglas Gregor70d26122008-11-12 17:17:38 +00003043 if (FnDecl) {
3044 // We matched an overloaded operator. Build a call to that
3045 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003046
Douglas Gregor70d26122008-11-12 17:17:38 +00003047 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003048 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3049 if (PerformObjectArgumentInitialization(lhs, Method) ||
3050 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3051 "passing"))
3052 return true;
3053 } else {
3054 // Convert the arguments.
3055 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3056 "passing") ||
3057 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3058 "passing"))
3059 return true;
3060 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003061
Douglas Gregor70d26122008-11-12 17:17:38 +00003062 // Determine the result type
3063 QualType ResultTy
3064 = FnDecl->getType()->getAsFunctionType()->getResultType();
3065 ResultTy = ResultTy.getNonReferenceType();
3066
3067 // Build the actual expression node.
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003068 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3069 SourceLocation());
3070 UsualUnaryConversions(FnExpr);
3071
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003072 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregor70d26122008-11-12 17:17:38 +00003073 } else {
3074 // We matched a built-in operator. Convert the arguments, then
3075 // break out so that we will build the appropriate built-in
3076 // operator node.
3077 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
3078 "passing") ||
3079 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
3080 "passing"))
3081 return true;
3082
3083 break;
3084 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003085 }
3086
3087 case OR_No_Viable_Function:
3088 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003089 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003090 break;
3091
3092 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003093 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3094 << BinaryOperator::getOpcodeStr(Opc)
3095 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003096 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3097 return true;
3098 }
3099
Douglas Gregor70d26122008-11-12 17:17:38 +00003100 // Either we found no viable overloaded operator or we matched a
3101 // built-in operator. In either case, fall through to trying to
3102 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003103 }
Chris Lattner4b009652007-07-25 00:24:17 +00003104
Douglas Gregord7f915e2008-11-06 23:29:22 +00003105 // Build a built-in binary operation.
3106 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003107}
3108
3109// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003110Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3111 tok::TokenKind Op, ExprTy *input) {
Chris Lattner4b009652007-07-25 00:24:17 +00003112 Expr *Input = (Expr*)input;
3113 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003114
3115 if (getLangOptions().CPlusPlus &&
3116 (Input->getType()->isRecordType()
3117 || Input->getType()->isEnumeralType())) {
3118 // Determine which overloaded operator we're dealing with.
3119 static const OverloadedOperatorKind OverOps[] = {
3120 OO_None, OO_None,
3121 OO_PlusPlus, OO_MinusMinus,
3122 OO_Amp, OO_Star,
3123 OO_Plus, OO_Minus,
3124 OO_Tilde, OO_Exclaim,
3125 OO_None, OO_None,
3126 OO_None,
3127 OO_None
3128 };
3129 OverloadedOperatorKind OverOp = OverOps[Opc];
3130
3131 // Add the appropriate overloaded operators (C++ [over.match.oper])
3132 // to the candidate set.
3133 OverloadCandidateSet CandidateSet;
3134 if (OverOp != OO_None)
3135 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3136
3137 // Perform overload resolution.
3138 OverloadCandidateSet::iterator Best;
3139 switch (BestViableFunction(CandidateSet, Best)) {
3140 case OR_Success: {
3141 // We found a built-in operator or an overloaded operator.
3142 FunctionDecl *FnDecl = Best->Function;
3143
3144 if (FnDecl) {
3145 // We matched an overloaded operator. Build a call to that
3146 // operator.
3147
3148 // Convert the arguments.
3149 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3150 if (PerformObjectArgumentInitialization(Input, Method))
3151 return true;
3152 } else {
3153 // Convert the arguments.
3154 if (PerformCopyInitialization(Input,
3155 FnDecl->getParamDecl(0)->getType(),
3156 "passing"))
3157 return true;
3158 }
3159
3160 // Determine the result type
3161 QualType ResultTy
3162 = FnDecl->getType()->getAsFunctionType()->getResultType();
3163 ResultTy = ResultTy.getNonReferenceType();
3164
3165 // Build the actual expression node.
3166 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3167 SourceLocation());
3168 UsualUnaryConversions(FnExpr);
3169
3170 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3171 } else {
3172 // We matched a built-in operator. Convert the arguments, then
3173 // break out so that we will build the appropriate built-in
3174 // operator node.
3175 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0],
3176 "passing"))
3177 return true;
3178
3179 break;
3180 }
3181 }
3182
3183 case OR_No_Viable_Function:
3184 // No viable function; fall through to handling this as a
3185 // built-in operator, which will produce an error message for us.
3186 break;
3187
3188 case OR_Ambiguous:
3189 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3190 << UnaryOperator::getOpcodeStr(Opc)
3191 << Input->getSourceRange();
3192 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3193 return true;
3194 }
3195
3196 // Either we found no viable overloaded operator or we matched a
3197 // built-in operator. In either case, fall through to trying to
3198 // build a built-in operation.
3199 }
3200
3201
Chris Lattner4b009652007-07-25 00:24:17 +00003202 QualType resultType;
3203 switch (Opc) {
3204 default:
3205 assert(0 && "Unimplemented unary expr!");
3206 case UnaryOperator::PreInc:
3207 case UnaryOperator::PreDec:
3208 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
3209 break;
3210 case UnaryOperator::AddrOf:
3211 resultType = CheckAddressOfOperand(Input, OpLoc);
3212 break;
3213 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003214 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003215 resultType = CheckIndirectionOperand(Input, OpLoc);
3216 break;
3217 case UnaryOperator::Plus:
3218 case UnaryOperator::Minus:
3219 UsualUnaryConversions(Input);
3220 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003221 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3222 break;
3223 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3224 resultType->isEnumeralType())
3225 break;
3226 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3227 Opc == UnaryOperator::Plus &&
3228 resultType->isPointerType())
3229 break;
3230
Chris Lattner77d52da2008-11-20 06:06:08 +00003231 return Diag(OpLoc, diag::err_typecheck_unary_expr)
3232 << resultType.getAsString();
Chris Lattner4b009652007-07-25 00:24:17 +00003233 case UnaryOperator::Not: // bitwise complement
3234 UsualUnaryConversions(Input);
3235 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003236 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3237 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3238 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003239 Diag(OpLoc, diag::ext_integer_complement_complex)
3240 << resultType.getAsString() << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003241 else if (!resultType->isIntegerType())
Chris Lattner77d52da2008-11-20 06:06:08 +00003242 return Diag(OpLoc, diag::err_typecheck_unary_expr)
3243 << resultType.getAsString() << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003244 break;
3245 case UnaryOperator::LNot: // logical negation
3246 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3247 DefaultFunctionArrayConversion(Input);
3248 resultType = Input->getType();
3249 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattner77d52da2008-11-20 06:06:08 +00003250 return Diag(OpLoc, diag::err_typecheck_unary_expr)
3251 << resultType.getAsString();
Chris Lattner4b009652007-07-25 00:24:17 +00003252 // LNot always has type int. C99 6.5.3.3p5.
3253 resultType = Context.IntTy;
3254 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003255 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003256 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003257 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003258 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003259 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003260 resultType = Input->getType();
3261 break;
3262 }
3263 if (resultType.isNull())
3264 return true;
3265 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3266}
3267
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003268/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3269Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003270 SourceLocation LabLoc,
3271 IdentifierInfo *LabelII) {
3272 // Look up the record for this label identifier.
3273 LabelStmt *&LabelDecl = LabelMap[LabelII];
3274
Daniel Dunbar879788d2008-08-04 16:51:22 +00003275 // If we haven't seen this label yet, create a forward reference. It
3276 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003277 if (LabelDecl == 0)
3278 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3279
3280 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003281 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3282 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003283}
3284
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003285Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003286 SourceLocation RPLoc) { // "({..})"
3287 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3288 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3289 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3290
3291 // FIXME: there are a variety of strange constraints to enforce here, for
3292 // example, it is not possible to goto into a stmt expression apparently.
3293 // More semantic analysis is needed.
3294
3295 // FIXME: the last statement in the compount stmt has its value used. We
3296 // should not warn about it being unused.
3297
3298 // If there are sub stmts in the compound stmt, take the type of the last one
3299 // as the type of the stmtexpr.
3300 QualType Ty = Context.VoidTy;
3301
Chris Lattner200964f2008-07-26 19:51:01 +00003302 if (!Compound->body_empty()) {
3303 Stmt *LastStmt = Compound->body_back();
3304 // If LastStmt is a label, skip down through into the body.
3305 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3306 LastStmt = Label->getSubStmt();
3307
3308 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003309 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003310 }
Chris Lattner4b009652007-07-25 00:24:17 +00003311
3312 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3313}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003314
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003315Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003316 SourceLocation TypeLoc,
3317 TypeTy *argty,
3318 OffsetOfComponent *CompPtr,
3319 unsigned NumComponents,
3320 SourceLocation RPLoc) {
3321 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3322 assert(!ArgTy.isNull() && "Missing type argument!");
3323
3324 // We must have at least one component that refers to the type, and the first
3325 // one is known to be a field designator. Verify that the ArgTy represents
3326 // a struct/union/class.
3327 if (!ArgTy->isRecordType())
Chris Lattner77d52da2008-11-20 06:06:08 +00003328 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy.getAsString();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003329
3330 // Otherwise, create a compound literal expression as the base, and
3331 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003332 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003333
Chris Lattnerb37522e2007-08-31 21:49:13 +00003334 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3335 // GCC extension, diagnose them.
3336 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003337 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3338 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003339
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003340 for (unsigned i = 0; i != NumComponents; ++i) {
3341 const OffsetOfComponent &OC = CompPtr[i];
3342 if (OC.isBrackets) {
3343 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003344 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003345 if (!AT) {
3346 delete Res;
Chris Lattner77d52da2008-11-20 06:06:08 +00003347 return Diag(OC.LocEnd, diag::err_offsetof_array_type)
3348 << Res->getType().getAsString();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003349 }
3350
Chris Lattner2af6a802007-08-30 17:59:59 +00003351 // FIXME: C++: Verify that operator[] isn't overloaded.
3352
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003353 // C99 6.5.2.1p1
3354 Expr *Idx = static_cast<Expr*>(OC.U.E);
3355 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003356 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3357 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003358
3359 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3360 continue;
3361 }
3362
3363 const RecordType *RC = Res->getType()->getAsRecordType();
3364 if (!RC) {
3365 delete Res;
Chris Lattner77d52da2008-11-20 06:06:08 +00003366 return Diag(OC.LocEnd, diag::err_offsetof_record_type)
3367 << Res->getType().getAsString();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003368 }
3369
3370 // Get the decl corresponding to this.
3371 RecordDecl *RD = RC->getDecl();
3372 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
3373 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003374 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3375 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003376
3377 // FIXME: C++: Verify that MemberDecl isn't a static field.
3378 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003379 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3380 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003381 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3382 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003383 }
3384
3385 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3386 BuiltinLoc);
3387}
3388
3389
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003390Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003391 TypeTy *arg1, TypeTy *arg2,
3392 SourceLocation RPLoc) {
3393 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3394 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3395
3396 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3397
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003398 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003399}
3400
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003401Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003402 ExprTy *expr1, ExprTy *expr2,
3403 SourceLocation RPLoc) {
3404 Expr *CondExpr = static_cast<Expr*>(cond);
3405 Expr *LHSExpr = static_cast<Expr*>(expr1);
3406 Expr *RHSExpr = static_cast<Expr*>(expr2);
3407
3408 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3409
3410 // The conditional expression is required to be a constant expression.
3411 llvm::APSInt condEval(32);
3412 SourceLocation ExpLoc;
3413 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003414 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3415 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00003416
3417 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3418 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3419 RHSExpr->getType();
3420 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3421}
3422
Steve Naroff52a81c02008-09-03 18:15:37 +00003423//===----------------------------------------------------------------------===//
3424// Clang Extensions.
3425//===----------------------------------------------------------------------===//
3426
3427/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003428void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003429 // Analyze block parameters.
3430 BlockSemaInfo *BSI = new BlockSemaInfo();
3431
3432 // Add BSI to CurBlock.
3433 BSI->PrevBlockInfo = CurBlock;
3434 CurBlock = BSI;
3435
3436 BSI->ReturnType = 0;
3437 BSI->TheScope = BlockScope;
3438
Steve Naroff52059382008-10-10 01:28:17 +00003439 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
3440 PushDeclContext(BSI->TheDecl);
3441}
3442
3443void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003444 // Analyze arguments to block.
3445 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3446 "Not a function declarator!");
3447 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3448
Steve Naroff52059382008-10-10 01:28:17 +00003449 CurBlock->hasPrototype = FTI.hasPrototype;
3450 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003451
3452 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3453 // no arguments, not a function that takes a single void argument.
3454 if (FTI.hasPrototype &&
3455 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3456 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3457 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3458 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003459 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003460 } else if (FTI.hasPrototype) {
3461 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003462 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3463 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003464 }
Steve Naroff52059382008-10-10 01:28:17 +00003465 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3466
3467 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3468 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3469 // If this has an identifier, add it to the scope stack.
3470 if ((*AI)->getIdentifier())
3471 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003472}
3473
3474/// ActOnBlockError - If there is an error parsing a block, this callback
3475/// is invoked to pop the information about the block from the action impl.
3476void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3477 // Ensure that CurBlock is deleted.
3478 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3479
3480 // Pop off CurBlock, handle nested blocks.
3481 CurBlock = CurBlock->PrevBlockInfo;
3482
3483 // FIXME: Delete the ParmVarDecl objects as well???
3484
3485}
3486
3487/// ActOnBlockStmtExpr - This is called when the body of a block statement
3488/// literal was successfully completed. ^(int x){...}
3489Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3490 Scope *CurScope) {
3491 // Ensure that CurBlock is deleted.
3492 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3493 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3494
Steve Naroff52059382008-10-10 01:28:17 +00003495 PopDeclContext();
3496
Steve Naroff52a81c02008-09-03 18:15:37 +00003497 // Pop off CurBlock, handle nested blocks.
3498 CurBlock = CurBlock->PrevBlockInfo;
3499
3500 QualType RetTy = Context.VoidTy;
3501 if (BSI->ReturnType)
3502 RetTy = QualType(BSI->ReturnType, 0);
3503
3504 llvm::SmallVector<QualType, 8> ArgTypes;
3505 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3506 ArgTypes.push_back(BSI->Params[i]->getType());
3507
3508 QualType BlockTy;
3509 if (!BSI->hasPrototype)
3510 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3511 else
3512 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003513 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003514
3515 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003516
Steve Naroff95029d92008-10-08 18:44:00 +00003517 BSI->TheDecl->setBody(Body.take());
3518 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003519}
3520
Nate Begemanbd881ef2008-01-30 20:50:20 +00003521/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003522/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003523/// The number of arguments has already been validated to match the number of
3524/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003525static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3526 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003527 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003528 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003529 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3530 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003531
3532 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003533 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003534 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003535 return true;
3536}
3537
3538Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3539 SourceLocation *CommaLocs,
3540 SourceLocation BuiltinLoc,
3541 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003542 // __builtin_overload requires at least 2 arguments
3543 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003544 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3545 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003546
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003547 // The first argument is required to be a constant expression. It tells us
3548 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003549 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003550 Expr *NParamsExpr = Args[0];
3551 llvm::APSInt constEval(32);
3552 SourceLocation ExpLoc;
3553 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003554 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3555 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003556
3557 // Verify that the number of parameters is > 0
3558 unsigned NumParams = constEval.getZExtValue();
3559 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003560 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3561 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003562 // Verify that we have at least 1 + NumParams arguments to the builtin.
3563 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003564 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3565 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003566
3567 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003568 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003569 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003570 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3571 // UsualUnaryConversions will convert the function DeclRefExpr into a
3572 // pointer to function.
3573 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003574 const FunctionTypeProto *FnType = 0;
3575 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3576 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003577
3578 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3579 // parameters, and the number of parameters must match the value passed to
3580 // the builtin.
3581 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003582 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
3583 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003584
3585 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003586 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003587 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003588 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003589 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003590 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
3591 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00003592 // Remember our match, and continue processing the remaining arguments
3593 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003594 OE = new OverloadExpr(Args, NumArgs, i,
3595 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003596 BuiltinLoc, RParenLoc);
3597 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003598 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003599 // Return the newly created OverloadExpr node, if we succeded in matching
3600 // exactly one of the candidate functions.
3601 if (OE)
3602 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003603
3604 // If we didn't find a matching function Expr in the __builtin_overload list
3605 // the return an error.
3606 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003607 for (unsigned i = 0; i != NumParams; ++i) {
3608 if (i != 0) typeNames += ", ";
3609 typeNames += Args[i+1]->getType().getAsString();
3610 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003611
Chris Lattner77d52da2008-11-20 06:06:08 +00003612 return Diag(BuiltinLoc, diag::err_overload_no_match)
3613 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003614}
3615
Anders Carlsson36760332007-10-15 20:28:48 +00003616Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3617 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003618 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003619 Expr *E = static_cast<Expr*>(expr);
3620 QualType T = QualType::getFromOpaquePtr(type);
3621
3622 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003623
3624 // Get the va_list type
3625 QualType VaListType = Context.getBuiltinVaListType();
3626 // Deal with implicit array decay; for example, on x86-64,
3627 // va_list is an array, but it's supposed to decay to
3628 // a pointer for va_arg.
3629 if (VaListType->isArrayType())
3630 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003631 // Make sure the input expression also decays appropriately.
3632 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003633
3634 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003635 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00003636 diag::err_first_argument_to_va_arg_not_of_type_va_list)
3637 << E->getType().getAsString() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00003638
3639 // FIXME: Warn if a non-POD type is passed in.
3640
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003641 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003642}
3643
Chris Lattner005ed752008-01-04 18:04:52 +00003644bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3645 SourceLocation Loc,
3646 QualType DstType, QualType SrcType,
3647 Expr *SrcExpr, const char *Flavor) {
3648 // Decode the result (notice that AST's are still created for extensions).
3649 bool isInvalid = false;
3650 unsigned DiagKind;
3651 switch (ConvTy) {
3652 default: assert(0 && "Unknown conversion type");
3653 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003654 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003655 DiagKind = diag::ext_typecheck_convert_pointer_int;
3656 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003657 case IntToPointer:
3658 DiagKind = diag::ext_typecheck_convert_int_pointer;
3659 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003660 case IncompatiblePointer:
3661 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3662 break;
3663 case FunctionVoidPointer:
3664 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3665 break;
3666 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003667 // If the qualifiers lost were because we were applying the
3668 // (deprecated) C++ conversion from a string literal to a char*
3669 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3670 // Ideally, this check would be performed in
3671 // CheckPointerTypesForAssignment. However, that would require a
3672 // bit of refactoring (so that the second argument is an
3673 // expression, rather than a type), which should be done as part
3674 // of a larger effort to fix CheckPointerTypesForAssignment for
3675 // C++ semantics.
3676 if (getLangOptions().CPlusPlus &&
3677 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3678 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003679 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3680 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003681 case IntToBlockPointer:
3682 DiagKind = diag::err_int_to_block_pointer;
3683 break;
3684 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003685 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003686 break;
3687 case BlockVoidPointer:
3688 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3689 break;
Steve Naroff19608432008-10-14 22:18:38 +00003690 case IncompatibleObjCQualifiedId:
3691 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3692 // it can give a more specific diagnostic.
3693 DiagKind = diag::warn_incompatible_qualified_id;
3694 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003695 case Incompatible:
3696 DiagKind = diag::err_typecheck_convert_incompatible;
3697 isInvalid = true;
3698 break;
3699 }
3700
Chris Lattner70b93d82008-11-18 22:52:51 +00003701 Diag(Loc, DiagKind) << DstType.getAsString() << SrcType.getAsString()
3702 << Flavor << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00003703 return isInvalid;
3704}