blob: 61b6f7e577e6200da5edc39716dbeb842f5d0818 [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)
285 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) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000350 // Could be enum-constant, value decl, instance variable, etc.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000351 Decl *D;
352 if (SS && !SS->isEmpty()) {
353 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
354 if (DC == 0)
355 return true;
356 D = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC);
357 } else
358 D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000359
360 // If this reference is in an Objective-C method, then ivar lookup happens as
361 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000362 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000363 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000364 // There are two cases to handle here. 1) scoped lookup could have failed,
365 // in which case we should look for an ivar. 2) scoped lookup could have
366 // found a decl, but that decl is outside the current method (i.e. a global
367 // variable). In these two cases, we do a lookup for an ivar with this
368 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000369 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000370 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattnered94f762008-07-21 04:44:44 +0000371 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000372 // FIXME: This should use a new expr for a direct reference, don't turn
373 // this into Self->ivar, just return a BareIVarExpr or something.
374 IdentifierInfo &II = Context.Idents.get("self");
375 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
376 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
377 static_cast<Expr*>(SelfExpr.Val), true, true);
378 }
379 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000380 // Needed to implement property "super.method" notation.
Daniel Dunbar4837ae72008-08-14 22:04:54 +0000381 if (SD == 0 && &II == SuperID) {
Steve Naroff6f786252008-06-02 23:03:37 +0000382 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000383 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000384 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000385 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000386 }
Chris Lattner4b009652007-07-25 00:24:17 +0000387 if (D == 0) {
388 // Otherwise, this could be an implicitly declared function reference (legal
389 // in C90, extension in C99).
390 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000391 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000392 D = ImplicitlyDefineFunction(Loc, II, S);
393 else {
394 // If this name wasn't predeclared and if this is not a function call,
395 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000396 if (SS && !SS->isEmpty())
397 return Diag(Loc, diag::err_typecheck_no_member,
398 II.getName(), SS->getRange());
399 else
400 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000401 }
402 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000403
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000404 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
405 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
406 if (MD->isStatic())
407 // "invalid use of member 'x' in static member function"
408 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
409 FD->getName());
410 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
411 // "invalid use of nonstatic data member 'x'"
412 return Diag(Loc, diag::err_invalid_non_static_member_use,
413 FD->getName());
414
415 if (FD->isInvalidDecl())
416 return true;
417
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +0000418 // FIXME: Handle 'mutable'.
419 return new DeclRefExpr(FD,
420 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000421 }
422
423 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
424 }
Chris Lattner4b009652007-07-25 00:24:17 +0000425 if (isa<TypedefDecl>(D))
426 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000427 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000428 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000429 if (isa<NamespaceDecl>(D))
430 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000431
Steve Naroffd6163f32008-09-05 22:11:13 +0000432 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000433 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
434 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
435
Steve Naroffd6163f32008-09-05 22:11:13 +0000436 ValueDecl *VD = cast<ValueDecl>(D);
437
438 // check if referencing an identifier with __attribute__((deprecated)).
439 if (VD->getAttr<DeprecatedAttr>())
440 Diag(Loc, diag::warn_deprecated, VD->getName());
441
442 // Only create DeclRefExpr's for valid Decl's.
443 if (VD->isInvalidDecl())
444 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000445
446 // If the identifier reference is inside a block, and it refers to a value
447 // that is outside the block, create a BlockDeclRefExpr instead of a
448 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
449 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000450 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000451 // We do not do this for things like enum constants, global variables, etc,
452 // as they do not get snapshotted.
453 //
454 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000455 // The BlocksAttr indicates the variable is bound by-reference.
456 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000457 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
458 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000459
460 // Variable will be bound by-copy, make it const within the closure.
461 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000462 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
463 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000464 }
465 // If this reference is not in a block or if the referenced variable is
466 // within the block, create a normal DeclRefExpr.
Douglas Gregor3fb675a2008-10-22 04:14:44 +0000467 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Chris Lattner4b009652007-07-25 00:24:17 +0000468}
469
Chris Lattner69909292008-08-10 01:53:14 +0000470Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000471 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000472 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000473
474 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000475 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000476 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
477 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
478 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000479 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000480
481 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000482 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000483 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000484
Chris Lattner7e637512008-01-12 08:14:25 +0000485 // Pre-defined identifiers are of type char[x], where x is the length of the
486 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000487 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000488 if (getCurFunctionDecl())
489 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000490 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000491 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000492
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000493 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000494 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000495 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000496 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000497}
498
Steve Naroff87d58b42007-09-16 03:34:24 +0000499Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000500 llvm::SmallString<16> CharBuffer;
501 CharBuffer.resize(Tok.getLength());
502 const char *ThisTokBegin = &CharBuffer[0];
503 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
504
505 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
506 Tok.getLocation(), PP);
507 if (Literal.hadError())
508 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000509
510 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
511
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000512 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
513 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000514}
515
Steve Naroff87d58b42007-09-16 03:34:24 +0000516Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000517 // fast path for a single digit (which is quite common). A single digit
518 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
519 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000520 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000521
Chris Lattner8cd0e932008-03-05 18:54:05 +0000522 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000523 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000524 Context.IntTy,
525 Tok.getLocation()));
526 }
527 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000528 // Add padding so that NumericLiteralParser can overread by one character.
529 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000530 const char *ThisTokBegin = &IntegerBuffer[0];
531
532 // Get the spelling of the token, which eliminates trigraphs, etc.
533 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000534
Chris Lattner4b009652007-07-25 00:24:17 +0000535 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
536 Tok.getLocation(), PP);
537 if (Literal.hadError)
538 return ExprResult(true);
539
Chris Lattner1de66eb2007-08-26 03:42:43 +0000540 Expr *Res;
541
542 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000543 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000544 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000545 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000546 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000547 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000548 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000549 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000550
551 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
552
Ted Kremenekddedbe22007-11-29 00:56:49 +0000553 // isExact will be set by GetFloatValue().
554 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000555 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000556 Ty, Tok.getLocation());
557
Chris Lattner1de66eb2007-08-26 03:42:43 +0000558 } else if (!Literal.isIntegerLiteral()) {
559 return ExprResult(true);
560 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000561 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000562
Neil Booth7421e9c2007-08-29 22:00:19 +0000563 // long long is a C99 feature.
564 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000565 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000566 Diag(Tok.getLocation(), diag::ext_longlong);
567
Chris Lattner4b009652007-07-25 00:24:17 +0000568 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000569 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000570
571 if (Literal.GetIntegerValue(ResultVal)) {
572 // If this value didn't fit into uintmax_t, warn and force to ull.
573 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000574 Ty = Context.UnsignedLongLongTy;
575 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000576 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000577 } else {
578 // If this value fits into a ULL, try to figure out what else it fits into
579 // according to the rules of C99 6.4.4.1p5.
580
581 // Octal, Hexadecimal, and integers with a U suffix are allowed to
582 // be an unsigned int.
583 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
584
585 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000586 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000587 if (!Literal.isLong && !Literal.isLongLong) {
588 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000589 unsigned IntSize = Context.Target.getIntWidth();
590
Chris Lattner4b009652007-07-25 00:24:17 +0000591 // Does it fit in a unsigned int?
592 if (ResultVal.isIntN(IntSize)) {
593 // Does it fit in a signed int?
594 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000595 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000596 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000597 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000598 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000599 }
Chris Lattner4b009652007-07-25 00:24:17 +0000600 }
601
602 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000603 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000604 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000605
606 // Does it fit in a unsigned long?
607 if (ResultVal.isIntN(LongSize)) {
608 // Does it fit in a signed long?
609 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000610 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000611 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000612 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000613 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000614 }
Chris Lattner4b009652007-07-25 00:24:17 +0000615 }
616
617 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000618 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000619 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000620
621 // Does it fit in a unsigned long long?
622 if (ResultVal.isIntN(LongLongSize)) {
623 // Does it fit in a signed long long?
624 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000625 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000626 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000627 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000628 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000629 }
630 }
631
632 // If we still couldn't decide a type, we probably have something that
633 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000634 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000635 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000636 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000637 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000638 }
Chris Lattnere4068872008-05-09 05:59:00 +0000639
640 if (ResultVal.getBitWidth() != Width)
641 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000642 }
643
Chris Lattner48d7f382008-04-02 04:24:33 +0000644 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000645 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000646
647 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
648 if (Literal.isImaginary)
649 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
650
651 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000652}
653
Steve Naroff87d58b42007-09-16 03:34:24 +0000654Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000655 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000656 Expr *E = (Expr *)Val;
657 assert((E != 0) && "ActOnParenExpr() missing expr");
658 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000659}
660
661/// The UsualUnaryConversions() function is *not* called by this routine.
662/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000663bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
664 SourceLocation OpLoc,
665 const SourceRange &ExprRange,
666 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000667 // C99 6.5.3.4p1:
668 if (isa<FunctionType>(exprType) && isSizeof)
669 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000670 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000671 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000672 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
673 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000674 else if (exprType->isIncompleteType()) {
675 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
676 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000677 exprType.getAsString(), ExprRange);
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000678 return true; // error
Chris Lattner4b009652007-07-25 00:24:17 +0000679 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000680
681 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000682}
683
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000684/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
685/// the same for @c alignof and @c __alignof
686/// Note that the ArgRange is invalid if isType is false.
687Action::ExprResult
688Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
689 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +0000690 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000691 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000692
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000693 QualType ArgTy;
694 SourceRange Range;
695 if (isType) {
696 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
697 Range = ArgRange;
698 } else {
699 // Get the end location.
700 Expr *ArgEx = (Expr *)TyOrEx;
701 Range = ArgEx->getSourceRange();
702 ArgTy = ArgEx->getType();
703 }
704
705 // Verify that the operand is valid.
706 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +0000707 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000708
709 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
710 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
711 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +0000712}
713
Chris Lattner5110ad52007-08-24 21:41:10 +0000714QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000715 DefaultFunctionArrayConversion(V);
716
Chris Lattnera16e42d2007-08-26 05:39:26 +0000717 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000718 if (const ComplexType *CT = V->getType()->getAsComplexType())
719 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000720
721 // Otherwise they pass through real integer and floating point types here.
722 if (V->getType()->isArithmeticType())
723 return V->getType();
724
725 // Reject anything else.
726 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
727 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000728}
729
730
Chris Lattner4b009652007-07-25 00:24:17 +0000731
Steve Naroff87d58b42007-09-16 03:34:24 +0000732Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000733 tok::TokenKind Kind,
734 ExprTy *Input) {
735 UnaryOperator::Opcode Opc;
736 switch (Kind) {
737 default: assert(0 && "Unknown unary op!");
738 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
739 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
740 }
741 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
742 if (result.isNull())
743 return true;
744 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
745}
746
747Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000748ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000749 ExprTy *Idx, SourceLocation RLoc) {
750 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
751
752 // Perform default conversions.
753 DefaultFunctionArrayConversion(LHSExp);
754 DefaultFunctionArrayConversion(RHSExp);
755
756 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
757
758 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000759 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000760 // in the subscript position. As a result, we need to derive the array base
761 // and index from the expression types.
762 Expr *BaseExpr, *IndexExpr;
763 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000764 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000765 BaseExpr = LHSExp;
766 IndexExpr = RHSExp;
767 // FIXME: need to deal with const...
768 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000769 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000770 // Handle the uncommon case of "123[Ptr]".
771 BaseExpr = RHSExp;
772 IndexExpr = LHSExp;
773 // FIXME: need to deal with const...
774 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000775 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
776 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000777 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000778
779 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000780 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
781 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000782 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000783 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000784 // FIXME: need to deal with const...
785 ResultType = VTy->getElementType();
786 } else {
787 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
788 RHSExp->getSourceRange());
789 }
790 // C99 6.5.2.1p1
791 if (!IndexExpr->getType()->isIntegerType())
792 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
793 IndexExpr->getSourceRange());
794
795 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
796 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000797 // void (*)(int)) and pointers to incomplete types. Functions are not
798 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000799 if (!ResultType->isObjectType())
800 return Diag(BaseExpr->getLocStart(),
801 diag::err_typecheck_subscript_not_object,
802 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
803
804 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
805}
806
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000807QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000808CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000809 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000810 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000811
812 // This flag determines whether or not the component is to be treated as a
813 // special name, or a regular GLSL-style component access.
814 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000815
816 // The vector accessor can't exceed the number of elements.
817 const char *compStr = CompName.getName();
818 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000819 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000820 baseType.getAsString(), SourceRange(CompLoc));
821 return QualType();
822 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000823
824 // Check that we've found one of the special components, or that the component
825 // names must come from the same set.
826 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
827 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
828 SpecialComponent = true;
829 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000830 do
831 compStr++;
832 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
833 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
834 do
835 compStr++;
836 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
837 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
838 do
839 compStr++;
840 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
841 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000842
Nate Begemanc8e51f82008-05-09 06:41:27 +0000843 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000844 // We didn't get to the end of the string. This means the component names
845 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000846 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000847 std::string(compStr,compStr+1), SourceRange(CompLoc));
848 return QualType();
849 }
850 // Each component accessor can't exceed the vector type.
851 compStr = CompName.getName();
852 while (*compStr) {
853 if (vecType->isAccessorWithinNumElements(*compStr))
854 compStr++;
855 else
856 break;
857 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000858 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000859 // We didn't get to the end of the string. This means a component accessor
860 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000861 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000862 baseType.getAsString(), SourceRange(CompLoc));
863 return QualType();
864 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000865
866 // If we have a special component name, verify that the current vector length
867 // is an even number, since all special component names return exactly half
868 // the elements.
869 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Daniel Dunbar45a91802008-09-30 17:22:47 +0000870 Diag(OpLoc, diag::err_ext_vector_component_requires_even,
871 baseType.getAsString(), SourceRange(CompLoc));
Nate Begemanc8e51f82008-05-09 06:41:27 +0000872 return QualType();
873 }
874
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000875 // The component accessor looks fine - now we need to compute the actual type.
876 // The vector type is implied by the component accessor. For example,
877 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000878 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
879 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
880 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000881 if (CompSize == 1)
882 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000883
Nate Begemanaf6ed502008-04-18 23:10:10 +0000884 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000885 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000886 // diagostics look bad. We want extended vector types to appear built-in.
887 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
888 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
889 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000890 }
891 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000892}
893
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000894/// constructSetterName - Return the setter name for the given
895/// identifier, i.e. "set" + Name where the initial character of Name
896/// has been capitalized.
897// FIXME: Merge with same routine in Parser. But where should this
898// live?
899static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
900 const IdentifierInfo *Name) {
901 unsigned N = Name->getLength();
902 char *SelectorName = new char[3 + N];
903 memcpy(SelectorName, "set", 3);
904 memcpy(&SelectorName[3], Name->getName(), N);
905 SelectorName[3] = toupper(SelectorName[3]);
906
907 IdentifierInfo *Setter =
908 &Idents.get(SelectorName, &SelectorName[3 + N]);
909 delete[] SelectorName;
910 return Setter;
911}
912
Chris Lattner4b009652007-07-25 00:24:17 +0000913Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000914ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000915 tok::TokenKind OpKind, SourceLocation MemberLoc,
916 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000917 Expr *BaseExpr = static_cast<Expr *>(Base);
918 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000919
920 // Perform default conversions.
921 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000922
Steve Naroff2cb66382007-07-26 03:11:44 +0000923 QualType BaseType = BaseExpr->getType();
924 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000925
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000926 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
927 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000928 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000929 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000930 BaseType = PT->getPointeeType();
931 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000932 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
933 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000934 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000935
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000936 // Handle field access to simple records. This also handles access to fields
937 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000938 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000939 RecordDecl *RDecl = RTy->getDecl();
940 if (RTy->isIncompleteType())
941 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
942 BaseExpr->getSourceRange());
943 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000944 FieldDecl *MemberDecl = RDecl->getMember(&Member);
945 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000946 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
947 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000948
949 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000950 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000951 QualType MemberType = MemberDecl->getType();
952 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000953 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000954 if (CXXFieldDecl *CXXMember = dyn_cast<CXXFieldDecl>(MemberDecl)) {
955 if (CXXMember->isMutable())
956 combinedQualifiers &= ~QualType::Const;
957 }
Eli Friedman76b49832008-02-06 22:48:16 +0000958 MemberType = MemberType.getQualifiedType(combinedQualifiers);
959
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000960 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000961 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000962 }
963
Chris Lattnere9d71612008-07-21 04:59:05 +0000964 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
965 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000966 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
967 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000968 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000969 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000970 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000971 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000972 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000973 }
974
Chris Lattnere9d71612008-07-21 04:59:05 +0000975 // Handle Objective-C property access, which is "Obj.property" where Obj is a
976 // pointer to a (potentially qualified) interface type.
977 const PointerType *PTy;
978 const ObjCInterfaceType *IFTy;
979 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
980 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
981 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +0000982
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000983 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +0000984 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
985 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
986
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000987 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000988 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
989 E = IFTy->qual_end(); I != E; ++I)
990 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
991 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000992
993 // If that failed, look for an "implicit" property by seeing if the nullary
994 // selector is implemented.
995
996 // FIXME: The logic for looking up nullary and unary selectors should be
997 // shared with the code in ActOnInstanceMessage.
998
999 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1000 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1001
1002 // If this reference is in an @implementation, check for 'private' methods.
1003 if (!Getter)
1004 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1005 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1006 if (ObjCImplementationDecl *ImpDecl =
1007 ObjCImplementations[ClassDecl->getIdentifier()])
1008 Getter = ImpDecl->getInstanceMethod(Sel);
1009
Steve Naroff04151f32008-10-22 19:16:27 +00001010 // Look through local category implementations associated with the class.
1011 if (!Getter) {
1012 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1013 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1014 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1015 }
1016 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001017 if (Getter) {
1018 // If we found a getter then this may be a valid dot-reference, we
1019 // need to also look for the matching setter.
1020 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1021 &Member);
1022 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1023 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1024
1025 if (!Setter) {
1026 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1027 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1028 if (ObjCImplementationDecl *ImpDecl =
1029 ObjCImplementations[ClassDecl->getIdentifier()])
1030 Setter = ImpDecl->getInstanceMethod(SetterSel);
1031 }
1032
1033 // FIXME: There are some issues here. First, we are not
1034 // diagnosing accesses to read-only properties because we do not
1035 // know if this is a getter or setter yet. Second, we are
1036 // checking that the type of the setter matches the type we
1037 // expect.
1038 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1039 MemberLoc, BaseExpr);
1040 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001041 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001042 // Handle properties on qualified "id" protocols.
1043 const ObjCQualifiedIdType *QIdTy;
1044 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1045 // Check protocols on qualified interfaces.
1046 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1047 E = QIdTy->qual_end(); I != E; ++I)
1048 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1049 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1050 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001051 // Handle 'field access' to vectors, such as 'V.xx'.
1052 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1053 // Component access limited to variables (reject vec4.rg.g).
1054 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1055 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +00001056 return Diag(MemberLoc, diag::err_ext_vector_component_access,
1057 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001058 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1059 if (ret.isNull())
1060 return true;
1061 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1062 }
1063
Chris Lattner7d5a8762008-07-21 05:35:34 +00001064 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1065 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001066}
1067
Steve Naroff87d58b42007-09-16 03:34:24 +00001068/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001069/// This provides the location of the left/right parens and a list of comma
1070/// locations.
1071Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001072ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001073 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001074 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1075 Expr *Fn = static_cast<Expr *>(fn);
1076 Expr **Args = reinterpret_cast<Expr**>(args);
1077 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001078 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001079 OverloadedFunctionDecl *Ovl = NULL;
1080
1081 // If we're directly calling a function or a set of overloaded
1082 // functions, get the appropriate declaration.
1083 {
1084 DeclRefExpr *DRExpr = NULL;
1085 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1086 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1087 else
1088 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1089
1090 if (DRExpr) {
1091 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1092 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1093 }
1094 }
1095
1096 // If we have a set of overloaded functions, perform overload
1097 // resolution to pick the function.
1098 if (Ovl) {
1099 OverloadCandidateSet CandidateSet;
1100 OverloadCandidateSet::iterator Best;
1101 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
1102 switch (BestViableFunction(CandidateSet, Best)) {
1103 case OR_Success:
1104 {
1105 // Success! Let the remainder of this function build a call to
1106 // the function selected by overload resolution.
1107 FDecl = Best->Function;
1108 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1109 Fn->getSourceRange().getBegin());
1110 delete Fn;
1111 Fn = NewFn;
1112 }
1113 break;
1114
1115 case OR_No_Viable_Function:
1116 if (CandidateSet.empty())
1117 Diag(Fn->getSourceRange().getBegin(),
1118 diag::err_ovl_no_viable_function_in_call, Ovl->getName(),
1119 Fn->getSourceRange());
1120 else {
1121 Diag(Fn->getSourceRange().getBegin(),
1122 diag::err_ovl_no_viable_function_in_call_with_cands,
1123 Ovl->getName(), Fn->getSourceRange());
1124 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1125 }
1126 return true;
1127
1128 case OR_Ambiguous:
1129 Diag(Fn->getSourceRange().getBegin(),
1130 diag::err_ovl_ambiguous_call, Ovl->getName(),
1131 Fn->getSourceRange());
1132 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1133 return true;
1134 }
1135 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001136
1137 // Promote the function operand.
1138 UsualUnaryConversions(Fn);
1139
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001140 // Make the call expr early, before semantic checks. This guarantees cleanup
1141 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001142 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001143 Context.BoolTy, RParenLoc));
Steve Naroffd6163f32008-09-05 22:11:13 +00001144 const FunctionType *FuncT;
1145 if (!Fn->getType()->isBlockPointerType()) {
1146 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1147 // have type pointer to function".
1148 const PointerType *PT = Fn->getType()->getAsPointerType();
1149 if (PT == 0)
1150 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1151 Fn->getSourceRange());
1152 FuncT = PT->getPointeeType()->getAsFunctionType();
1153 } else { // This is a block call.
1154 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1155 getAsFunctionType();
1156 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001157 if (FuncT == 0)
Chris Lattner61000b12008-08-14 04:33:24 +00001158 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1159 Fn->getSourceRange());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001160
1161 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001162 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001163
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001164 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001165 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1166 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001167 unsigned NumArgsInProto = Proto->getNumArgs();
1168 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001169
Chris Lattner3e254fb2008-04-08 04:40:51 +00001170 // If too few arguments are available (and we don't have default
1171 // arguments for the remaining parameters), don't make the call.
1172 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +00001173 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001174 // Use default arguments for missing arguments
1175 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +00001176 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001177 } else
Steve Naroffd6163f32008-09-05 22:11:13 +00001178 return Diag(RParenLoc,
1179 !Fn->getType()->isBlockPointerType()
1180 ? diag::err_typecheck_call_too_few_args
1181 : diag::err_typecheck_block_too_few_args,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001182 Fn->getSourceRange());
1183 }
1184
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001185 // If too many are passed and not variadic, error on the extras and drop
1186 // them.
1187 if (NumArgs > NumArgsInProto) {
1188 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001189 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffd6163f32008-09-05 22:11:13 +00001190 !Fn->getType()->isBlockPointerType()
1191 ? diag::err_typecheck_call_too_many_args
1192 : diag::err_typecheck_block_too_many_args,
1193 Fn->getSourceRange(),
Chris Lattner4b009652007-07-25 00:24:17 +00001194 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001195 Args[NumArgs-1]->getLocEnd()));
1196 // This deletes the extra arguments.
1197 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001198 }
1199 NumArgsToCheck = NumArgsInProto;
1200 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001201
Chris Lattner4b009652007-07-25 00:24:17 +00001202 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001203 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001204 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001205
1206 Expr *Arg;
1207 if (i < NumArgs)
1208 Arg = Args[i];
1209 else
1210 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001211 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001212
Douglas Gregor81c29152008-10-29 00:13:59 +00001213 // Pass the argument.
1214 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner005ed752008-01-04 18:04:52 +00001215 return true;
Douglas Gregor81c29152008-10-29 00:13:59 +00001216
1217 TheCall->setArg(i, Arg);
Chris Lattner4b009652007-07-25 00:24:17 +00001218 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001219
1220 // If this is a variadic call, handle args passed through "...".
1221 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001222 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001223 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1224 Expr *Arg = Args[i];
1225 DefaultArgumentPromotion(Arg);
1226 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001227 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001228 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001229 } else {
1230 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1231
Steve Naroffdb65e052007-08-28 23:30:39 +00001232 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001233 for (unsigned i = 0; i != NumArgs; i++) {
1234 Expr *Arg = Args[i];
1235 DefaultArgumentPromotion(Arg);
1236 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001237 }
Chris Lattner4b009652007-07-25 00:24:17 +00001238 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001239
Chris Lattner2e64c072007-08-10 20:18:51 +00001240 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001241 if (FDecl)
1242 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001243
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001244 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001245}
1246
1247Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001248ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001249 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001250 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001251 QualType literalType = QualType::getFromOpaquePtr(Ty);
1252 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001253 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001254 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001255
Eli Friedman8c2173d2008-05-20 05:22:08 +00001256 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001257 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001258 return Diag(LParenLoc,
1259 diag::err_variable_object_no_init,
1260 SourceRange(LParenLoc,
1261 literalExpr->getSourceRange().getEnd()));
1262 } else if (literalType->isIncompleteType()) {
1263 return Diag(LParenLoc,
1264 diag::err_typecheck_decl_incomplete_type,
1265 literalType.getAsString(),
1266 SourceRange(LParenLoc,
1267 literalExpr->getSourceRange().getEnd()));
1268 }
1269
Douglas Gregor6428e762008-11-05 15:29:30 +00001270 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
1271 "temporary"))
Steve Naroff92590f92008-01-09 20:58:06 +00001272 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001273
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001274 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001275 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001276 if (CheckForConstantInitializer(literalExpr, literalType))
1277 return true;
1278 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001279 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1280 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001281}
1282
1283Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001284ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001285 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001286 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001287 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001288
Steve Naroff0acc9c92007-09-15 18:49:24 +00001289 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001290 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001291
Chris Lattner71ca8c82008-10-26 23:43:26 +00001292 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1293 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001294 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1295 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001296}
1297
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001298/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001299bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001300 UsualUnaryConversions(castExpr);
1301
1302 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1303 // type needs to be scalar.
1304 if (castType->isVoidType()) {
1305 // Cast to void allows any expr type.
1306 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1307 // GCC struct/union extension: allow cast to self.
1308 if (Context.getCanonicalType(castType) !=
1309 Context.getCanonicalType(castExpr->getType()) ||
1310 (!castType->isStructureType() && !castType->isUnionType())) {
1311 // Reject any other conversions to non-scalar types.
1312 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1313 castType.getAsString(), castExpr->getSourceRange());
1314 }
1315
1316 // accept this, but emit an ext-warn.
1317 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1318 castType.getAsString(), castExpr->getSourceRange());
1319 } else if (!castExpr->getType()->isScalarType() &&
1320 !castExpr->getType()->isVectorType()) {
1321 return Diag(castExpr->getLocStart(),
1322 diag::err_typecheck_expect_scalar_operand,
1323 castExpr->getType().getAsString(),castExpr->getSourceRange());
1324 } else if (castExpr->getType()->isVectorType()) {
1325 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1326 return true;
1327 } else if (castType->isVectorType()) {
1328 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1329 return true;
1330 }
1331 return false;
1332}
1333
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001334bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001335 assert(VectorTy->isVectorType() && "Not a vector type!");
1336
1337 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001338 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001339 return Diag(R.getBegin(),
1340 Ty->isVectorType() ?
1341 diag::err_invalid_conversion_between_vectors :
1342 diag::err_invalid_conversion_between_vector_and_integer,
1343 VectorTy.getAsString().c_str(),
1344 Ty.getAsString().c_str(), R);
1345 } else
1346 return Diag(R.getBegin(),
1347 diag::err_invalid_conversion_between_vector_and_scalar,
1348 VectorTy.getAsString().c_str(),
1349 Ty.getAsString().c_str(), R);
1350
1351 return false;
1352}
1353
Chris Lattner4b009652007-07-25 00:24:17 +00001354Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001355ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001356 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001357 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001358
1359 Expr *castExpr = static_cast<Expr*>(Op);
1360 QualType castType = QualType::getFromOpaquePtr(Ty);
1361
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001362 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1363 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00001364 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001365}
1366
Chris Lattner98a425c2007-11-26 01:40:58 +00001367/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1368/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001369inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1370 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1371 UsualUnaryConversions(cond);
1372 UsualUnaryConversions(lex);
1373 UsualUnaryConversions(rex);
1374 QualType condT = cond->getType();
1375 QualType lexT = lex->getType();
1376 QualType rexT = rex->getType();
1377
1378 // first, check the condition.
1379 if (!condT->isScalarType()) { // C99 6.5.15p2
1380 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1381 condT.getAsString());
1382 return QualType();
1383 }
Chris Lattner992ae932008-01-06 22:42:25 +00001384
1385 // Now check the two expressions.
1386
1387 // If both operands have arithmetic type, do the usual arithmetic conversions
1388 // to find a common type: C99 6.5.15p3,5.
1389 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001390 UsualArithmeticConversions(lex, rex);
1391 return lex->getType();
1392 }
Chris Lattner992ae932008-01-06 22:42:25 +00001393
1394 // If both operands are the same structure or union type, the result is that
1395 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001396 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001397 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001398 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001399 // "If both the operands have structure or union type, the result has
1400 // that type." This implies that CV qualifiers are dropped.
1401 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001402 }
Chris Lattner992ae932008-01-06 22:42:25 +00001403
1404 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001405 // The following || allows only one side to be void (a GCC-ism).
1406 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001407 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001408 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1409 rex->getSourceRange());
1410 if (!rexT->isVoidType())
1411 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001412 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001413 ImpCastExprToType(lex, Context.VoidTy);
1414 ImpCastExprToType(rex, Context.VoidTy);
1415 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001416 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001417 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1418 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001419 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1420 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001421 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001422 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001423 return lexT;
1424 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001425 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1426 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001427 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001428 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001429 return rexT;
1430 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001431 // Handle the case where both operands are pointers before we handle null
1432 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001433 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1434 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1435 // get the "pointed to" types
1436 QualType lhptee = LHSPT->getPointeeType();
1437 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001438
Chris Lattner71225142007-07-31 21:27:01 +00001439 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1440 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001441 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001442 // Figure out necessary qualifiers (C99 6.5.15p6)
1443 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001444 QualType destType = Context.getPointerType(destPointee);
1445 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1446 ImpCastExprToType(rex, destType); // promote to void*
1447 return destType;
1448 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001449 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001450 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001451 QualType destType = Context.getPointerType(destPointee);
1452 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1453 ImpCastExprToType(rex, destType); // promote to void*
1454 return destType;
1455 }
Chris Lattner4b009652007-07-25 00:24:17 +00001456
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001457 QualType compositeType = lexT;
1458
1459 // If either type is an Objective-C object type then check
1460 // compatibility according to Objective-C.
1461 if (Context.isObjCObjectPointerType(lexT) ||
1462 Context.isObjCObjectPointerType(rexT)) {
1463 // If both operands are interfaces and either operand can be
1464 // assigned to the other, use that type as the composite
1465 // type. This allows
1466 // xxx ? (A*) a : (B*) b
1467 // where B is a subclass of A.
1468 //
1469 // Additionally, as for assignment, if either type is 'id'
1470 // allow silent coercion. Finally, if the types are
1471 // incompatible then make sure to use 'id' as the composite
1472 // type so the result is acceptable for sending messages to.
1473
1474 // FIXME: This code should not be localized to here. Also this
1475 // should use a compatible check instead of abusing the
1476 // canAssignObjCInterfaces code.
1477 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1478 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1479 if (LHSIface && RHSIface &&
1480 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1481 compositeType = lexT;
1482 } else if (LHSIface && RHSIface &&
1483 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1484 compositeType = rexT;
1485 } else if (Context.isObjCIdType(lhptee) ||
1486 Context.isObjCIdType(rhptee)) {
1487 // FIXME: This code looks wrong, because isObjCIdType checks
1488 // the struct but getObjCIdType returns the pointer to
1489 // struct. This is horrible and should be fixed.
1490 compositeType = Context.getObjCIdType();
1491 } else {
1492 QualType incompatTy = Context.getObjCIdType();
1493 ImpCastExprToType(lex, incompatTy);
1494 ImpCastExprToType(rex, incompatTy);
1495 return incompatTy;
1496 }
1497 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1498 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001499 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001500 lexT.getAsString(), rexT.getAsString(),
1501 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001502 // In this situation, we assume void* type. No especially good
1503 // reason, but this is what gcc does, and we do have to pick
1504 // to get a consistent AST.
1505 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001506 ImpCastExprToType(lex, incompatTy);
1507 ImpCastExprToType(rex, incompatTy);
1508 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001509 }
1510 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001511 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1512 // differently qualified versions of compatible types, the result type is
1513 // a pointer to an appropriately qualified version of the *composite*
1514 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001515 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001516 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001517 ImpCastExprToType(lex, compositeType);
1518 ImpCastExprToType(rex, compositeType);
1519 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001520 }
Chris Lattner4b009652007-07-25 00:24:17 +00001521 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001522 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1523 // evaluates to "struct objc_object *" (and is handled above when comparing
1524 // id with statically typed objects).
1525 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1526 // GCC allows qualified id and any Objective-C type to devolve to
1527 // id. Currently localizing to here until clear this should be
1528 // part of ObjCQualifiedIdTypesAreCompatible.
1529 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1530 (lexT->isObjCQualifiedIdType() &&
1531 Context.isObjCObjectPointerType(rexT)) ||
1532 (rexT->isObjCQualifiedIdType() &&
1533 Context.isObjCObjectPointerType(lexT))) {
1534 // FIXME: This is not the correct composite type. This only
1535 // happens to work because id can more or less be used anywhere,
1536 // however this may change the type of method sends.
1537 // FIXME: gcc adds some type-checking of the arguments and emits
1538 // (confusing) incompatible comparison warnings in some
1539 // cases. Investigate.
1540 QualType compositeType = Context.getObjCIdType();
1541 ImpCastExprToType(lex, compositeType);
1542 ImpCastExprToType(rex, compositeType);
1543 return compositeType;
1544 }
1545 }
1546
Steve Naroff3eac7692008-09-10 19:17:48 +00001547 // Selection between block pointer types is ok as long as they are the same.
1548 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1549 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1550 return lexT;
1551
Chris Lattner992ae932008-01-06 22:42:25 +00001552 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001553 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1554 lexT.getAsString(), rexT.getAsString(),
1555 lex->getSourceRange(), rex->getSourceRange());
1556 return QualType();
1557}
1558
Steve Naroff87d58b42007-09-16 03:34:24 +00001559/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001560/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001561Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001562 SourceLocation ColonLoc,
1563 ExprTy *Cond, ExprTy *LHS,
1564 ExprTy *RHS) {
1565 Expr *CondExpr = (Expr *) Cond;
1566 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001567
1568 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1569 // was the condition.
1570 bool isLHSNull = LHSExpr == 0;
1571 if (isLHSNull)
1572 LHSExpr = CondExpr;
1573
Chris Lattner4b009652007-07-25 00:24:17 +00001574 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1575 RHSExpr, QuestionLoc);
1576 if (result.isNull())
1577 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001578 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1579 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001580}
1581
Chris Lattner4b009652007-07-25 00:24:17 +00001582
1583// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1584// being closely modeled after the C99 spec:-). The odd characteristic of this
1585// routine is it effectively iqnores the qualifiers on the top level pointee.
1586// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1587// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001588Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001589Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1590 QualType lhptee, rhptee;
1591
1592 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001593 lhptee = lhsType->getAsPointerType()->getPointeeType();
1594 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001595
1596 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001597 lhptee = Context.getCanonicalType(lhptee);
1598 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001599
Chris Lattner005ed752008-01-04 18:04:52 +00001600 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001601
1602 // C99 6.5.16.1p1: This following citation is common to constraints
1603 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1604 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001605 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001606 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001607 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001608
1609 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1610 // incomplete type and the other is a pointer to a qualified or unqualified
1611 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001612 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001613 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001614 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001615
1616 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001617 assert(rhptee->isFunctionType());
1618 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001619 }
1620
1621 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001622 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001623 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001624
1625 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001626 assert(lhptee->isFunctionType());
1627 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001628 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001629
1630 // Check for ObjC interfaces
1631 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1632 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1633 if (LHSIface && RHSIface &&
1634 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1635 return ConvTy;
1636
1637 // ID acts sort of like void* for ObjC interfaces
1638 if (LHSIface && Context.isObjCIdType(rhptee))
1639 return ConvTy;
1640 if (RHSIface && Context.isObjCIdType(lhptee))
1641 return ConvTy;
1642
Chris Lattner4b009652007-07-25 00:24:17 +00001643 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1644 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001645 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1646 rhptee.getUnqualifiedType()))
1647 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001648 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001649}
1650
Steve Naroff3454b6c2008-09-04 15:10:53 +00001651/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1652/// block pointer types are compatible or whether a block and normal pointer
1653/// are compatible. It is more restrict than comparing two function pointer
1654// types.
1655Sema::AssignConvertType
1656Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1657 QualType rhsType) {
1658 QualType lhptee, rhptee;
1659
1660 // get the "pointed to" type (ignoring qualifiers at the top level)
1661 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1662 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1663
1664 // make sure we operate on the canonical type
1665 lhptee = Context.getCanonicalType(lhptee);
1666 rhptee = Context.getCanonicalType(rhptee);
1667
1668 AssignConvertType ConvTy = Compatible;
1669
1670 // For blocks we enforce that qualifiers are identical.
1671 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1672 ConvTy = CompatiblePointerDiscardsQualifiers;
1673
1674 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1675 return IncompatibleBlockPointer;
1676 return ConvTy;
1677}
1678
Chris Lattner4b009652007-07-25 00:24:17 +00001679/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1680/// has code to accommodate several GCC extensions when type checking
1681/// pointers. Here are some objectionable examples that GCC considers warnings:
1682///
1683/// int a, *pint;
1684/// short *pshort;
1685/// struct foo *pfoo;
1686///
1687/// pint = pshort; // warning: assignment from incompatible pointer type
1688/// a = pint; // warning: assignment makes integer from pointer without a cast
1689/// pint = a; // warning: assignment makes pointer from integer without a cast
1690/// pint = pfoo; // warning: assignment from incompatible pointer type
1691///
1692/// As a result, the code for dealing with pointers is more complex than the
1693/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001694///
Chris Lattner005ed752008-01-04 18:04:52 +00001695Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001696Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001697 // Get canonical types. We're not formatting these types, just comparing
1698 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001699 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1700 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001701
1702 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001703 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001704
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001705 // If the left-hand side is a reference type, then we are in a
1706 // (rare!) case where we've allowed the use of references in C,
1707 // e.g., as a parameter type in a built-in function. In this case,
1708 // just make sure that the type referenced is compatible with the
1709 // right-hand side type. The caller is responsible for adjusting
1710 // lhsType so that the resulting expression does not have reference
1711 // type.
1712 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
1713 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001714 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001715 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001716 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001717
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001718 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1719 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001720 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001721 // Relax integer conversions like we do for pointers below.
1722 if (rhsType->isIntegerType())
1723 return IntToPointer;
1724 if (lhsType->isIntegerType())
1725 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00001726 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001727 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001728
Nate Begemanc5f0f652008-07-14 18:02:46 +00001729 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001730 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001731 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1732 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001733 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001734
Nate Begemanc5f0f652008-07-14 18:02:46 +00001735 // If we are allowing lax vector conversions, and LHS and RHS are both
1736 // vectors, the total size only needs to be the same. This is a bitcast;
1737 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001738 if (getLangOptions().LaxVectorConversions &&
1739 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001740 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1741 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001742 }
1743 return Incompatible;
1744 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001745
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001746 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001747 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001748
Chris Lattner390564e2008-04-07 06:49:41 +00001749 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001750 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001751 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001752
Chris Lattner390564e2008-04-07 06:49:41 +00001753 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001754 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001755
Steve Naroffa982c712008-09-29 18:10:17 +00001756 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00001757 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff3454b6c2008-09-04 15:10:53 +00001758 return BlockVoidPointer;
Steve Naroffa982c712008-09-29 18:10:17 +00001759
1760 // Treat block pointers as objects.
1761 if (getLangOptions().ObjC1 &&
1762 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1763 return Compatible;
1764 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001765 return Incompatible;
1766 }
1767
1768 if (isa<BlockPointerType>(lhsType)) {
1769 if (rhsType->isIntegerType())
1770 return IntToPointer;
1771
Steve Naroffa982c712008-09-29 18:10:17 +00001772 // Treat block pointers as objects.
1773 if (getLangOptions().ObjC1 &&
1774 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1775 return Compatible;
1776
Steve Naroff3454b6c2008-09-04 15:10:53 +00001777 if (rhsType->isBlockPointerType())
1778 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1779
1780 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1781 if (RHSPT->getPointeeType()->isVoidType())
1782 return BlockVoidPointer;
1783 }
Chris Lattner1853da22008-01-04 23:18:45 +00001784 return Incompatible;
1785 }
1786
Chris Lattner390564e2008-04-07 06:49:41 +00001787 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001788 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001789 if (lhsType == Context.BoolTy)
1790 return Compatible;
1791
1792 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001793 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001794
Chris Lattner390564e2008-04-07 06:49:41 +00001795 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001796 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001797
1798 if (isa<BlockPointerType>(lhsType) &&
1799 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1800 return BlockVoidPointer;
Chris Lattner1853da22008-01-04 23:18:45 +00001801 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001802 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001803
Chris Lattner1853da22008-01-04 23:18:45 +00001804 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001805 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001806 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001807 }
1808 return Incompatible;
1809}
1810
Chris Lattner005ed752008-01-04 18:04:52 +00001811Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001812Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001813 if (getLangOptions().CPlusPlus) {
1814 if (!lhsType->isRecordType()) {
1815 // C++ 5.17p3: If the left operand is not of class type, the
1816 // expression is implicitly converted (C++ 4) to the
1817 // cv-unqualified type of the left operand.
Douglas Gregorbb461502008-10-24 04:54:22 +00001818 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001819 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00001820 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001821 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001822 }
1823
1824 // FIXME: Currently, we fall through and treat C++ classes like C
1825 // structures.
1826 }
1827
Steve Naroffcdee22d2007-11-27 17:58:44 +00001828 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1829 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00001830 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1831 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001832 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001833 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001834 return Compatible;
1835 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001836
1837 // We don't allow conversion of non-null-pointer constants to integers.
1838 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1839 return IntToBlockPointer;
1840
Chris Lattner5f505bf2007-10-16 02:55:40 +00001841 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001842 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001843 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001844 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001845 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001846 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00001847 if (!lhsType->isReferenceType())
1848 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001849
Chris Lattner005ed752008-01-04 18:04:52 +00001850 Sema::AssignConvertType result =
1851 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001852
1853 // C99 6.5.16.1p2: The value of the right operand is converted to the
1854 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001855 // CheckAssignmentConstraints allows the left-hand side to be a reference,
1856 // so that we can use references in built-in functions even in C.
1857 // The getNonReferenceType() call makes sure that the resulting expression
1858 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00001859 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001860 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001861 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001862}
1863
Chris Lattner005ed752008-01-04 18:04:52 +00001864Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001865Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1866 return CheckAssignmentConstraints(lhsType, rhsType);
1867}
1868
Chris Lattner2c8bff72007-12-12 05:47:28 +00001869QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001870 Diag(loc, diag::err_typecheck_invalid_operands,
1871 lex->getType().getAsString(), rex->getType().getAsString(),
1872 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001873 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001874}
1875
1876inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1877 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001878 // For conversion purposes, we ignore any qualifiers.
1879 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001880 QualType lhsType =
1881 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1882 QualType rhsType =
1883 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001884
Nate Begemanc5f0f652008-07-14 18:02:46 +00001885 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001886 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001887 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001888
Nate Begemanc5f0f652008-07-14 18:02:46 +00001889 // Handle the case of a vector & extvector type of the same size and element
1890 // type. It would be nice if we only had one vector type someday.
1891 if (getLangOptions().LaxVectorConversions)
1892 if (const VectorType *LV = lhsType->getAsVectorType())
1893 if (const VectorType *RV = rhsType->getAsVectorType())
1894 if (LV->getElementType() == RV->getElementType() &&
1895 LV->getNumElements() == RV->getNumElements())
1896 return lhsType->isExtVectorType() ? lhsType : rhsType;
1897
1898 // If the lhs is an extended vector and the rhs is a scalar of the same type
1899 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001900 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001901 QualType eltType = V->getElementType();
1902
1903 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1904 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1905 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001906 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001907 return lhsType;
1908 }
1909 }
1910
Nate Begemanc5f0f652008-07-14 18:02:46 +00001911 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001912 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001913 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001914 QualType eltType = V->getElementType();
1915
1916 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1917 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1918 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001919 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001920 return rhsType;
1921 }
1922 }
1923
Chris Lattner4b009652007-07-25 00:24:17 +00001924 // You cannot convert between vector values of different size.
1925 Diag(loc, diag::err_typecheck_vector_not_convertable,
1926 lex->getType().getAsString(), rex->getType().getAsString(),
1927 lex->getSourceRange(), rex->getSourceRange());
1928 return QualType();
1929}
1930
1931inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001932 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001933{
1934 QualType lhsType = lex->getType(), rhsType = rex->getType();
1935
1936 if (lhsType->isVectorType() || rhsType->isVectorType())
1937 return CheckVectorOperands(loc, lex, rex);
1938
Steve Naroff8f708362007-08-24 19:07:16 +00001939 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001940
Chris Lattner4b009652007-07-25 00:24:17 +00001941 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001942 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001943 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001944}
1945
1946inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001947 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001948{
1949 QualType lhsType = lex->getType(), rhsType = rex->getType();
1950
Steve Naroff8f708362007-08-24 19:07:16 +00001951 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001952
Chris Lattner4b009652007-07-25 00:24:17 +00001953 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001954 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001955 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001956}
1957
1958inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001959 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001960{
1961 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1962 return CheckVectorOperands(loc, lex, rex);
1963
Steve Naroff8f708362007-08-24 19:07:16 +00001964 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001965
Chris Lattner4b009652007-07-25 00:24:17 +00001966 // handle the common case first (both operands are arithmetic).
1967 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001968 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001969
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001970 // Put any potential pointer into PExp
1971 Expr* PExp = lex, *IExp = rex;
1972 if (IExp->getType()->isPointerType())
1973 std::swap(PExp, IExp);
1974
1975 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1976 if (IExp->getType()->isIntegerType()) {
1977 // Check for arithmetic on pointers to incomplete types
1978 if (!PTy->getPointeeType()->isObjectType()) {
1979 if (PTy->getPointeeType()->isVoidType()) {
1980 Diag(loc, diag::ext_gnu_void_ptr,
1981 lex->getSourceRange(), rex->getSourceRange());
1982 } else {
1983 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1984 lex->getType().getAsString(), lex->getSourceRange());
1985 return QualType();
1986 }
1987 }
1988 return PExp->getType();
1989 }
1990 }
1991
Chris Lattner2c8bff72007-12-12 05:47:28 +00001992 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001993}
1994
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001995// C99 6.5.6
1996QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1997 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001998 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1999 return CheckVectorOperands(loc, lex, rex);
2000
Steve Naroff8f708362007-08-24 19:07:16 +00002001 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002002
Chris Lattnerf6da2912007-12-09 21:53:25 +00002003 // Enforce type constraints: C99 6.5.6p3.
2004
2005 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002006 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002007 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002008
2009 // Either ptr - int or ptr - ptr.
2010 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002011 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002012
Chris Lattnerf6da2912007-12-09 21:53:25 +00002013 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002014 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002015 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002016 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002017 Diag(loc, diag::ext_gnu_void_ptr,
2018 lex->getSourceRange(), rex->getSourceRange());
2019 } else {
2020 Diag(loc, diag::err_typecheck_sub_ptr_object,
2021 lex->getType().getAsString(), lex->getSourceRange());
2022 return QualType();
2023 }
2024 }
2025
2026 // The result type of a pointer-int computation is the pointer type.
2027 if (rex->getType()->isIntegerType())
2028 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002029
Chris Lattnerf6da2912007-12-09 21:53:25 +00002030 // Handle pointer-pointer subtractions.
2031 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002032 QualType rpointee = RHSPTy->getPointeeType();
2033
Chris Lattnerf6da2912007-12-09 21:53:25 +00002034 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002035 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002036 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002037 if (rpointee->isVoidType()) {
2038 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00002039 Diag(loc, diag::ext_gnu_void_ptr,
2040 lex->getSourceRange(), rex->getSourceRange());
2041 } else {
2042 Diag(loc, diag::err_typecheck_sub_ptr_object,
2043 rex->getType().getAsString(), rex->getSourceRange());
2044 return QualType();
2045 }
2046 }
2047
2048 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002049 if (!Context.typesAreCompatible(
2050 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2051 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002052 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
2053 lex->getType().getAsString(), rex->getType().getAsString(),
2054 lex->getSourceRange(), rex->getSourceRange());
2055 return QualType();
2056 }
2057
2058 return Context.getPointerDiffType();
2059 }
2060 }
2061
Chris Lattner2c8bff72007-12-12 05:47:28 +00002062 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002063}
2064
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002065// C99 6.5.7
2066QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2067 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002068 // C99 6.5.7p2: Each of the operands shall have integer type.
2069 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
2070 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002071
Chris Lattner2c8bff72007-12-12 05:47:28 +00002072 // Shifts don't perform usual arithmetic conversions, they just do integer
2073 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002074 if (!isCompAssign)
2075 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002076 UsualUnaryConversions(rex);
2077
2078 // "The type of the result is that of the promoted left operand."
2079 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002080}
2081
Eli Friedman0d9549b2008-08-22 00:56:42 +00002082static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2083 ASTContext& Context) {
2084 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2085 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2086 // ID acts sort of like void* for ObjC interfaces
2087 if (LHSIface && Context.isObjCIdType(RHS))
2088 return true;
2089 if (RHSIface && Context.isObjCIdType(LHS))
2090 return true;
2091 if (!LHSIface || !RHSIface)
2092 return false;
2093 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2094 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2095}
2096
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002097// C99 6.5.8
2098QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2099 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002100 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2101 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
2102
Chris Lattner254f3bc2007-08-26 01:18:55 +00002103 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002104 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2105 UsualArithmeticConversions(lex, rex);
2106 else {
2107 UsualUnaryConversions(lex);
2108 UsualUnaryConversions(rex);
2109 }
Chris Lattner4b009652007-07-25 00:24:17 +00002110 QualType lType = lex->getType();
2111 QualType rType = rex->getType();
2112
Ted Kremenek486509e2007-10-29 17:13:39 +00002113 // For non-floating point types, check for self-comparisons of the form
2114 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2115 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002116 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002117 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2118 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002119 if (DRL->getDecl() == DRR->getDecl())
2120 Diag(loc, diag::warn_selfcomparison);
2121 }
2122
Chris Lattner254f3bc2007-08-26 01:18:55 +00002123 if (isRelational) {
2124 if (lType->isRealType() && rType->isRealType())
2125 return Context.IntTy;
2126 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002127 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002128 if (lType->isFloatingType()) {
2129 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00002130 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002131 }
2132
Chris Lattner254f3bc2007-08-26 01:18:55 +00002133 if (lType->isArithmeticType() && rType->isArithmeticType())
2134 return Context.IntTy;
2135 }
Chris Lattner4b009652007-07-25 00:24:17 +00002136
Chris Lattner22be8422007-08-26 01:10:14 +00002137 bool LHSIsNull = lex->isNullPointerConstant(Context);
2138 bool RHSIsNull = rex->isNullPointerConstant(Context);
2139
Chris Lattner254f3bc2007-08-26 01:18:55 +00002140 // All of the following pointer related warnings are GCC extensions, except
2141 // when handling null pointer constants. One day, we can consider making them
2142 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002143 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002144 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002145 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002146 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002147 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002148
Steve Naroff3b435622007-11-13 14:57:38 +00002149 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002150 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2151 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002152 RCanPointeeTy.getUnqualifiedType()) &&
2153 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroff4462cb02007-08-16 21:48:38 +00002154 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2155 lType.getAsString(), rType.getAsString(),
2156 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002157 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002158 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002159 return Context.IntTy;
2160 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002161 // Handle block pointer types.
2162 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2163 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2164 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2165
2166 if (!LHSIsNull && !RHSIsNull &&
2167 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2168 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2169 lType.getAsString(), rType.getAsString(),
2170 lex->getSourceRange(), rex->getSourceRange());
2171 }
2172 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2173 return Context.IntTy;
2174 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002175 // Allow block pointers to be compared with null pointer constants.
2176 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2177 (lType->isPointerType() && rType->isBlockPointerType())) {
2178 if (!LHSIsNull && !RHSIsNull) {
2179 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2180 lType.getAsString(), rType.getAsString(),
2181 lex->getSourceRange(), rex->getSourceRange());
2182 }
2183 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2184 return Context.IntTy;
2185 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002186
Steve Naroff936c4362008-06-03 14:04:54 +00002187 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002188 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002189 const PointerType *LPT = lType->getAsPointerType();
2190 const PointerType *RPT = rType->getAsPointerType();
2191 bool LPtrToVoid = LPT ?
2192 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2193 bool RPtrToVoid = RPT ?
2194 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2195
2196 if (!LPtrToVoid && !RPtrToVoid &&
2197 !Context.typesAreCompatible(lType, rType)) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002198 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2199 lType.getAsString(), rType.getAsString(),
2200 lex->getSourceRange(), rex->getSourceRange());
2201 ImpCastExprToType(rex, lType);
2202 return Context.IntTy;
2203 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002204 ImpCastExprToType(rex, lType);
Steve Naroff792800d2008-10-22 22:40:28 +00002205 return Context.IntTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002206 }
Steve Naroff936c4362008-06-03 14:04:54 +00002207 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2208 ImpCastExprToType(rex, lType);
2209 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002210 } else {
2211 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
2212 Diag(loc, diag::warn_incompatible_qualified_id_operands,
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002213 lType.getAsString(), rType.getAsString(),
Steve Naroff19608432008-10-14 22:18:38 +00002214 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002215 ImpCastExprToType(rex, lType);
Steve Naroff792800d2008-10-22 22:40:28 +00002216 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002217 }
Steve Naroff936c4362008-06-03 14:04:54 +00002218 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002219 }
Steve Naroff936c4362008-06-03 14:04:54 +00002220 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2221 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002222 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002223 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2224 lType.getAsString(), rType.getAsString(),
2225 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002226 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002227 return Context.IntTy;
2228 }
Steve Naroff936c4362008-06-03 14:04:54 +00002229 if (lType->isIntegerType() &&
2230 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002231 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002232 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2233 lType.getAsString(), rType.getAsString(),
2234 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002235 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002236 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002237 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002238 // Handle block pointers.
2239 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2240 if (!RHSIsNull)
2241 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2242 lType.getAsString(), rType.getAsString(),
2243 lex->getSourceRange(), rex->getSourceRange());
2244 ImpCastExprToType(rex, lType); // promote the integer to pointer
2245 return Context.IntTy;
2246 }
2247 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2248 if (!LHSIsNull)
2249 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2250 lType.getAsString(), rType.getAsString(),
2251 lex->getSourceRange(), rex->getSourceRange());
2252 ImpCastExprToType(lex, rType); // promote the integer to pointer
2253 return Context.IntTy;
2254 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00002255 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002256}
2257
Nate Begemanc5f0f652008-07-14 18:02:46 +00002258/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2259/// operates on extended vector types. Instead of producing an IntTy result,
2260/// like a scalar comparison, a vector comparison produces a vector of integer
2261/// types.
2262QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2263 SourceLocation loc,
2264 bool isRelational) {
2265 // Check to make sure we're operating on vectors of the same type and width,
2266 // Allowing one side to be a scalar of element type.
2267 QualType vType = CheckVectorOperands(loc, lex, rex);
2268 if (vType.isNull())
2269 return vType;
2270
2271 QualType lType = lex->getType();
2272 QualType rType = rex->getType();
2273
2274 // For non-floating point types, check for self-comparisons of the form
2275 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2276 // often indicate logic errors in the program.
2277 if (!lType->isFloatingType()) {
2278 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2279 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2280 if (DRL->getDecl() == DRR->getDecl())
2281 Diag(loc, diag::warn_selfcomparison);
2282 }
2283
2284 // Check for comparisons of floating point operands using != and ==.
2285 if (!isRelational && lType->isFloatingType()) {
2286 assert (rType->isFloatingType());
2287 CheckFloatComparison(loc,lex,rex);
2288 }
2289
2290 // Return the type for the comparison, which is the same as vector type for
2291 // integer vectors, or an integer type of identical size and number of
2292 // elements for floating point vectors.
2293 if (lType->isIntegerType())
2294 return lType;
2295
2296 const VectorType *VTy = lType->getAsVectorType();
2297
2298 // FIXME: need to deal with non-32b int / non-64b long long
2299 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2300 if (TypeSize == 32) {
2301 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2302 }
2303 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2304 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2305}
2306
Chris Lattner4b009652007-07-25 00:24:17 +00002307inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00002308 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002309{
2310 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2311 return CheckVectorOperands(loc, lex, rex);
2312
Steve Naroff8f708362007-08-24 19:07:16 +00002313 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002314
2315 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002316 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002317 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002318}
2319
2320inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
2321 Expr *&lex, Expr *&rex, SourceLocation loc)
2322{
2323 UsualUnaryConversions(lex);
2324 UsualUnaryConversions(rex);
2325
Eli Friedmanbea3f842008-05-13 20:16:47 +00002326 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002327 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002328 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002329}
2330
Chris Lattner4c2642c2008-11-18 01:22:49 +00002331/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2332/// emit an error and return true. If so, return false.
2333static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2334 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2335 if (IsLV == Expr::MLV_Valid)
2336 return false;
2337
2338 unsigned Diag = 0;
2339 bool NeedType = false;
2340 switch (IsLV) { // C99 6.5.16p2
2341 default: assert(0 && "Unknown result from isModifiableLvalue!");
2342 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00002343 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002344 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2345 NeedType = true;
2346 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002347 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002348 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2349 NeedType = true;
2350 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00002351 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002352 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2353 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002354 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002355 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2356 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002357 case Expr::MLV_IncompleteType:
2358 case Expr::MLV_IncompleteVoidType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002359 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2360 NeedType = true;
2361 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002362 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002363 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2364 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00002365 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002366 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2367 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002368 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002369
Chris Lattner4c2642c2008-11-18 01:22:49 +00002370 if (NeedType)
Chris Lattnerda189c62008-11-18 01:26:17 +00002371 S.Diag(Loc, Diag, E->getType().getAsString(), E->getSourceRange());
Chris Lattner4c2642c2008-11-18 01:22:49 +00002372 else
2373 S.Diag(Loc, Diag, E->getSourceRange());
2374 return true;
2375}
2376
2377
2378
2379// C99 6.5.16.1
2380QualType Sema::CheckAssignmentOperands(Expr *lex, Expr *&rex,SourceLocation loc,
2381 QualType compoundType) {
2382 QualType lhsType = lex->getType();
2383 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
2384
2385 // Verify that lex is a modifiable lvalue, and emit error if not.
2386 if (CheckForModifiableLvalue(lex, loc, *this))
2387 return QualType();
2388
Chris Lattner005ed752008-01-04 18:04:52 +00002389 AssignConvertType ConvTy;
Chris Lattner34c85082008-08-21 18:04:13 +00002390 if (compoundType.isNull()) {
2391 // Simple assignment "x = y".
Chris Lattner005ed752008-01-04 18:04:52 +00002392 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner34c85082008-08-21 18:04:13 +00002393
2394 // If the RHS is a unary plus or minus, check to see if they = and + are
2395 // right next to each other. If so, the user may have typo'd "x =+ 4"
2396 // instead of "x += 4".
2397 Expr *RHSCheck = rex;
2398 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2399 RHSCheck = ICE->getSubExpr();
2400 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2401 if ((UO->getOpcode() == UnaryOperator::Plus ||
2402 UO->getOpcode() == UnaryOperator::Minus) &&
2403 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2404 // Only if the two operators are exactly adjacent.
2405 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2406 Diag(loc, diag::warn_not_compound_assign,
2407 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2408 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2409 }
2410 } else {
2411 // Compound assignment "x += y"
Chris Lattner005ed752008-01-04 18:04:52 +00002412 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner34c85082008-08-21 18:04:13 +00002413 }
Chris Lattner005ed752008-01-04 18:04:52 +00002414
2415 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2416 rex, "assigning"))
2417 return QualType();
2418
Chris Lattner4b009652007-07-25 00:24:17 +00002419 // C99 6.5.16p3: The type of an assignment expression is the type of the
2420 // left operand unless the left operand has qualified type, in which case
2421 // it is the unqualified version of the type of the left operand.
2422 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2423 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002424 // C++ 5.17p1: the type of the assignment expression is that of its left
2425 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00002426 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002427}
2428
2429inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2430 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00002431
2432 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2433 DefaultFunctionArrayConversion(rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002434 return rex->getType();
2435}
2436
2437/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2438/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2439QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2440 QualType resType = op->getType();
2441 assert(!resType.isNull() && "no type for increment/decrement expression");
2442
Steve Naroffd30e1932007-08-24 17:20:07 +00002443 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00002444 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002445 if (pt->getPointeeType()->isVoidType()) {
2446 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2447 } else if (!pt->getPointeeType()->isObjectType()) {
2448 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00002449 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2450 resType.getAsString(), op->getSourceRange());
2451 return QualType();
2452 }
Steve Naroffd30e1932007-08-24 17:20:07 +00002453 } else if (!resType->isRealType()) {
2454 if (resType->isComplexType())
2455 // C99 does not support ++/-- on complex types.
2456 Diag(OpLoc, diag::ext_integer_increment_complex,
2457 resType.getAsString(), op->getSourceRange());
2458 else {
2459 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2460 resType.getAsString(), op->getSourceRange());
2461 return QualType();
2462 }
Chris Lattner4b009652007-07-25 00:24:17 +00002463 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002464 // At this point, we know we have a real, complex or pointer type.
2465 // Now make sure the operand is a modifiable lvalue.
Chris Lattnerda189c62008-11-18 01:26:17 +00002466 if (CheckForModifiableLvalue(op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00002467 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002468 return resType;
2469}
2470
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002471/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002472/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002473/// where the declaration is needed for type checking. We only need to
2474/// handle cases when the expression references a function designator
2475/// or is an lvalue. Here are some examples:
2476/// - &(x) => x
2477/// - &*****f => f for f a function designator.
2478/// - &s.xx => s
2479/// - &s.zz[1].yy -> s, if zz is an array
2480/// - *(x + 1) -> x, if x is an array
2481/// - &"123"[2] -> 0
2482/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002483static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002484 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002485 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002486 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002487 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002488 // Fields cannot be declared with a 'register' storage class.
2489 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002490 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002491 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002492 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002493 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002494 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002495
Douglas Gregord2baafd2008-10-21 16:13:35 +00002496 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002497 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002498 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002499 return 0;
2500 else
2501 return VD;
2502 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002503 case Stmt::UnaryOperatorClass: {
2504 UnaryOperator *UO = cast<UnaryOperator>(E);
2505
2506 switch(UO->getOpcode()) {
2507 case UnaryOperator::Deref: {
2508 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002509 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2510 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2511 if (!VD || VD->getType()->isPointerType())
2512 return 0;
2513 return VD;
2514 }
2515 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002516 }
2517 case UnaryOperator::Real:
2518 case UnaryOperator::Imag:
2519 case UnaryOperator::Extension:
2520 return getPrimaryDecl(UO->getSubExpr());
2521 default:
2522 return 0;
2523 }
2524 }
2525 case Stmt::BinaryOperatorClass: {
2526 BinaryOperator *BO = cast<BinaryOperator>(E);
2527
2528 // Handle cases involving pointer arithmetic. The result of an
2529 // Assign or AddAssign is not an lvalue so they can be ignored.
2530
2531 // (x + n) or (n + x) => x
2532 if (BO->getOpcode() == BinaryOperator::Add) {
2533 if (BO->getLHS()->getType()->isPointerType()) {
2534 return getPrimaryDecl(BO->getLHS());
2535 } else if (BO->getRHS()->getType()->isPointerType()) {
2536 return getPrimaryDecl(BO->getRHS());
2537 }
2538 }
2539
2540 return 0;
2541 }
Chris Lattner4b009652007-07-25 00:24:17 +00002542 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002543 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002544 case Stmt::ImplicitCastExprClass:
2545 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002546 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002547 default:
2548 return 0;
2549 }
2550}
2551
2552/// CheckAddressOfOperand - The operand of & must be either a function
2553/// designator or an lvalue designating an object. If it is an lvalue, the
2554/// object cannot be declared with storage class register or be a bit field.
2555/// Note: The usual conversions are *not* applied to the operand of the &
2556/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00002557/// In C++, the operand might be an overloaded function name, in which case
2558/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00002559QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002560 if (getLangOptions().C99) {
2561 // Implement C99-only parts of addressof rules.
2562 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2563 if (uOp->getOpcode() == UnaryOperator::Deref)
2564 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2565 // (assuming the deref expression is valid).
2566 return uOp->getSubExpr()->getType();
2567 }
2568 // Technically, there should be a check for array subscript
2569 // expressions here, but the result of one is always an lvalue anyway.
2570 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002571 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002572 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002573
2574 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002575 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2576 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002577 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2578 op->getSourceRange());
2579 return QualType();
2580 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002581 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2582 if (MemExpr->getMemberDecl()->isBitField()) {
2583 Diag(OpLoc, diag::err_typecheck_address_of,
2584 std::string("bit-field"), op->getSourceRange());
2585 return QualType();
2586 }
2587 // Check for Apple extension for accessing vector components.
2588 } else if (isa<ArraySubscriptExpr>(op) &&
2589 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2590 Diag(OpLoc, diag::err_typecheck_address_of,
2591 std::string("vector"), op->getSourceRange());
2592 return QualType();
2593 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002594 // We have an lvalue with a decl. Make sure the decl is not declared
2595 // with the register storage-class specifier.
2596 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2597 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002598 Diag(OpLoc, diag::err_typecheck_address_of,
2599 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002600 return QualType();
2601 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00002602 } else if (isa<OverloadedFunctionDecl>(dcl))
2603 return Context.OverloadTy;
2604 else
Chris Lattner4b009652007-07-25 00:24:17 +00002605 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002606 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002607
Chris Lattner4b009652007-07-25 00:24:17 +00002608 // If the operand has type "type", the result has type "pointer to type".
2609 return Context.getPointerType(op->getType());
2610}
2611
2612QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2613 UsualUnaryConversions(op);
2614 QualType qType = op->getType();
2615
Chris Lattner7931f4a2007-07-31 16:53:04 +00002616 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002617 // Note that per both C89 and C99, this is always legal, even
2618 // if ptype is an incomplete type or void.
2619 // It would be possible to warn about dereferencing a
2620 // void pointer, but it's completely well-defined,
2621 // and such a warning is unlikely to catch any mistakes.
2622 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002623 }
2624 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2625 qType.getAsString(), op->getSourceRange());
2626 return QualType();
2627}
2628
2629static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2630 tok::TokenKind Kind) {
2631 BinaryOperator::Opcode Opc;
2632 switch (Kind) {
2633 default: assert(0 && "Unknown binop!");
2634 case tok::star: Opc = BinaryOperator::Mul; break;
2635 case tok::slash: Opc = BinaryOperator::Div; break;
2636 case tok::percent: Opc = BinaryOperator::Rem; break;
2637 case tok::plus: Opc = BinaryOperator::Add; break;
2638 case tok::minus: Opc = BinaryOperator::Sub; break;
2639 case tok::lessless: Opc = BinaryOperator::Shl; break;
2640 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2641 case tok::lessequal: Opc = BinaryOperator::LE; break;
2642 case tok::less: Opc = BinaryOperator::LT; break;
2643 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2644 case tok::greater: Opc = BinaryOperator::GT; break;
2645 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2646 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2647 case tok::amp: Opc = BinaryOperator::And; break;
2648 case tok::caret: Opc = BinaryOperator::Xor; break;
2649 case tok::pipe: Opc = BinaryOperator::Or; break;
2650 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2651 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2652 case tok::equal: Opc = BinaryOperator::Assign; break;
2653 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2654 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2655 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2656 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2657 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2658 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2659 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2660 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2661 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2662 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2663 case tok::comma: Opc = BinaryOperator::Comma; break;
2664 }
2665 return Opc;
2666}
2667
2668static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2669 tok::TokenKind Kind) {
2670 UnaryOperator::Opcode Opc;
2671 switch (Kind) {
2672 default: assert(0 && "Unknown unary op!");
2673 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2674 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2675 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2676 case tok::star: Opc = UnaryOperator::Deref; break;
2677 case tok::plus: Opc = UnaryOperator::Plus; break;
2678 case tok::minus: Opc = UnaryOperator::Minus; break;
2679 case tok::tilde: Opc = UnaryOperator::Not; break;
2680 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002681 case tok::kw___real: Opc = UnaryOperator::Real; break;
2682 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2683 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2684 }
2685 return Opc;
2686}
2687
Douglas Gregord7f915e2008-11-06 23:29:22 +00002688/// CreateBuiltinBinOp - Creates a new built-in binary operation with
2689/// operator @p Opc at location @c TokLoc. This routine only supports
2690/// built-in operations; ActOnBinOp handles overloaded operators.
2691Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
2692 unsigned Op,
2693 Expr *lhs, Expr *rhs) {
2694 QualType ResultTy; // Result type of the binary operator.
2695 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2696 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
2697
2698 switch (Opc) {
2699 default:
2700 assert(0 && "Unknown binary expr!");
2701 case BinaryOperator::Assign:
2702 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
2703 break;
2704 case BinaryOperator::Mul:
2705 case BinaryOperator::Div:
2706 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
2707 break;
2708 case BinaryOperator::Rem:
2709 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
2710 break;
2711 case BinaryOperator::Add:
2712 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
2713 break;
2714 case BinaryOperator::Sub:
2715 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
2716 break;
2717 case BinaryOperator::Shl:
2718 case BinaryOperator::Shr:
2719 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
2720 break;
2721 case BinaryOperator::LE:
2722 case BinaryOperator::LT:
2723 case BinaryOperator::GE:
2724 case BinaryOperator::GT:
2725 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
2726 break;
2727 case BinaryOperator::EQ:
2728 case BinaryOperator::NE:
2729 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
2730 break;
2731 case BinaryOperator::And:
2732 case BinaryOperator::Xor:
2733 case BinaryOperator::Or:
2734 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
2735 break;
2736 case BinaryOperator::LAnd:
2737 case BinaryOperator::LOr:
2738 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
2739 break;
2740 case BinaryOperator::MulAssign:
2741 case BinaryOperator::DivAssign:
2742 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
2743 if (!CompTy.isNull())
2744 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2745 break;
2746 case BinaryOperator::RemAssign:
2747 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
2748 if (!CompTy.isNull())
2749 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2750 break;
2751 case BinaryOperator::AddAssign:
2752 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
2753 if (!CompTy.isNull())
2754 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2755 break;
2756 case BinaryOperator::SubAssign:
2757 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
2758 if (!CompTy.isNull())
2759 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2760 break;
2761 case BinaryOperator::ShlAssign:
2762 case BinaryOperator::ShrAssign:
2763 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
2764 if (!CompTy.isNull())
2765 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2766 break;
2767 case BinaryOperator::AndAssign:
2768 case BinaryOperator::XorAssign:
2769 case BinaryOperator::OrAssign:
2770 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
2771 if (!CompTy.isNull())
2772 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2773 break;
2774 case BinaryOperator::Comma:
2775 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
2776 break;
2777 }
2778 if (ResultTy.isNull())
2779 return true;
2780 if (CompTy.isNull())
2781 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
2782 else
2783 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
2784}
2785
Chris Lattner4b009652007-07-25 00:24:17 +00002786// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002787Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
2788 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002789 ExprTy *LHS, ExprTy *RHS) {
2790 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2791 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2792
Steve Naroff87d58b42007-09-16 03:34:24 +00002793 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2794 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002795
Douglas Gregord7f915e2008-11-06 23:29:22 +00002796 if (getLangOptions().CPlusPlus &&
2797 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
2798 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002799 // If this is one of the assignment operators, we only perform
2800 // overload resolution if the left-hand side is a class or
2801 // enumeration type (C++ [expr.ass]p3).
2802 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
2803 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
2804 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
2805 }
2806
Douglas Gregord7f915e2008-11-06 23:29:22 +00002807 // C++ [over.binary]p1:
2808 // A binary operator shall be implemented either by a non-static
2809 // member function (9.3) with one parameter or by a non-member
2810 // function with two parameters. Thus, for any binary operator
2811 // @, x@y can be interpreted as either x.operator@(y) or
2812 // operator@(x,y). If both forms of the operator function have
2813 // been declared, the rules in 13.3.1.2 determines which, if
2814 // any, interpretation is used.
2815 OverloadCandidateSet CandidateSet;
2816
2817 // Determine which overloaded operator we're dealing with.
2818 static const OverloadedOperatorKind OverOps[] = {
2819 OO_Star, OO_Slash, OO_Percent,
2820 OO_Plus, OO_Minus,
2821 OO_LessLess, OO_GreaterGreater,
2822 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2823 OO_EqualEqual, OO_ExclaimEqual,
2824 OO_Amp,
2825 OO_Caret,
2826 OO_Pipe,
2827 OO_AmpAmp,
2828 OO_PipePipe,
2829 OO_Equal, OO_StarEqual,
2830 OO_SlashEqual, OO_PercentEqual,
2831 OO_PlusEqual, OO_MinusEqual,
2832 OO_LessLessEqual, OO_GreaterGreaterEqual,
2833 OO_AmpEqual, OO_CaretEqual,
2834 OO_PipeEqual,
2835 OO_Comma
2836 };
2837 OverloadedOperatorKind OverOp = OverOps[Opc];
2838
2839 // Lookup this operator.
2840 Decl *D = LookupDecl(&PP.getIdentifierTable().getOverloadedOperator(OverOp),
2841 Decl::IDNS_Ordinary, S);
2842
2843 // Add any overloaded operators we find to the overload set.
2844 Expr *Args[2] = { lhs, rhs };
2845 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
2846 AddOverloadCandidate(FD, Args, 2, CandidateSet);
2847 else if (OverloadedFunctionDecl *Ovl
2848 = dyn_cast_or_null<OverloadedFunctionDecl>(D))
2849 AddOverloadCandidates(Ovl, Args, 2, CandidateSet);
2850
Douglas Gregor70d26122008-11-12 17:17:38 +00002851 // Add builtin overload candidates (C++ [over.built]).
2852 AddBuiltinBinaryOperatorCandidates(OverOp, Args, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00002853
2854 // Perform overload resolution.
2855 OverloadCandidateSet::iterator Best;
2856 switch (BestViableFunction(CandidateSet, Best)) {
2857 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00002858 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002859 FunctionDecl *FnDecl = Best->Function;
2860
Douglas Gregor70d26122008-11-12 17:17:38 +00002861 if (FnDecl) {
2862 // We matched an overloaded operator. Build a call to that
2863 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002864
Douglas Gregor70d26122008-11-12 17:17:38 +00002865 // Convert the arguments.
2866 // FIXME: Conversion will be different for member operators.
2867 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
2868 "passing") ||
2869 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
2870 "passing"))
2871 return true;
Douglas Gregord7f915e2008-11-06 23:29:22 +00002872
Douglas Gregor70d26122008-11-12 17:17:38 +00002873 // Determine the result type
2874 QualType ResultTy
2875 = FnDecl->getType()->getAsFunctionType()->getResultType();
2876 ResultTy = ResultTy.getNonReferenceType();
2877
2878 // Build the actual expression node.
Douglas Gregor65fedaf2008-11-14 16:09:21 +00002879 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
2880 SourceLocation());
2881 UsualUnaryConversions(FnExpr);
2882
2883 Expr *Args[2] = { lhs, rhs };
2884 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregor70d26122008-11-12 17:17:38 +00002885 } else {
2886 // We matched a built-in operator. Convert the arguments, then
2887 // break out so that we will build the appropriate built-in
2888 // operator node.
2889 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
2890 "passing") ||
2891 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
2892 "passing"))
2893 return true;
2894
2895 break;
2896 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00002897 }
2898
2899 case OR_No_Viable_Function:
2900 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00002901 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002902 break;
2903
2904 case OR_Ambiguous:
2905 Diag(TokLoc,
2906 diag::err_ovl_ambiguous_oper,
2907 BinaryOperator::getOpcodeStr(Opc),
2908 lhs->getSourceRange(), rhs->getSourceRange());
2909 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2910 return true;
2911 }
2912
Douglas Gregor70d26122008-11-12 17:17:38 +00002913 // Either we found no viable overloaded operator or we matched a
2914 // built-in operator. In either case, fall through to trying to
2915 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002916 }
2917
Chris Lattner4b009652007-07-25 00:24:17 +00002918
Douglas Gregord7f915e2008-11-06 23:29:22 +00002919 // Build a built-in binary operation.
2920 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00002921}
2922
2923// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002924Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002925 ExprTy *input) {
2926 Expr *Input = (Expr*)input;
2927 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2928 QualType resultType;
2929 switch (Opc) {
2930 default:
2931 assert(0 && "Unimplemented unary expr!");
2932 case UnaryOperator::PreInc:
2933 case UnaryOperator::PreDec:
2934 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2935 break;
2936 case UnaryOperator::AddrOf:
2937 resultType = CheckAddressOfOperand(Input, OpLoc);
2938 break;
2939 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002940 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002941 resultType = CheckIndirectionOperand(Input, OpLoc);
2942 break;
2943 case UnaryOperator::Plus:
2944 case UnaryOperator::Minus:
2945 UsualUnaryConversions(Input);
2946 resultType = Input->getType();
2947 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2948 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2949 resultType.getAsString());
2950 break;
2951 case UnaryOperator::Not: // bitwise complement
2952 UsualUnaryConversions(Input);
2953 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002954 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2955 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2956 // C99 does not support '~' for complex conjugation.
2957 Diag(OpLoc, diag::ext_integer_complement_complex,
2958 resultType.getAsString(), Input->getSourceRange());
2959 else if (!resultType->isIntegerType())
2960 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2961 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002962 break;
2963 case UnaryOperator::LNot: // logical negation
2964 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2965 DefaultFunctionArrayConversion(Input);
2966 resultType = Input->getType();
2967 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2968 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2969 resultType.getAsString());
2970 // LNot always has type int. C99 6.5.3.3p5.
2971 resultType = Context.IntTy;
2972 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002973 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002974 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002975 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002976 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002977 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002978 resultType = Input->getType();
2979 break;
2980 }
2981 if (resultType.isNull())
2982 return true;
2983 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2984}
2985
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002986/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2987Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002988 SourceLocation LabLoc,
2989 IdentifierInfo *LabelII) {
2990 // Look up the record for this label identifier.
2991 LabelStmt *&LabelDecl = LabelMap[LabelII];
2992
Daniel Dunbar879788d2008-08-04 16:51:22 +00002993 // If we haven't seen this label yet, create a forward reference. It
2994 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00002995 if (LabelDecl == 0)
2996 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2997
2998 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002999 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3000 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003001}
3002
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003003Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003004 SourceLocation RPLoc) { // "({..})"
3005 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3006 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3007 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3008
3009 // FIXME: there are a variety of strange constraints to enforce here, for
3010 // example, it is not possible to goto into a stmt expression apparently.
3011 // More semantic analysis is needed.
3012
3013 // FIXME: the last statement in the compount stmt has its value used. We
3014 // should not warn about it being unused.
3015
3016 // If there are sub stmts in the compound stmt, take the type of the last one
3017 // as the type of the stmtexpr.
3018 QualType Ty = Context.VoidTy;
3019
Chris Lattner200964f2008-07-26 19:51:01 +00003020 if (!Compound->body_empty()) {
3021 Stmt *LastStmt = Compound->body_back();
3022 // If LastStmt is a label, skip down through into the body.
3023 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3024 LastStmt = Label->getSubStmt();
3025
3026 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003027 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003028 }
Chris Lattner4b009652007-07-25 00:24:17 +00003029
3030 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3031}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003032
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003033Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003034 SourceLocation TypeLoc,
3035 TypeTy *argty,
3036 OffsetOfComponent *CompPtr,
3037 unsigned NumComponents,
3038 SourceLocation RPLoc) {
3039 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3040 assert(!ArgTy.isNull() && "Missing type argument!");
3041
3042 // We must have at least one component that refers to the type, and the first
3043 // one is known to be a field designator. Verify that the ArgTy represents
3044 // a struct/union/class.
3045 if (!ArgTy->isRecordType())
3046 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
3047
3048 // Otherwise, create a compound literal expression as the base, and
3049 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003050 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003051
Chris Lattnerb37522e2007-08-31 21:49:13 +00003052 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3053 // GCC extension, diagnose them.
3054 if (NumComponents != 1)
3055 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
3056 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
3057
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003058 for (unsigned i = 0; i != NumComponents; ++i) {
3059 const OffsetOfComponent &OC = CompPtr[i];
3060 if (OC.isBrackets) {
3061 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003062 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003063 if (!AT) {
3064 delete Res;
3065 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
3066 Res->getType().getAsString());
3067 }
3068
Chris Lattner2af6a802007-08-30 17:59:59 +00003069 // FIXME: C++: Verify that operator[] isn't overloaded.
3070
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003071 // C99 6.5.2.1p1
3072 Expr *Idx = static_cast<Expr*>(OC.U.E);
3073 if (!Idx->getType()->isIntegerType())
3074 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
3075 Idx->getSourceRange());
3076
3077 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3078 continue;
3079 }
3080
3081 const RecordType *RC = Res->getType()->getAsRecordType();
3082 if (!RC) {
3083 delete Res;
3084 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
3085 Res->getType().getAsString());
3086 }
3087
3088 // Get the decl corresponding to this.
3089 RecordDecl *RD = RC->getDecl();
3090 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
3091 if (!MemberDecl)
3092 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
3093 OC.U.IdentInfo->getName(),
3094 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00003095
3096 // FIXME: C++: Verify that MemberDecl isn't a static field.
3097 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003098 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3099 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003100 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3101 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003102 }
3103
3104 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3105 BuiltinLoc);
3106}
3107
3108
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003109Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003110 TypeTy *arg1, TypeTy *arg2,
3111 SourceLocation RPLoc) {
3112 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3113 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3114
3115 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3116
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003117 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003118}
3119
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003120Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003121 ExprTy *expr1, ExprTy *expr2,
3122 SourceLocation RPLoc) {
3123 Expr *CondExpr = static_cast<Expr*>(cond);
3124 Expr *LHSExpr = static_cast<Expr*>(expr1);
3125 Expr *RHSExpr = static_cast<Expr*>(expr2);
3126
3127 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3128
3129 // The conditional expression is required to be a constant expression.
3130 llvm::APSInt condEval(32);
3131 SourceLocation ExpLoc;
3132 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
3133 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
3134 CondExpr->getSourceRange());
3135
3136 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3137 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3138 RHSExpr->getType();
3139 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3140}
3141
Steve Naroff52a81c02008-09-03 18:15:37 +00003142//===----------------------------------------------------------------------===//
3143// Clang Extensions.
3144//===----------------------------------------------------------------------===//
3145
3146/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003147void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003148 // Analyze block parameters.
3149 BlockSemaInfo *BSI = new BlockSemaInfo();
3150
3151 // Add BSI to CurBlock.
3152 BSI->PrevBlockInfo = CurBlock;
3153 CurBlock = BSI;
3154
3155 BSI->ReturnType = 0;
3156 BSI->TheScope = BlockScope;
3157
Steve Naroff52059382008-10-10 01:28:17 +00003158 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
3159 PushDeclContext(BSI->TheDecl);
3160}
3161
3162void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003163 // Analyze arguments to block.
3164 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3165 "Not a function declarator!");
3166 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3167
Steve Naroff52059382008-10-10 01:28:17 +00003168 CurBlock->hasPrototype = FTI.hasPrototype;
3169 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003170
3171 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3172 // no arguments, not a function that takes a single void argument.
3173 if (FTI.hasPrototype &&
3174 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3175 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3176 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3177 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003178 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003179 } else if (FTI.hasPrototype) {
3180 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003181 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3182 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003183 }
Steve Naroff52059382008-10-10 01:28:17 +00003184 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3185
3186 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3187 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3188 // If this has an identifier, add it to the scope stack.
3189 if ((*AI)->getIdentifier())
3190 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003191}
3192
3193/// ActOnBlockError - If there is an error parsing a block, this callback
3194/// is invoked to pop the information about the block from the action impl.
3195void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3196 // Ensure that CurBlock is deleted.
3197 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3198
3199 // Pop off CurBlock, handle nested blocks.
3200 CurBlock = CurBlock->PrevBlockInfo;
3201
3202 // FIXME: Delete the ParmVarDecl objects as well???
3203
3204}
3205
3206/// ActOnBlockStmtExpr - This is called when the body of a block statement
3207/// literal was successfully completed. ^(int x){...}
3208Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3209 Scope *CurScope) {
3210 // Ensure that CurBlock is deleted.
3211 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3212 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3213
Steve Naroff52059382008-10-10 01:28:17 +00003214 PopDeclContext();
3215
Steve Naroff52a81c02008-09-03 18:15:37 +00003216 // Pop off CurBlock, handle nested blocks.
3217 CurBlock = CurBlock->PrevBlockInfo;
3218
3219 QualType RetTy = Context.VoidTy;
3220 if (BSI->ReturnType)
3221 RetTy = QualType(BSI->ReturnType, 0);
3222
3223 llvm::SmallVector<QualType, 8> ArgTypes;
3224 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3225 ArgTypes.push_back(BSI->Params[i]->getType());
3226
3227 QualType BlockTy;
3228 if (!BSI->hasPrototype)
3229 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3230 else
3231 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003232 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003233
3234 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003235
Steve Naroff95029d92008-10-08 18:44:00 +00003236 BSI->TheDecl->setBody(Body.take());
3237 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003238}
3239
Nate Begemanbd881ef2008-01-30 20:50:20 +00003240/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003241/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003242/// The number of arguments has already been validated to match the number of
3243/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003244static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3245 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003246 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003247 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003248 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3249 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003250
3251 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003252 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003253 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003254 return true;
3255}
3256
3257Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3258 SourceLocation *CommaLocs,
3259 SourceLocation BuiltinLoc,
3260 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003261 // __builtin_overload requires at least 2 arguments
3262 if (NumArgs < 2)
3263 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3264 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003265
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003266 // The first argument is required to be a constant expression. It tells us
3267 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003268 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003269 Expr *NParamsExpr = Args[0];
3270 llvm::APSInt constEval(32);
3271 SourceLocation ExpLoc;
3272 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
3273 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3274 NParamsExpr->getSourceRange());
3275
3276 // Verify that the number of parameters is > 0
3277 unsigned NumParams = constEval.getZExtValue();
3278 if (NumParams == 0)
3279 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3280 NParamsExpr->getSourceRange());
3281 // Verify that we have at least 1 + NumParams arguments to the builtin.
3282 if ((NumParams + 1) > NumArgs)
3283 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3284 SourceRange(BuiltinLoc, RParenLoc));
3285
3286 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003287 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003288 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003289 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3290 // UsualUnaryConversions will convert the function DeclRefExpr into a
3291 // pointer to function.
3292 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003293 const FunctionTypeProto *FnType = 0;
3294 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3295 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003296
3297 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3298 // parameters, and the number of parameters must match the value passed to
3299 // the builtin.
3300 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00003301 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
3302 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003303
3304 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003305 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003306 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003307 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003308 if (OE)
3309 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
3310 OE->getFn()->getSourceRange());
3311 // Remember our match, and continue processing the remaining arguments
3312 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003313 OE = new OverloadExpr(Args, NumArgs, i,
3314 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003315 BuiltinLoc, RParenLoc);
3316 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003317 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003318 // Return the newly created OverloadExpr node, if we succeded in matching
3319 // exactly one of the candidate functions.
3320 if (OE)
3321 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003322
3323 // If we didn't find a matching function Expr in the __builtin_overload list
3324 // the return an error.
3325 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003326 for (unsigned i = 0; i != NumParams; ++i) {
3327 if (i != 0) typeNames += ", ";
3328 typeNames += Args[i+1]->getType().getAsString();
3329 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003330
3331 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3332 SourceRange(BuiltinLoc, RParenLoc));
3333}
3334
Anders Carlsson36760332007-10-15 20:28:48 +00003335Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3336 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003337 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003338 Expr *E = static_cast<Expr*>(expr);
3339 QualType T = QualType::getFromOpaquePtr(type);
3340
3341 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003342
3343 // Get the va_list type
3344 QualType VaListType = Context.getBuiltinVaListType();
3345 // Deal with implicit array decay; for example, on x86-64,
3346 // va_list is an array, but it's supposed to decay to
3347 // a pointer for va_arg.
3348 if (VaListType->isArrayType())
3349 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003350 // Make sure the input expression also decays appropriately.
3351 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003352
3353 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003354 return Diag(E->getLocStart(),
3355 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3356 E->getType().getAsString(),
3357 E->getSourceRange());
3358
3359 // FIXME: Warn if a non-POD type is passed in.
3360
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003361 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003362}
3363
Chris Lattner005ed752008-01-04 18:04:52 +00003364bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3365 SourceLocation Loc,
3366 QualType DstType, QualType SrcType,
3367 Expr *SrcExpr, const char *Flavor) {
3368 // Decode the result (notice that AST's are still created for extensions).
3369 bool isInvalid = false;
3370 unsigned DiagKind;
3371 switch (ConvTy) {
3372 default: assert(0 && "Unknown conversion type");
3373 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003374 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003375 DiagKind = diag::ext_typecheck_convert_pointer_int;
3376 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003377 case IntToPointer:
3378 DiagKind = diag::ext_typecheck_convert_int_pointer;
3379 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003380 case IncompatiblePointer:
3381 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3382 break;
3383 case FunctionVoidPointer:
3384 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3385 break;
3386 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003387 // If the qualifiers lost were because we were applying the
3388 // (deprecated) C++ conversion from a string literal to a char*
3389 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3390 // Ideally, this check would be performed in
3391 // CheckPointerTypesForAssignment. However, that would require a
3392 // bit of refactoring (so that the second argument is an
3393 // expression, rather than a type), which should be done as part
3394 // of a larger effort to fix CheckPointerTypesForAssignment for
3395 // C++ semantics.
3396 if (getLangOptions().CPlusPlus &&
3397 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3398 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003399 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3400 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003401 case IntToBlockPointer:
3402 DiagKind = diag::err_int_to_block_pointer;
3403 break;
3404 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003405 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003406 break;
3407 case BlockVoidPointer:
3408 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3409 break;
Steve Naroff19608432008-10-14 22:18:38 +00003410 case IncompatibleObjCQualifiedId:
3411 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3412 // it can give a more specific diagnostic.
3413 DiagKind = diag::warn_incompatible_qualified_id;
3414 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003415 case Incompatible:
3416 DiagKind = diag::err_typecheck_convert_incompatible;
3417 isInvalid = true;
3418 break;
3419 }
3420
3421 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3422 SrcExpr->getSourceRange());
3423 return isInvalid;
3424}