blob: a6197dd2b75edf3e777a08c791dea16cf9ebb460 [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"
25#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026using namespace clang;
27
Chris Lattner299b8842008-07-25 21:10:04 +000028//===----------------------------------------------------------------------===//
29// Standard Promotions and Conversions
30//===----------------------------------------------------------------------===//
31
Chris Lattner299b8842008-07-25 21:10:04 +000032/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
33void Sema::DefaultFunctionArrayConversion(Expr *&E) {
34 QualType Ty = E->getType();
35 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
36
37 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
38 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
39 Ty = E->getType();
40 }
41 if (Ty->isFunctionType())
42 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000043 else if (Ty->isArrayType()) {
44 // In C90 mode, arrays only promote to pointers if the array expression is
45 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
46 // type 'array of type' is converted to an expression that has type 'pointer
47 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
48 // that has type 'array of type' ...". The relevant change is "an lvalue"
49 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000050 //
51 // C++ 4.2p1:
52 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
53 // T" can be converted to an rvalue of type "pointer to T".
54 //
55 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
56 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000057 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
58 }
Chris Lattner299b8842008-07-25 21:10:04 +000059}
60
61/// UsualUnaryConversions - Performs various conversions that are common to most
62/// operators (C99 6.3). The conversions of array and function types are
63/// sometimes surpressed. For example, the array->pointer conversion doesn't
64/// apply if the array is an argument to the sizeof or address (&) operators.
65/// In these instances, this routine should *not* be called.
66Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
67 QualType Ty = Expr->getType();
68 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
69
70 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
71 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
72 Ty = Expr->getType();
73 }
74 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
75 ImpCastExprToType(Expr, Context.IntTy);
76 else
77 DefaultFunctionArrayConversion(Expr);
78
79 return Expr;
80}
81
Chris Lattner9305c3d2008-07-25 22:25:12 +000082/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
83/// do not have a prototype. Arguments that have type float are promoted to
84/// double. All other argument types are converted by UsualUnaryConversions().
85void Sema::DefaultArgumentPromotion(Expr *&Expr) {
86 QualType Ty = Expr->getType();
87 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
88
89 // If this is a 'float' (CVR qualified or typedef) promote to double.
90 if (const BuiltinType *BT = Ty->getAsBuiltinType())
91 if (BT->getKind() == BuiltinType::Float)
92 return ImpCastExprToType(Expr, Context.DoubleTy);
93
94 UsualUnaryConversions(Expr);
95}
96
Chris Lattner299b8842008-07-25 21:10:04 +000097/// UsualArithmeticConversions - Performs various conversions that are common to
98/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
99/// routine returns the first non-arithmetic type found. The client is
100/// responsible for emitting appropriate error diagnostics.
101/// FIXME: verify the conversion rules for "complex int" are consistent with
102/// GCC.
103QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
104 bool isCompAssign) {
105 if (!isCompAssign) {
106 UsualUnaryConversions(lhsExpr);
107 UsualUnaryConversions(rhsExpr);
108 }
109 // For conversion purposes, we ignore any qualifiers.
110 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000111 QualType lhs =
112 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
113 QualType rhs =
114 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattner299b8842008-07-25 21:10:04 +0000115
116 // If both types are identical, no conversion is needed.
117 if (lhs == rhs)
118 return lhs;
119
120 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
121 // The caller can deal with this (e.g. pointer + int).
122 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
123 return lhs;
124
125 // At this point, we have two different arithmetic types.
126
127 // Handle complex types first (C99 6.3.1.8p1).
128 if (lhs->isComplexType() || rhs->isComplexType()) {
129 // if we have an integer operand, the result is the complex type.
130 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
131 // convert the rhs to the lhs complex type.
132 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
133 return lhs;
134 }
135 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
136 // convert the lhs to the rhs complex type.
137 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
138 return rhs;
139 }
140 // This handles complex/complex, complex/float, or float/complex.
141 // When both operands are complex, the shorter operand is converted to the
142 // type of the longer, and that is the type of the result. This corresponds
143 // to what is done when combining two real floating-point operands.
144 // The fun begins when size promotion occur across type domains.
145 // From H&S 6.3.4: When one operand is complex and the other is a real
146 // floating-point type, the less precise type is converted, within it's
147 // real or complex domain, to the precision of the other type. For example,
148 // when combining a "long double" with a "double _Complex", the
149 // "double _Complex" is promoted to "long double _Complex".
150 int result = Context.getFloatingTypeOrder(lhs, rhs);
151
152 if (result > 0) { // The left side is bigger, convert rhs.
153 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
154 if (!isCompAssign)
155 ImpCastExprToType(rhsExpr, rhs);
156 } else if (result < 0) { // The right side is bigger, convert lhs.
157 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
158 if (!isCompAssign)
159 ImpCastExprToType(lhsExpr, lhs);
160 }
161 // At this point, lhs and rhs have the same rank/size. Now, make sure the
162 // domains match. This is a requirement for our implementation, C99
163 // does not require this promotion.
164 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
165 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
166 if (!isCompAssign)
167 ImpCastExprToType(lhsExpr, rhs);
168 return rhs;
169 } else { // handle "_Complex double, double".
170 if (!isCompAssign)
171 ImpCastExprToType(rhsExpr, lhs);
172 return lhs;
173 }
174 }
175 return lhs; // The domain/size match exactly.
176 }
177 // Now handle "real" floating types (i.e. float, double, long double).
178 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
179 // if we have an integer operand, the result is the real floating type.
180 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
181 // convert rhs to the lhs floating point type.
182 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
183 return lhs;
184 }
185 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
186 // convert lhs to the rhs floating point type.
187 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
188 return rhs;
189 }
190 // We have two real floating types, float/complex combos were handled above.
191 // Convert the smaller operand to the bigger result.
192 int result = Context.getFloatingTypeOrder(lhs, rhs);
193
194 if (result > 0) { // convert the rhs
195 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
196 return lhs;
197 }
198 if (result < 0) { // convert the lhs
199 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
200 return rhs;
201 }
202 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
203 }
204 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
205 // Handle GCC complex int extension.
206 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
207 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
208
209 if (lhsComplexInt && rhsComplexInt) {
210 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
211 rhsComplexInt->getElementType()) >= 0) {
212 // convert the rhs
213 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
214 return lhs;
215 }
216 if (!isCompAssign)
217 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
218 return rhs;
219 } else if (lhsComplexInt && rhs->isIntegerType()) {
220 // convert the rhs to the lhs complex type.
221 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
222 return lhs;
223 } else if (rhsComplexInt && lhs->isIntegerType()) {
224 // convert the lhs to the rhs complex type.
225 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
226 return rhs;
227 }
228 }
229 // Finally, we have two differing integer types.
230 // The rules for this case are in C99 6.3.1.8
231 int compare = Context.getIntegerTypeOrder(lhs, rhs);
232 bool lhsSigned = lhs->isSignedIntegerType(),
233 rhsSigned = rhs->isSignedIntegerType();
234 QualType destType;
235 if (lhsSigned == rhsSigned) {
236 // Same signedness; use the higher-ranked type
237 destType = compare >= 0 ? lhs : rhs;
238 } else if (compare != (lhsSigned ? 1 : -1)) {
239 // The unsigned type has greater than or equal rank to the
240 // signed type, so use the unsigned type
241 destType = lhsSigned ? rhs : lhs;
242 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
243 // The two types are different widths; if we are here, that
244 // means the signed type is larger than the unsigned type, so
245 // use the signed type.
246 destType = lhsSigned ? lhs : rhs;
247 } else {
248 // The signed type is higher-ranked than the unsigned type,
249 // but isn't actually any bigger (like unsigned int and long
250 // on most 32-bit systems). Use the unsigned type corresponding
251 // to the signed type.
252 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
253 }
254 if (!isCompAssign) {
255 ImpCastExprToType(lhsExpr, destType);
256 ImpCastExprToType(rhsExpr, destType);
257 }
258 return destType;
259}
260
261//===----------------------------------------------------------------------===//
262// Semantic Analysis for various Expression Types
263//===----------------------------------------------------------------------===//
264
265
Steve Naroff87d58b42007-09-16 03:34:24 +0000266/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000267/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
268/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
269/// multiple tokens. However, the common case is that StringToks points to one
270/// string.
271///
272Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000273Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000274 assert(NumStringToks && "Must have at least one string!");
275
276 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
277 if (Literal.hadError)
278 return ExprResult(true);
279
280 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
281 for (unsigned i = 0; i != NumStringToks; ++i)
282 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000283
284 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000285 if (Literal.Pascal && Literal.GetStringLength() > 256)
286 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
287 SourceRange(StringToks[0].getLocation(),
288 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000289
Chris Lattnera6dcce32008-02-11 00:02:17 +0000290 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000291 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000292 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000293
294 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
295 if (getLangOptions().CPlusPlus)
296 StrTy.addConst();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000297
298 // Get an array type for the string, according to C99 6.4.5. This includes
299 // the nul terminator character as well as the string length for pascal
300 // strings.
301 StrTy = Context.getConstantArrayType(StrTy,
302 llvm::APInt(32, Literal.GetStringLength()+1),
303 ArrayType::Normal, 0);
304
Chris Lattner4b009652007-07-25 00:24:17 +0000305 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
306 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000307 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000308 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000309 StringToks[NumStringToks-1].getLocation());
310}
311
Steve Naroff0acc9c92007-09-15 18:49:24 +0000312/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000313/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000314/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000315Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000316 IdentifierInfo &II,
317 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000318 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +0000319 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000320
321 // If this reference is in an Objective-C method, then ivar lookup happens as
322 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000323 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000324 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000325 // There are two cases to handle here. 1) scoped lookup could have failed,
326 // in which case we should look for an ivar. 2) scoped lookup could have
327 // found a decl, but that decl is outside the current method (i.e. a global
328 // variable). In these two cases, we do a lookup for an ivar with this
329 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000330 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000331 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattnered94f762008-07-21 04:44:44 +0000332 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000333 // FIXME: This should use a new expr for a direct reference, don't turn
334 // this into Self->ivar, just return a BareIVarExpr or something.
335 IdentifierInfo &II = Context.Idents.get("self");
336 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
337 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
338 static_cast<Expr*>(SelfExpr.Val), true, true);
339 }
340 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000341 // Needed to implement property "super.method" notation.
Daniel Dunbar4837ae72008-08-14 22:04:54 +0000342 if (SD == 0 && &II == SuperID) {
Steve Naroff6f786252008-06-02 23:03:37 +0000343 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000344 getCurMethodDecl()->getClassInterface()));
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000345 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroff6f786252008-06-02 23:03:37 +0000346 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000347 }
Chris Lattner4b009652007-07-25 00:24:17 +0000348 if (D == 0) {
349 // Otherwise, this could be an implicitly declared function reference (legal
350 // in C90, extension in C99).
351 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000352 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000353 D = ImplicitlyDefineFunction(Loc, II, S);
354 else {
355 // If this name wasn't predeclared and if this is not a function call,
356 // diagnose the problem.
357 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
358 }
359 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000360
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000361 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
362 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
363 if (MD->isStatic())
364 // "invalid use of member 'x' in static member function"
365 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
366 FD->getName());
367 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
368 // "invalid use of nonstatic data member 'x'"
369 return Diag(Loc, diag::err_invalid_non_static_member_use,
370 FD->getName());
371
372 if (FD->isInvalidDecl())
373 return true;
374
375 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
376 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
377 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
378 true, FD, Loc, FD->getType());
379 }
380
381 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
382 }
Chris Lattner4b009652007-07-25 00:24:17 +0000383 if (isa<TypedefDecl>(D))
384 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000385 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000386 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000387 if (isa<NamespaceDecl>(D))
388 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000389
Steve Naroffd6163f32008-09-05 22:11:13 +0000390 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
391 ValueDecl *VD = cast<ValueDecl>(D);
392
393 // check if referencing an identifier with __attribute__((deprecated)).
394 if (VD->getAttr<DeprecatedAttr>())
395 Diag(Loc, diag::warn_deprecated, VD->getName());
396
397 // Only create DeclRefExpr's for valid Decl's.
398 if (VD->isInvalidDecl())
399 return true;
400
Steve Naroffd6163f32008-09-05 22:11:13 +0000401 // FIXME: This will create BlockDeclRefExprs for global variables,
Chris Lattner631b1352008-09-28 05:30:26 +0000402 // function references, etc which is suboptimal :) and breaks
Steve Naroffd6163f32008-09-05 22:11:13 +0000403 // things like "integer constant expression" tests.
404 //
Steve Naroff52059382008-10-10 01:28:17 +0000405 if (CurBlock && (CurBlock->TheDecl != VD->getDeclContext()) &&
406 !isa<EnumConstantDecl>(VD)) {
407 // If we are in a block and the variable is outside the current block,
408 // bind the variable reference with a BlockDeclRefExpr.
Steve Naroffd6163f32008-09-05 22:11:13 +0000409
Steve Naroff52059382008-10-10 01:28:17 +0000410 // The BlocksAttr indicates the variable is bound by-reference.
411 if (VD->getAttr<BlocksAttr>())
412 return new BlockDeclRefExpr(VD, VD->getType(), Loc, true);
413
414 // Variable will be bound by-copy, make it const within the closure.
415 VD->getType().addConst();
416 return new BlockDeclRefExpr(VD, VD->getType(), Loc, false);
417 }
418 // If this reference is not in a block or if the referenced variable is
419 // within the block, create a normal DeclRefExpr.
420 return new DeclRefExpr(VD, VD->getType(), Loc);
Chris Lattner4b009652007-07-25 00:24:17 +0000421}
422
Chris Lattner69909292008-08-10 01:53:14 +0000423Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000424 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000425 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000426
427 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000428 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000429 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
430 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
431 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000432 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000433
434 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000435 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000436 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000437
Chris Lattner7e637512008-01-12 08:14:25 +0000438 // Pre-defined identifiers are of type char[x], where x is the length of the
439 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000440 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000441 if (getCurFunctionDecl())
442 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000443 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000444 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000445
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000446 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000447 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000448 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000449 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000450}
451
Steve Naroff87d58b42007-09-16 03:34:24 +0000452Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000453 llvm::SmallString<16> CharBuffer;
454 CharBuffer.resize(Tok.getLength());
455 const char *ThisTokBegin = &CharBuffer[0];
456 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
457
458 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
459 Tok.getLocation(), PP);
460 if (Literal.hadError())
461 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000462
463 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
464
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000465 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
466 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000467}
468
Steve Naroff87d58b42007-09-16 03:34:24 +0000469Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000470 // fast path for a single digit (which is quite common). A single digit
471 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
472 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000473 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000474
Chris Lattner8cd0e932008-03-05 18:54:05 +0000475 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000476 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000477 Context.IntTy,
478 Tok.getLocation()));
479 }
480 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000481 // Add padding so that NumericLiteralParser can overread by one character.
482 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000483 const char *ThisTokBegin = &IntegerBuffer[0];
484
485 // Get the spelling of the token, which eliminates trigraphs, etc.
486 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000487
Chris Lattner4b009652007-07-25 00:24:17 +0000488 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
489 Tok.getLocation(), PP);
490 if (Literal.hadError)
491 return ExprResult(true);
492
Chris Lattner1de66eb2007-08-26 03:42:43 +0000493 Expr *Res;
494
495 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000496 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000497 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000498 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000499 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000500 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000501 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000502 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000503
504 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
505
Ted Kremenekddedbe22007-11-29 00:56:49 +0000506 // isExact will be set by GetFloatValue().
507 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000508 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000509 Ty, Tok.getLocation());
510
Chris Lattner1de66eb2007-08-26 03:42:43 +0000511 } else if (!Literal.isIntegerLiteral()) {
512 return ExprResult(true);
513 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000514 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000515
Neil Booth7421e9c2007-08-29 22:00:19 +0000516 // long long is a C99 feature.
517 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000518 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000519 Diag(Tok.getLocation(), diag::ext_longlong);
520
Chris Lattner4b009652007-07-25 00:24:17 +0000521 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000522 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000523
524 if (Literal.GetIntegerValue(ResultVal)) {
525 // If this value didn't fit into uintmax_t, warn and force to ull.
526 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000527 Ty = Context.UnsignedLongLongTy;
528 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000529 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000530 } else {
531 // If this value fits into a ULL, try to figure out what else it fits into
532 // according to the rules of C99 6.4.4.1p5.
533
534 // Octal, Hexadecimal, and integers with a U suffix are allowed to
535 // be an unsigned int.
536 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
537
538 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000539 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000540 if (!Literal.isLong && !Literal.isLongLong) {
541 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000542 unsigned IntSize = Context.Target.getIntWidth();
543
Chris Lattner4b009652007-07-25 00:24:17 +0000544 // Does it fit in a unsigned int?
545 if (ResultVal.isIntN(IntSize)) {
546 // Does it fit in a signed int?
547 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000548 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000549 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000550 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000551 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000552 }
Chris Lattner4b009652007-07-25 00:24:17 +0000553 }
554
555 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000556 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000557 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000558
559 // Does it fit in a unsigned long?
560 if (ResultVal.isIntN(LongSize)) {
561 // Does it fit in a signed long?
562 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000563 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000564 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000565 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000566 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000567 }
Chris Lattner4b009652007-07-25 00:24:17 +0000568 }
569
570 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000571 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000572 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000573
574 // Does it fit in a unsigned long long?
575 if (ResultVal.isIntN(LongLongSize)) {
576 // Does it fit in a signed long long?
577 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000578 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000579 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000580 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000581 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000582 }
583 }
584
585 // If we still couldn't decide a type, we probably have something that
586 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000587 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000588 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000589 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000590 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000591 }
Chris Lattnere4068872008-05-09 05:59:00 +0000592
593 if (ResultVal.getBitWidth() != Width)
594 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000595 }
596
Chris Lattner48d7f382008-04-02 04:24:33 +0000597 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000598 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000599
600 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
601 if (Literal.isImaginary)
602 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
603
604 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000605}
606
Steve Naroff87d58b42007-09-16 03:34:24 +0000607Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000608 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000609 Expr *E = (Expr *)Val;
610 assert((E != 0) && "ActOnParenExpr() missing expr");
611 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000612}
613
614/// The UsualUnaryConversions() function is *not* called by this routine.
615/// See C99 6.3.2.1p[2-4] for more details.
616QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerf814d882008-07-25 21:45:37 +0000617 SourceLocation OpLoc,
618 const SourceRange &ExprRange,
619 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000620 // C99 6.5.3.4p1:
621 if (isa<FunctionType>(exprType) && isSizeof)
622 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000623 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000624 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000625 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
626 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000627 else if (exprType->isIncompleteType()) {
628 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
629 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000630 exprType.getAsString(), ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000631 return QualType(); // error
632 }
633 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
634 return Context.getSizeType();
635}
636
637Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000638ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000639 SourceLocation LPLoc, TypeTy *Ty,
640 SourceLocation RPLoc) {
641 // If error parsing type, ignore.
642 if (Ty == 0) return true;
643
644 // Verify that this is a valid expression.
645 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
646
Chris Lattnerf814d882008-07-25 21:45:37 +0000647 QualType resultType =
648 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Chris Lattner4b009652007-07-25 00:24:17 +0000649
650 if (resultType.isNull())
651 return true;
652 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
653}
654
Chris Lattner5110ad52007-08-24 21:41:10 +0000655QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000656 DefaultFunctionArrayConversion(V);
657
Chris Lattnera16e42d2007-08-26 05:39:26 +0000658 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000659 if (const ComplexType *CT = V->getType()->getAsComplexType())
660 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000661
662 // Otherwise they pass through real integer and floating point types here.
663 if (V->getType()->isArithmeticType())
664 return V->getType();
665
666 // Reject anything else.
667 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
668 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000669}
670
671
Chris Lattner4b009652007-07-25 00:24:17 +0000672
Steve Naroff87d58b42007-09-16 03:34:24 +0000673Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000674 tok::TokenKind Kind,
675 ExprTy *Input) {
676 UnaryOperator::Opcode Opc;
677 switch (Kind) {
678 default: assert(0 && "Unknown unary op!");
679 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
680 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
681 }
682 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
683 if (result.isNull())
684 return true;
685 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
686}
687
688Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000689ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000690 ExprTy *Idx, SourceLocation RLoc) {
691 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
692
693 // Perform default conversions.
694 DefaultFunctionArrayConversion(LHSExp);
695 DefaultFunctionArrayConversion(RHSExp);
696
697 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
698
699 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000700 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000701 // in the subscript position. As a result, we need to derive the array base
702 // and index from the expression types.
703 Expr *BaseExpr, *IndexExpr;
704 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000705 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000706 BaseExpr = LHSExp;
707 IndexExpr = RHSExp;
708 // FIXME: need to deal with const...
709 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000710 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000711 // Handle the uncommon case of "123[Ptr]".
712 BaseExpr = RHSExp;
713 IndexExpr = LHSExp;
714 // FIXME: need to deal with const...
715 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000716 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
717 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000718 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000719
720 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000721 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
722 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000723 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000724 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000725 // FIXME: need to deal with const...
726 ResultType = VTy->getElementType();
727 } else {
728 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
729 RHSExp->getSourceRange());
730 }
731 // C99 6.5.2.1p1
732 if (!IndexExpr->getType()->isIntegerType())
733 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
734 IndexExpr->getSourceRange());
735
736 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
737 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000738 // void (*)(int)) and pointers to incomplete types. Functions are not
739 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000740 if (!ResultType->isObjectType())
741 return Diag(BaseExpr->getLocStart(),
742 diag::err_typecheck_subscript_not_object,
743 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
744
745 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
746}
747
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000748QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000749CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000750 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000751 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000752
753 // This flag determines whether or not the component is to be treated as a
754 // special name, or a regular GLSL-style component access.
755 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000756
757 // The vector accessor can't exceed the number of elements.
758 const char *compStr = CompName.getName();
759 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000760 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000761 baseType.getAsString(), SourceRange(CompLoc));
762 return QualType();
763 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000764
765 // Check that we've found one of the special components, or that the component
766 // names must come from the same set.
767 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
768 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
769 SpecialComponent = true;
770 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000771 do
772 compStr++;
773 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
774 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
775 do
776 compStr++;
777 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
778 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
779 do
780 compStr++;
781 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
782 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000783
Nate Begemanc8e51f82008-05-09 06:41:27 +0000784 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000785 // We didn't get to the end of the string. This means the component names
786 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000787 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000788 std::string(compStr,compStr+1), SourceRange(CompLoc));
789 return QualType();
790 }
791 // Each component accessor can't exceed the vector type.
792 compStr = CompName.getName();
793 while (*compStr) {
794 if (vecType->isAccessorWithinNumElements(*compStr))
795 compStr++;
796 else
797 break;
798 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000799 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000800 // We didn't get to the end of the string. This means a component accessor
801 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000802 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000803 baseType.getAsString(), SourceRange(CompLoc));
804 return QualType();
805 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000806
807 // If we have a special component name, verify that the current vector length
808 // is an even number, since all special component names return exactly half
809 // the elements.
810 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Daniel Dunbar45a91802008-09-30 17:22:47 +0000811 Diag(OpLoc, diag::err_ext_vector_component_requires_even,
812 baseType.getAsString(), SourceRange(CompLoc));
Nate Begemanc8e51f82008-05-09 06:41:27 +0000813 return QualType();
814 }
815
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000816 // The component accessor looks fine - now we need to compute the actual type.
817 // The vector type is implied by the component accessor. For example,
818 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000819 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
820 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
821 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000822 if (CompSize == 1)
823 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000824
Nate Begemanaf6ed502008-04-18 23:10:10 +0000825 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000826 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000827 // diagostics look bad. We want extended vector types to appear built-in.
828 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
829 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
830 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000831 }
832 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000833}
834
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000835/// constructSetterName - Return the setter name for the given
836/// identifier, i.e. "set" + Name where the initial character of Name
837/// has been capitalized.
838// FIXME: Merge with same routine in Parser. But where should this
839// live?
840static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
841 const IdentifierInfo *Name) {
842 unsigned N = Name->getLength();
843 char *SelectorName = new char[3 + N];
844 memcpy(SelectorName, "set", 3);
845 memcpy(&SelectorName[3], Name->getName(), N);
846 SelectorName[3] = toupper(SelectorName[3]);
847
848 IdentifierInfo *Setter =
849 &Idents.get(SelectorName, &SelectorName[3 + N]);
850 delete[] SelectorName;
851 return Setter;
852}
853
Chris Lattner4b009652007-07-25 00:24:17 +0000854Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000855ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000856 tok::TokenKind OpKind, SourceLocation MemberLoc,
857 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000858 Expr *BaseExpr = static_cast<Expr *>(Base);
859 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000860
861 // Perform default conversions.
862 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000863
Steve Naroff2cb66382007-07-26 03:11:44 +0000864 QualType BaseType = BaseExpr->getType();
865 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000866
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000867 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
868 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000869 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000870 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000871 BaseType = PT->getPointeeType();
872 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000873 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
874 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000875 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000876
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000877 // Handle field access to simple records. This also handles access to fields
878 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000879 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000880 RecordDecl *RDecl = RTy->getDecl();
881 if (RTy->isIncompleteType())
882 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
883 BaseExpr->getSourceRange());
884 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000885 FieldDecl *MemberDecl = RDecl->getMember(&Member);
886 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000887 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
888 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000889
890 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000891 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000892 QualType MemberType = MemberDecl->getType();
893 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000894 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000895 MemberType = MemberType.getQualifiedType(combinedQualifiers);
896
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000897 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000898 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000899 }
900
Chris Lattnere9d71612008-07-21 04:59:05 +0000901 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
902 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000903 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
904 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000905 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000906 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000907 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000908 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000909 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000910 }
911
Chris Lattnere9d71612008-07-21 04:59:05 +0000912 // Handle Objective-C property access, which is "Obj.property" where Obj is a
913 // pointer to a (potentially qualified) interface type.
914 const PointerType *PTy;
915 const ObjCInterfaceType *IFTy;
916 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
917 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
918 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +0000919
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000920 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +0000921 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
922 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
923
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000924 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000925 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
926 E = IFTy->qual_end(); I != E; ++I)
927 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
928 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000929
930 // If that failed, look for an "implicit" property by seeing if the nullary
931 // selector is implemented.
932
933 // FIXME: The logic for looking up nullary and unary selectors should be
934 // shared with the code in ActOnInstanceMessage.
935
936 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
937 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
938
939 // If this reference is in an @implementation, check for 'private' methods.
940 if (!Getter)
941 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
942 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
943 if (ObjCImplementationDecl *ImpDecl =
944 ObjCImplementations[ClassDecl->getIdentifier()])
945 Getter = ImpDecl->getInstanceMethod(Sel);
946
947 if (Getter) {
948 // If we found a getter then this may be a valid dot-reference, we
949 // need to also look for the matching setter.
950 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
951 &Member);
952 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
953 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
954
955 if (!Setter) {
956 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
957 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
958 if (ObjCImplementationDecl *ImpDecl =
959 ObjCImplementations[ClassDecl->getIdentifier()])
960 Setter = ImpDecl->getInstanceMethod(SetterSel);
961 }
962
963 // FIXME: There are some issues here. First, we are not
964 // diagnosing accesses to read-only properties because we do not
965 // know if this is a getter or setter yet. Second, we are
966 // checking that the type of the setter matches the type we
967 // expect.
968 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
969 MemberLoc, BaseExpr);
970 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000971 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000972
973 // Handle 'field access' to vectors, such as 'V.xx'.
974 if (BaseType->isExtVectorType() && OpKind == tok::period) {
975 // Component access limited to variables (reject vec4.rg.g).
976 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
977 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +0000978 return Diag(MemberLoc, diag::err_ext_vector_component_access,
979 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000980 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
981 if (ret.isNull())
982 return true;
983 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
984 }
985
Chris Lattner7d5a8762008-07-21 05:35:34 +0000986 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
987 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000988}
989
Steve Naroff87d58b42007-09-16 03:34:24 +0000990/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000991/// This provides the location of the left/right parens and a list of comma
992/// locations.
993Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000994ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000995 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000996 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
997 Expr *Fn = static_cast<Expr *>(fn);
998 Expr **Args = reinterpret_cast<Expr**>(args);
999 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001000 FunctionDecl *FDecl = NULL;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001001
1002 // Promote the function operand.
1003 UsualUnaryConversions(Fn);
1004
1005 // If we're directly calling a function, get the declaration for
1006 // that function.
1007 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1008 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
1009 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1010
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001011 // Make the call expr early, before semantic checks. This guarantees cleanup
1012 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001013 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001014 Context.BoolTy, RParenLoc));
Steve Naroffd6163f32008-09-05 22:11:13 +00001015 const FunctionType *FuncT;
1016 if (!Fn->getType()->isBlockPointerType()) {
1017 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1018 // have type pointer to function".
1019 const PointerType *PT = Fn->getType()->getAsPointerType();
1020 if (PT == 0)
1021 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1022 Fn->getSourceRange());
1023 FuncT = PT->getPointeeType()->getAsFunctionType();
1024 } else { // This is a block call.
1025 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1026 getAsFunctionType();
1027 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001028 if (FuncT == 0)
Chris Lattner61000b12008-08-14 04:33:24 +00001029 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1030 Fn->getSourceRange());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001031
1032 // We know the result type of the call, set it.
1033 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +00001034
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001035 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001036 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1037 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001038 unsigned NumArgsInProto = Proto->getNumArgs();
1039 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001040
Chris Lattner3e254fb2008-04-08 04:40:51 +00001041 // If too few arguments are available (and we don't have default
1042 // arguments for the remaining parameters), don't make the call.
1043 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +00001044 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001045 // Use default arguments for missing arguments
1046 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +00001047 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001048 } else
Steve Naroffd6163f32008-09-05 22:11:13 +00001049 return Diag(RParenLoc,
1050 !Fn->getType()->isBlockPointerType()
1051 ? diag::err_typecheck_call_too_few_args
1052 : diag::err_typecheck_block_too_few_args,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001053 Fn->getSourceRange());
1054 }
1055
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001056 // If too many are passed and not variadic, error on the extras and drop
1057 // them.
1058 if (NumArgs > NumArgsInProto) {
1059 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001060 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffd6163f32008-09-05 22:11:13 +00001061 !Fn->getType()->isBlockPointerType()
1062 ? diag::err_typecheck_call_too_many_args
1063 : diag::err_typecheck_block_too_many_args,
1064 Fn->getSourceRange(),
Chris Lattner4b009652007-07-25 00:24:17 +00001065 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001066 Args[NumArgs-1]->getLocEnd()));
1067 // This deletes the extra arguments.
1068 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001069 }
1070 NumArgsToCheck = NumArgsInProto;
1071 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001072
Chris Lattner4b009652007-07-25 00:24:17 +00001073 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001074 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001075 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001076
1077 Expr *Arg;
1078 if (i < NumArgs)
1079 Arg = Args[i];
1080 else
1081 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001082 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001083
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001084 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +00001085 AssignConvertType ConvTy =
1086 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001087 TheCall->setArg(i, Arg);
Eli Friedman583c31e2008-09-02 05:09:35 +00001088
Chris Lattner005ed752008-01-04 18:04:52 +00001089 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1090 ArgType, Arg, "passing"))
1091 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001092 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001093
1094 // If this is a variadic call, handle args passed through "...".
1095 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001096 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001097 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1098 Expr *Arg = Args[i];
1099 DefaultArgumentPromotion(Arg);
1100 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001101 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001102 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001103 } else {
1104 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1105
Steve Naroffdb65e052007-08-28 23:30:39 +00001106 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001107 for (unsigned i = 0; i != NumArgs; i++) {
1108 Expr *Arg = Args[i];
1109 DefaultArgumentPromotion(Arg);
1110 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001111 }
Chris Lattner4b009652007-07-25 00:24:17 +00001112 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001113
Chris Lattner2e64c072007-08-10 20:18:51 +00001114 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001115 if (FDecl)
1116 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001117
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001118 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001119}
1120
1121Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001122ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001123 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001124 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001125 QualType literalType = QualType::getFromOpaquePtr(Ty);
1126 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001127 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001128 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001129
Eli Friedman8c2173d2008-05-20 05:22:08 +00001130 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001131 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001132 return Diag(LParenLoc,
1133 diag::err_variable_object_no_init,
1134 SourceRange(LParenLoc,
1135 literalExpr->getSourceRange().getEnd()));
1136 } else if (literalType->isIncompleteType()) {
1137 return Diag(LParenLoc,
1138 diag::err_typecheck_decl_incomplete_type,
1139 literalType.getAsString(),
1140 SourceRange(LParenLoc,
1141 literalExpr->getSourceRange().getEnd()));
1142 }
1143
Steve Narofff0b23542008-01-10 22:15:12 +00001144 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +00001145 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001146
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001147 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001148 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001149 if (CheckForConstantInitializer(literalExpr, literalType))
1150 return true;
1151 }
Steve Naroffbe37fc02008-01-14 18:19:28 +00001152 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001153}
1154
1155Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001156ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001157 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001158 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001159
Steve Naroff0acc9c92007-09-15 18:49:24 +00001160 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001161 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001162
Chris Lattner48d7f382008-04-02 04:24:33 +00001163 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1164 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1165 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001166}
1167
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001168/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001169bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001170 UsualUnaryConversions(castExpr);
1171
1172 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1173 // type needs to be scalar.
1174 if (castType->isVoidType()) {
1175 // Cast to void allows any expr type.
1176 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1177 // GCC struct/union extension: allow cast to self.
1178 if (Context.getCanonicalType(castType) !=
1179 Context.getCanonicalType(castExpr->getType()) ||
1180 (!castType->isStructureType() && !castType->isUnionType())) {
1181 // Reject any other conversions to non-scalar types.
1182 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1183 castType.getAsString(), castExpr->getSourceRange());
1184 }
1185
1186 // accept this, but emit an ext-warn.
1187 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1188 castType.getAsString(), castExpr->getSourceRange());
1189 } else if (!castExpr->getType()->isScalarType() &&
1190 !castExpr->getType()->isVectorType()) {
1191 return Diag(castExpr->getLocStart(),
1192 diag::err_typecheck_expect_scalar_operand,
1193 castExpr->getType().getAsString(),castExpr->getSourceRange());
1194 } else if (castExpr->getType()->isVectorType()) {
1195 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1196 return true;
1197 } else if (castType->isVectorType()) {
1198 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1199 return true;
1200 }
1201 return false;
1202}
1203
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001204bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001205 assert(VectorTy->isVectorType() && "Not a vector type!");
1206
1207 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001208 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001209 return Diag(R.getBegin(),
1210 Ty->isVectorType() ?
1211 diag::err_invalid_conversion_between_vectors :
1212 diag::err_invalid_conversion_between_vector_and_integer,
1213 VectorTy.getAsString().c_str(),
1214 Ty.getAsString().c_str(), R);
1215 } else
1216 return Diag(R.getBegin(),
1217 diag::err_invalid_conversion_between_vector_and_scalar,
1218 VectorTy.getAsString().c_str(),
1219 Ty.getAsString().c_str(), R);
1220
1221 return false;
1222}
1223
Chris Lattner4b009652007-07-25 00:24:17 +00001224Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001225ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001226 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001227 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001228
1229 Expr *castExpr = static_cast<Expr*>(Op);
1230 QualType castType = QualType::getFromOpaquePtr(Ty);
1231
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001232 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1233 return true;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001234 return new ExplicitCastExpr(castType, castExpr, LParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001235}
1236
Chris Lattner98a425c2007-11-26 01:40:58 +00001237/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1238/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001239inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1240 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1241 UsualUnaryConversions(cond);
1242 UsualUnaryConversions(lex);
1243 UsualUnaryConversions(rex);
1244 QualType condT = cond->getType();
1245 QualType lexT = lex->getType();
1246 QualType rexT = rex->getType();
1247
1248 // first, check the condition.
1249 if (!condT->isScalarType()) { // C99 6.5.15p2
1250 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1251 condT.getAsString());
1252 return QualType();
1253 }
Chris Lattner992ae932008-01-06 22:42:25 +00001254
1255 // Now check the two expressions.
1256
1257 // If both operands have arithmetic type, do the usual arithmetic conversions
1258 // to find a common type: C99 6.5.15p3,5.
1259 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001260 UsualArithmeticConversions(lex, rex);
1261 return lex->getType();
1262 }
Chris Lattner992ae932008-01-06 22:42:25 +00001263
1264 // If both operands are the same structure or union type, the result is that
1265 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001266 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001267 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001268 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001269 // "If both the operands have structure or union type, the result has
1270 // that type." This implies that CV qualifiers are dropped.
1271 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001272 }
Chris Lattner992ae932008-01-06 22:42:25 +00001273
1274 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001275 // The following || allows only one side to be void (a GCC-ism).
1276 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001277 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001278 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1279 rex->getSourceRange());
1280 if (!rexT->isVoidType())
1281 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001282 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001283 ImpCastExprToType(lex, Context.VoidTy);
1284 ImpCastExprToType(rex, Context.VoidTy);
1285 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001286 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001287 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1288 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001289 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1290 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001291 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001292 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001293 return lexT;
1294 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001295 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1296 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001297 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001298 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001299 return rexT;
1300 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001301 // Handle the case where both operands are pointers before we handle null
1302 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001303 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1304 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1305 // get the "pointed to" types
1306 QualType lhptee = LHSPT->getPointeeType();
1307 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001308
Chris Lattner71225142007-07-31 21:27:01 +00001309 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1310 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001311 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001312 // Figure out necessary qualifiers (C99 6.5.15p6)
1313 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001314 QualType destType = Context.getPointerType(destPointee);
1315 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1316 ImpCastExprToType(rex, destType); // promote to void*
1317 return destType;
1318 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001319 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001320 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001321 QualType destType = Context.getPointerType(destPointee);
1322 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1323 ImpCastExprToType(rex, destType); // promote to void*
1324 return destType;
1325 }
Chris Lattner4b009652007-07-25 00:24:17 +00001326
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001327 QualType compositeType = lexT;
1328
1329 // If either type is an Objective-C object type then check
1330 // compatibility according to Objective-C.
1331 if (Context.isObjCObjectPointerType(lexT) ||
1332 Context.isObjCObjectPointerType(rexT)) {
1333 // If both operands are interfaces and either operand can be
1334 // assigned to the other, use that type as the composite
1335 // type. This allows
1336 // xxx ? (A*) a : (B*) b
1337 // where B is a subclass of A.
1338 //
1339 // Additionally, as for assignment, if either type is 'id'
1340 // allow silent coercion. Finally, if the types are
1341 // incompatible then make sure to use 'id' as the composite
1342 // type so the result is acceptable for sending messages to.
1343
1344 // FIXME: This code should not be localized to here. Also this
1345 // should use a compatible check instead of abusing the
1346 // canAssignObjCInterfaces code.
1347 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1348 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1349 if (LHSIface && RHSIface &&
1350 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1351 compositeType = lexT;
1352 } else if (LHSIface && RHSIface &&
1353 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1354 compositeType = rexT;
1355 } else if (Context.isObjCIdType(lhptee) ||
1356 Context.isObjCIdType(rhptee)) {
1357 // FIXME: This code looks wrong, because isObjCIdType checks
1358 // the struct but getObjCIdType returns the pointer to
1359 // struct. This is horrible and should be fixed.
1360 compositeType = Context.getObjCIdType();
1361 } else {
1362 QualType incompatTy = Context.getObjCIdType();
1363 ImpCastExprToType(lex, incompatTy);
1364 ImpCastExprToType(rex, incompatTy);
1365 return incompatTy;
1366 }
1367 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1368 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001369 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001370 lexT.getAsString(), rexT.getAsString(),
1371 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001372 // In this situation, we assume void* type. No especially good
1373 // reason, but this is what gcc does, and we do have to pick
1374 // to get a consistent AST.
1375 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001376 ImpCastExprToType(lex, incompatTy);
1377 ImpCastExprToType(rex, incompatTy);
1378 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001379 }
1380 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001381 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1382 // differently qualified versions of compatible types, the result type is
1383 // a pointer to an appropriately qualified version of the *composite*
1384 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001385 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001386 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001387 ImpCastExprToType(lex, compositeType);
1388 ImpCastExprToType(rex, compositeType);
1389 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001390 }
Chris Lattner4b009652007-07-25 00:24:17 +00001391 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001392 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1393 // evaluates to "struct objc_object *" (and is handled above when comparing
1394 // id with statically typed objects).
1395 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1396 // GCC allows qualified id and any Objective-C type to devolve to
1397 // id. Currently localizing to here until clear this should be
1398 // part of ObjCQualifiedIdTypesAreCompatible.
1399 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1400 (lexT->isObjCQualifiedIdType() &&
1401 Context.isObjCObjectPointerType(rexT)) ||
1402 (rexT->isObjCQualifiedIdType() &&
1403 Context.isObjCObjectPointerType(lexT))) {
1404 // FIXME: This is not the correct composite type. This only
1405 // happens to work because id can more or less be used anywhere,
1406 // however this may change the type of method sends.
1407 // FIXME: gcc adds some type-checking of the arguments and emits
1408 // (confusing) incompatible comparison warnings in some
1409 // cases. Investigate.
1410 QualType compositeType = Context.getObjCIdType();
1411 ImpCastExprToType(lex, compositeType);
1412 ImpCastExprToType(rex, compositeType);
1413 return compositeType;
1414 }
1415 }
1416
Steve Naroff3eac7692008-09-10 19:17:48 +00001417 // Selection between block pointer types is ok as long as they are the same.
1418 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1419 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1420 return lexT;
1421
Chris Lattner992ae932008-01-06 22:42:25 +00001422 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001423 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1424 lexT.getAsString(), rexT.getAsString(),
1425 lex->getSourceRange(), rex->getSourceRange());
1426 return QualType();
1427}
1428
Steve Naroff87d58b42007-09-16 03:34:24 +00001429/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001430/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001431Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001432 SourceLocation ColonLoc,
1433 ExprTy *Cond, ExprTy *LHS,
1434 ExprTy *RHS) {
1435 Expr *CondExpr = (Expr *) Cond;
1436 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001437
1438 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1439 // was the condition.
1440 bool isLHSNull = LHSExpr == 0;
1441 if (isLHSNull)
1442 LHSExpr = CondExpr;
1443
Chris Lattner4b009652007-07-25 00:24:17 +00001444 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1445 RHSExpr, QuestionLoc);
1446 if (result.isNull())
1447 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001448 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1449 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001450}
1451
Chris Lattner4b009652007-07-25 00:24:17 +00001452
1453// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1454// being closely modeled after the C99 spec:-). The odd characteristic of this
1455// routine is it effectively iqnores the qualifiers on the top level pointee.
1456// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1457// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001458Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001459Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1460 QualType lhptee, rhptee;
1461
1462 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001463 lhptee = lhsType->getAsPointerType()->getPointeeType();
1464 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001465
1466 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001467 lhptee = Context.getCanonicalType(lhptee);
1468 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001469
Chris Lattner005ed752008-01-04 18:04:52 +00001470 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001471
1472 // C99 6.5.16.1p1: This following citation is common to constraints
1473 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1474 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001475 // FIXME: Handle ASQualType
1476 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1477 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001478 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001479
1480 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1481 // incomplete type and the other is a pointer to a qualified or unqualified
1482 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001483 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001484 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001485 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001486
1487 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001488 assert(rhptee->isFunctionType());
1489 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001490 }
1491
1492 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001493 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001494 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001495
1496 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001497 assert(lhptee->isFunctionType());
1498 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001499 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001500
1501 // Check for ObjC interfaces
1502 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1503 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1504 if (LHSIface && RHSIface &&
1505 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1506 return ConvTy;
1507
1508 // ID acts sort of like void* for ObjC interfaces
1509 if (LHSIface && Context.isObjCIdType(rhptee))
1510 return ConvTy;
1511 if (RHSIface && Context.isObjCIdType(lhptee))
1512 return ConvTy;
1513
Chris Lattner4b009652007-07-25 00:24:17 +00001514 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1515 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001516 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1517 rhptee.getUnqualifiedType()))
1518 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001519 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001520}
1521
Steve Naroff3454b6c2008-09-04 15:10:53 +00001522/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1523/// block pointer types are compatible or whether a block and normal pointer
1524/// are compatible. It is more restrict than comparing two function pointer
1525// types.
1526Sema::AssignConvertType
1527Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1528 QualType rhsType) {
1529 QualType lhptee, rhptee;
1530
1531 // get the "pointed to" type (ignoring qualifiers at the top level)
1532 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1533 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1534
1535 // make sure we operate on the canonical type
1536 lhptee = Context.getCanonicalType(lhptee);
1537 rhptee = Context.getCanonicalType(rhptee);
1538
1539 AssignConvertType ConvTy = Compatible;
1540
1541 // For blocks we enforce that qualifiers are identical.
1542 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1543 ConvTy = CompatiblePointerDiscardsQualifiers;
1544
1545 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1546 return IncompatibleBlockPointer;
1547 return ConvTy;
1548}
1549
Chris Lattner4b009652007-07-25 00:24:17 +00001550/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1551/// has code to accommodate several GCC extensions when type checking
1552/// pointers. Here are some objectionable examples that GCC considers warnings:
1553///
1554/// int a, *pint;
1555/// short *pshort;
1556/// struct foo *pfoo;
1557///
1558/// pint = pshort; // warning: assignment from incompatible pointer type
1559/// a = pint; // warning: assignment makes integer from pointer without a cast
1560/// pint = a; // warning: assignment makes pointer from integer without a cast
1561/// pint = pfoo; // warning: assignment from incompatible pointer type
1562///
1563/// As a result, the code for dealing with pointers is more complex than the
1564/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001565///
Chris Lattner005ed752008-01-04 18:04:52 +00001566Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001567Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001568 // Get canonical types. We're not formatting these types, just comparing
1569 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001570 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1571 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001572
1573 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001574 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001575
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001576 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001577 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001578 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001579 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001580 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001581
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001582 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1583 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001584 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001585 // Relax integer conversions like we do for pointers below.
1586 if (rhsType->isIntegerType())
1587 return IntToPointer;
1588 if (lhsType->isIntegerType())
1589 return PointerToInt;
Chris Lattner1853da22008-01-04 23:18:45 +00001590 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001591 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001592
Nate Begemanc5f0f652008-07-14 18:02:46 +00001593 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001594 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001595 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1596 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001597 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001598
Nate Begemanc5f0f652008-07-14 18:02:46 +00001599 // If we are allowing lax vector conversions, and LHS and RHS are both
1600 // vectors, the total size only needs to be the same. This is a bitcast;
1601 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001602 if (getLangOptions().LaxVectorConversions &&
1603 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001604 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1605 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001606 }
1607 return Incompatible;
1608 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001609
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001610 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001611 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001612
Chris Lattner390564e2008-04-07 06:49:41 +00001613 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001614 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001615 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001616
Chris Lattner390564e2008-04-07 06:49:41 +00001617 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001618 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001619
Steve Naroffa982c712008-09-29 18:10:17 +00001620 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00001621 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff3454b6c2008-09-04 15:10:53 +00001622 return BlockVoidPointer;
Steve Naroffa982c712008-09-29 18:10:17 +00001623
1624 // Treat block pointers as objects.
1625 if (getLangOptions().ObjC1 &&
1626 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1627 return Compatible;
1628 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001629 return Incompatible;
1630 }
1631
1632 if (isa<BlockPointerType>(lhsType)) {
1633 if (rhsType->isIntegerType())
1634 return IntToPointer;
1635
Steve Naroffa982c712008-09-29 18:10:17 +00001636 // Treat block pointers as objects.
1637 if (getLangOptions().ObjC1 &&
1638 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1639 return Compatible;
1640
Steve Naroff3454b6c2008-09-04 15:10:53 +00001641 if (rhsType->isBlockPointerType())
1642 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1643
1644 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1645 if (RHSPT->getPointeeType()->isVoidType())
1646 return BlockVoidPointer;
1647 }
Chris Lattner1853da22008-01-04 23:18:45 +00001648 return Incompatible;
1649 }
1650
Chris Lattner390564e2008-04-07 06:49:41 +00001651 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001652 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001653 if (lhsType == Context.BoolTy)
1654 return Compatible;
1655
1656 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001657 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001658
Chris Lattner390564e2008-04-07 06:49:41 +00001659 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001660 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001661
1662 if (isa<BlockPointerType>(lhsType) &&
1663 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1664 return BlockVoidPointer;
Chris Lattner1853da22008-01-04 23:18:45 +00001665 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001666 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001667
Chris Lattner1853da22008-01-04 23:18:45 +00001668 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001669 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001670 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001671 }
1672 return Incompatible;
1673}
1674
Chris Lattner005ed752008-01-04 18:04:52 +00001675Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001676Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001677 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1678 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00001679 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1680 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001681 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001682 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001683 return Compatible;
1684 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001685
1686 // We don't allow conversion of non-null-pointer constants to integers.
1687 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1688 return IntToBlockPointer;
1689
Chris Lattner5f505bf2007-10-16 02:55:40 +00001690 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001691 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001692 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001693 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001694 //
1695 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1696 // are better understood.
1697 if (!lhsType->isReferenceType())
1698 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001699
Chris Lattner005ed752008-01-04 18:04:52 +00001700 Sema::AssignConvertType result =
1701 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001702
1703 // C99 6.5.16.1p2: The value of the right operand is converted to the
1704 // type of the assignment expression.
1705 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001706 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001707 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001708}
1709
Chris Lattner005ed752008-01-04 18:04:52 +00001710Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001711Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1712 return CheckAssignmentConstraints(lhsType, rhsType);
1713}
1714
Chris Lattner2c8bff72007-12-12 05:47:28 +00001715QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001716 Diag(loc, diag::err_typecheck_invalid_operands,
1717 lex->getType().getAsString(), rex->getType().getAsString(),
1718 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001719 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001720}
1721
1722inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1723 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001724 // For conversion purposes, we ignore any qualifiers.
1725 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001726 QualType lhsType =
1727 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1728 QualType rhsType =
1729 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001730
Nate Begemanc5f0f652008-07-14 18:02:46 +00001731 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001732 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001733 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001734
Nate Begemanc5f0f652008-07-14 18:02:46 +00001735 // Handle the case of a vector & extvector type of the same size and element
1736 // type. It would be nice if we only had one vector type someday.
1737 if (getLangOptions().LaxVectorConversions)
1738 if (const VectorType *LV = lhsType->getAsVectorType())
1739 if (const VectorType *RV = rhsType->getAsVectorType())
1740 if (LV->getElementType() == RV->getElementType() &&
1741 LV->getNumElements() == RV->getNumElements())
1742 return lhsType->isExtVectorType() ? lhsType : rhsType;
1743
1744 // If the lhs is an extended vector and the rhs is a scalar of the same type
1745 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001746 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001747 QualType eltType = V->getElementType();
1748
1749 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1750 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1751 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001752 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001753 return lhsType;
1754 }
1755 }
1756
Nate Begemanc5f0f652008-07-14 18:02:46 +00001757 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001758 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001759 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001760 QualType eltType = V->getElementType();
1761
1762 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1763 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1764 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001765 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001766 return rhsType;
1767 }
1768 }
1769
Chris Lattner4b009652007-07-25 00:24:17 +00001770 // You cannot convert between vector values of different size.
1771 Diag(loc, diag::err_typecheck_vector_not_convertable,
1772 lex->getType().getAsString(), rex->getType().getAsString(),
1773 lex->getSourceRange(), rex->getSourceRange());
1774 return QualType();
1775}
1776
1777inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001778 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001779{
1780 QualType lhsType = lex->getType(), rhsType = rex->getType();
1781
1782 if (lhsType->isVectorType() || rhsType->isVectorType())
1783 return CheckVectorOperands(loc, lex, rex);
1784
Steve Naroff8f708362007-08-24 19:07:16 +00001785 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001786
Chris Lattner4b009652007-07-25 00:24:17 +00001787 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001788 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001789 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001790}
1791
1792inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001793 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001794{
1795 QualType lhsType = lex->getType(), rhsType = rex->getType();
1796
Steve Naroff8f708362007-08-24 19:07:16 +00001797 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001798
Chris Lattner4b009652007-07-25 00:24:17 +00001799 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001800 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001801 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001802}
1803
1804inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001805 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001806{
1807 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1808 return CheckVectorOperands(loc, lex, rex);
1809
Steve Naroff8f708362007-08-24 19:07:16 +00001810 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001811
Chris Lattner4b009652007-07-25 00:24:17 +00001812 // handle the common case first (both operands are arithmetic).
1813 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001814 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001815
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001816 // Put any potential pointer into PExp
1817 Expr* PExp = lex, *IExp = rex;
1818 if (IExp->getType()->isPointerType())
1819 std::swap(PExp, IExp);
1820
1821 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1822 if (IExp->getType()->isIntegerType()) {
1823 // Check for arithmetic on pointers to incomplete types
1824 if (!PTy->getPointeeType()->isObjectType()) {
1825 if (PTy->getPointeeType()->isVoidType()) {
1826 Diag(loc, diag::ext_gnu_void_ptr,
1827 lex->getSourceRange(), rex->getSourceRange());
1828 } else {
1829 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1830 lex->getType().getAsString(), lex->getSourceRange());
1831 return QualType();
1832 }
1833 }
1834 return PExp->getType();
1835 }
1836 }
1837
Chris Lattner2c8bff72007-12-12 05:47:28 +00001838 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001839}
1840
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001841// C99 6.5.6
1842QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1843 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001844 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1845 return CheckVectorOperands(loc, lex, rex);
1846
Steve Naroff8f708362007-08-24 19:07:16 +00001847 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001848
Chris Lattnerf6da2912007-12-09 21:53:25 +00001849 // Enforce type constraints: C99 6.5.6p3.
1850
1851 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001852 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001853 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001854
1855 // Either ptr - int or ptr - ptr.
1856 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001857 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001858
Chris Lattnerf6da2912007-12-09 21:53:25 +00001859 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001860 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001861 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001862 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001863 Diag(loc, diag::ext_gnu_void_ptr,
1864 lex->getSourceRange(), rex->getSourceRange());
1865 } else {
1866 Diag(loc, diag::err_typecheck_sub_ptr_object,
1867 lex->getType().getAsString(), lex->getSourceRange());
1868 return QualType();
1869 }
1870 }
1871
1872 // The result type of a pointer-int computation is the pointer type.
1873 if (rex->getType()->isIntegerType())
1874 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001875
Chris Lattnerf6da2912007-12-09 21:53:25 +00001876 // Handle pointer-pointer subtractions.
1877 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001878 QualType rpointee = RHSPTy->getPointeeType();
1879
Chris Lattnerf6da2912007-12-09 21:53:25 +00001880 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001881 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001882 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001883 if (rpointee->isVoidType()) {
1884 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001885 Diag(loc, diag::ext_gnu_void_ptr,
1886 lex->getSourceRange(), rex->getSourceRange());
1887 } else {
1888 Diag(loc, diag::err_typecheck_sub_ptr_object,
1889 rex->getType().getAsString(), rex->getSourceRange());
1890 return QualType();
1891 }
1892 }
1893
1894 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00001895 if (!Context.typesAreCompatible(
1896 Context.getCanonicalType(lpointee).getUnqualifiedType(),
1897 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001898 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1899 lex->getType().getAsString(), rex->getType().getAsString(),
1900 lex->getSourceRange(), rex->getSourceRange());
1901 return QualType();
1902 }
1903
1904 return Context.getPointerDiffType();
1905 }
1906 }
1907
Chris Lattner2c8bff72007-12-12 05:47:28 +00001908 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001909}
1910
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001911// C99 6.5.7
1912QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1913 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00001914 // C99 6.5.7p2: Each of the operands shall have integer type.
1915 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1916 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001917
Chris Lattner2c8bff72007-12-12 05:47:28 +00001918 // Shifts don't perform usual arithmetic conversions, they just do integer
1919 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001920 if (!isCompAssign)
1921 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001922 UsualUnaryConversions(rex);
1923
1924 // "The type of the result is that of the promoted left operand."
1925 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001926}
1927
Eli Friedman0d9549b2008-08-22 00:56:42 +00001928static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
1929 ASTContext& Context) {
1930 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
1931 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
1932 // ID acts sort of like void* for ObjC interfaces
1933 if (LHSIface && Context.isObjCIdType(RHS))
1934 return true;
1935 if (RHSIface && Context.isObjCIdType(LHS))
1936 return true;
1937 if (!LHSIface || !RHSIface)
1938 return false;
1939 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
1940 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
1941}
1942
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001943// C99 6.5.8
1944QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1945 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001946 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1947 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1948
Chris Lattner254f3bc2007-08-26 01:18:55 +00001949 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001950 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1951 UsualArithmeticConversions(lex, rex);
1952 else {
1953 UsualUnaryConversions(lex);
1954 UsualUnaryConversions(rex);
1955 }
Chris Lattner4b009652007-07-25 00:24:17 +00001956 QualType lType = lex->getType();
1957 QualType rType = rex->getType();
1958
Ted Kremenek486509e2007-10-29 17:13:39 +00001959 // For non-floating point types, check for self-comparisons of the form
1960 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1961 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001962 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001963 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1964 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001965 if (DRL->getDecl() == DRR->getDecl())
1966 Diag(loc, diag::warn_selfcomparison);
1967 }
1968
Chris Lattner254f3bc2007-08-26 01:18:55 +00001969 if (isRelational) {
1970 if (lType->isRealType() && rType->isRealType())
1971 return Context.IntTy;
1972 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001973 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001974 if (lType->isFloatingType()) {
1975 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001976 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001977 }
1978
Chris Lattner254f3bc2007-08-26 01:18:55 +00001979 if (lType->isArithmeticType() && rType->isArithmeticType())
1980 return Context.IntTy;
1981 }
Chris Lattner4b009652007-07-25 00:24:17 +00001982
Chris Lattner22be8422007-08-26 01:10:14 +00001983 bool LHSIsNull = lex->isNullPointerConstant(Context);
1984 bool RHSIsNull = rex->isNullPointerConstant(Context);
1985
Chris Lattner254f3bc2007-08-26 01:18:55 +00001986 // All of the following pointer related warnings are GCC extensions, except
1987 // when handling null pointer constants. One day, we can consider making them
1988 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001989 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001990 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001991 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00001992 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001993 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00001994
Steve Naroff3b435622007-11-13 14:57:38 +00001995 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001996 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1997 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00001998 RCanPointeeTy.getUnqualifiedType()) &&
1999 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroff4462cb02007-08-16 21:48:38 +00002000 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2001 lType.getAsString(), rType.getAsString(),
2002 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002003 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002004 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002005 return Context.IntTy;
2006 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002007 // Handle block pointer types.
2008 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2009 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2010 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2011
2012 if (!LHSIsNull && !RHSIsNull &&
2013 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2014 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2015 lType.getAsString(), rType.getAsString(),
2016 lex->getSourceRange(), rex->getSourceRange());
2017 }
2018 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2019 return Context.IntTy;
2020 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002021 // Allow block pointers to be compared with null pointer constants.
2022 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2023 (lType->isPointerType() && rType->isBlockPointerType())) {
2024 if (!LHSIsNull && !RHSIsNull) {
2025 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2026 lType.getAsString(), rType.getAsString(),
2027 lex->getSourceRange(), rex->getSourceRange());
2028 }
2029 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2030 return Context.IntTy;
2031 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002032
Steve Naroff936c4362008-06-03 14:04:54 +00002033 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
2034 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2035 ImpCastExprToType(rex, lType);
2036 return Context.IntTy;
2037 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002038 }
Steve Naroff936c4362008-06-03 14:04:54 +00002039 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2040 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002041 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002042 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2043 lType.getAsString(), rType.getAsString(),
2044 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002045 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002046 return Context.IntTy;
2047 }
Steve Naroff936c4362008-06-03 14:04:54 +00002048 if (lType->isIntegerType() &&
2049 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002050 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002051 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2052 lType.getAsString(), rType.getAsString(),
2053 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002054 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002055 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002056 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002057 // Handle block pointers.
2058 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2059 if (!RHSIsNull)
2060 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2061 lType.getAsString(), rType.getAsString(),
2062 lex->getSourceRange(), rex->getSourceRange());
2063 ImpCastExprToType(rex, lType); // promote the integer to pointer
2064 return Context.IntTy;
2065 }
2066 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2067 if (!LHSIsNull)
2068 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2069 lType.getAsString(), rType.getAsString(),
2070 lex->getSourceRange(), rex->getSourceRange());
2071 ImpCastExprToType(lex, rType); // promote the integer to pointer
2072 return Context.IntTy;
2073 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00002074 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002075}
2076
Nate Begemanc5f0f652008-07-14 18:02:46 +00002077/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2078/// operates on extended vector types. Instead of producing an IntTy result,
2079/// like a scalar comparison, a vector comparison produces a vector of integer
2080/// types.
2081QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2082 SourceLocation loc,
2083 bool isRelational) {
2084 // Check to make sure we're operating on vectors of the same type and width,
2085 // Allowing one side to be a scalar of element type.
2086 QualType vType = CheckVectorOperands(loc, lex, rex);
2087 if (vType.isNull())
2088 return vType;
2089
2090 QualType lType = lex->getType();
2091 QualType rType = rex->getType();
2092
2093 // For non-floating point types, check for self-comparisons of the form
2094 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2095 // often indicate logic errors in the program.
2096 if (!lType->isFloatingType()) {
2097 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2098 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2099 if (DRL->getDecl() == DRR->getDecl())
2100 Diag(loc, diag::warn_selfcomparison);
2101 }
2102
2103 // Check for comparisons of floating point operands using != and ==.
2104 if (!isRelational && lType->isFloatingType()) {
2105 assert (rType->isFloatingType());
2106 CheckFloatComparison(loc,lex,rex);
2107 }
2108
2109 // Return the type for the comparison, which is the same as vector type for
2110 // integer vectors, or an integer type of identical size and number of
2111 // elements for floating point vectors.
2112 if (lType->isIntegerType())
2113 return lType;
2114
2115 const VectorType *VTy = lType->getAsVectorType();
2116
2117 // FIXME: need to deal with non-32b int / non-64b long long
2118 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2119 if (TypeSize == 32) {
2120 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2121 }
2122 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2123 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2124}
2125
Chris Lattner4b009652007-07-25 00:24:17 +00002126inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00002127 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002128{
2129 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2130 return CheckVectorOperands(loc, lex, rex);
2131
Steve Naroff8f708362007-08-24 19:07:16 +00002132 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002133
2134 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002135 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002136 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002137}
2138
2139inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
2140 Expr *&lex, Expr *&rex, SourceLocation loc)
2141{
2142 UsualUnaryConversions(lex);
2143 UsualUnaryConversions(rex);
2144
Eli Friedmanbea3f842008-05-13 20:16:47 +00002145 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002146 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002147 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002148}
2149
2150inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00002151 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00002152{
2153 QualType lhsType = lex->getType();
2154 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner25168a52008-07-26 21:30:36 +00002155 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002156
2157 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00002158 case Expr::MLV_Valid:
2159 break;
2160 case Expr::MLV_ConstQualified:
2161 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2162 return QualType();
2163 case Expr::MLV_ArrayType:
2164 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2165 lhsType.getAsString(), lex->getSourceRange());
2166 return QualType();
2167 case Expr::MLV_NotObjectType:
2168 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2169 lhsType.getAsString(), lex->getSourceRange());
2170 return QualType();
2171 case Expr::MLV_InvalidExpression:
2172 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2173 lex->getSourceRange());
2174 return QualType();
2175 case Expr::MLV_IncompleteType:
2176 case Expr::MLV_IncompleteVoidType:
2177 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2178 lhsType.getAsString(), lex->getSourceRange());
2179 return QualType();
2180 case Expr::MLV_DuplicateVectorComponents:
2181 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2182 lex->getSourceRange());
2183 return QualType();
Steve Naroff076d6cb2008-09-26 14:41:28 +00002184 case Expr::MLV_NotBlockQualified:
2185 Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2186 lex->getSourceRange());
2187 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002188 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002189
Chris Lattner005ed752008-01-04 18:04:52 +00002190 AssignConvertType ConvTy;
Chris Lattner34c85082008-08-21 18:04:13 +00002191 if (compoundType.isNull()) {
2192 // Simple assignment "x = y".
Chris Lattner005ed752008-01-04 18:04:52 +00002193 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner34c85082008-08-21 18:04:13 +00002194
2195 // If the RHS is a unary plus or minus, check to see if they = and + are
2196 // right next to each other. If so, the user may have typo'd "x =+ 4"
2197 // instead of "x += 4".
2198 Expr *RHSCheck = rex;
2199 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2200 RHSCheck = ICE->getSubExpr();
2201 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2202 if ((UO->getOpcode() == UnaryOperator::Plus ||
2203 UO->getOpcode() == UnaryOperator::Minus) &&
2204 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2205 // Only if the two operators are exactly adjacent.
2206 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2207 Diag(loc, diag::warn_not_compound_assign,
2208 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2209 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2210 }
2211 } else {
2212 // Compound assignment "x += y"
Chris Lattner005ed752008-01-04 18:04:52 +00002213 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner34c85082008-08-21 18:04:13 +00002214 }
Chris Lattner005ed752008-01-04 18:04:52 +00002215
2216 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2217 rex, "assigning"))
2218 return QualType();
2219
Chris Lattner4b009652007-07-25 00:24:17 +00002220 // C99 6.5.16p3: The type of an assignment expression is the type of the
2221 // left operand unless the left operand has qualified type, in which case
2222 // it is the unqualified version of the type of the left operand.
2223 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2224 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002225 // C++ 5.17p1: the type of the assignment expression is that of its left
2226 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00002227 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002228}
2229
2230inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2231 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00002232
2233 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2234 DefaultFunctionArrayConversion(rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002235 return rex->getType();
2236}
2237
2238/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2239/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2240QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2241 QualType resType = op->getType();
2242 assert(!resType.isNull() && "no type for increment/decrement expression");
2243
Steve Naroffd30e1932007-08-24 17:20:07 +00002244 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00002245 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002246 if (pt->getPointeeType()->isVoidType()) {
2247 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2248 } else if (!pt->getPointeeType()->isObjectType()) {
2249 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00002250 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2251 resType.getAsString(), op->getSourceRange());
2252 return QualType();
2253 }
Steve Naroffd30e1932007-08-24 17:20:07 +00002254 } else if (!resType->isRealType()) {
2255 if (resType->isComplexType())
2256 // C99 does not support ++/-- on complex types.
2257 Diag(OpLoc, diag::ext_integer_increment_complex,
2258 resType.getAsString(), op->getSourceRange());
2259 else {
2260 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2261 resType.getAsString(), op->getSourceRange());
2262 return QualType();
2263 }
Chris Lattner4b009652007-07-25 00:24:17 +00002264 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002265 // At this point, we know we have a real, complex or pointer type.
2266 // Now make sure the operand is a modifiable lvalue.
Chris Lattner25168a52008-07-26 21:30:36 +00002267 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002268 if (mlval != Expr::MLV_Valid) {
2269 // FIXME: emit a more precise diagnostic...
2270 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2271 op->getSourceRange());
2272 return QualType();
2273 }
2274 return resType;
2275}
2276
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002277/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002278/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002279/// where the declaration is needed for type checking. We only need to
2280/// handle cases when the expression references a function designator
2281/// or is an lvalue. Here are some examples:
2282/// - &(x) => x
2283/// - &*****f => f for f a function designator.
2284/// - &s.xx => s
2285/// - &s.zz[1].yy -> s, if zz is an array
2286/// - *(x + 1) -> x, if x is an array
2287/// - &"123"[2] -> 0
2288/// - & __real__ x -> x
Chris Lattner48d7f382008-04-02 04:24:33 +00002289static ValueDecl *getPrimaryDecl(Expr *E) {
2290 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002291 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002292 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002293 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002294 // Fields cannot be declared with a 'register' storage class.
2295 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002296 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002297 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002298 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002299 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002300 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002301
Chris Lattner48d7f382008-04-02 04:24:33 +00002302 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00002303 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002304 return 0;
2305 else
2306 return VD;
2307 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002308 case Stmt::UnaryOperatorClass: {
2309 UnaryOperator *UO = cast<UnaryOperator>(E);
2310
2311 switch(UO->getOpcode()) {
2312 case UnaryOperator::Deref: {
2313 // *(X + 1) refers to X if X is not a pointer.
2314 ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2315 if (!VD || VD->getType()->isPointerType())
2316 return 0;
2317 return VD;
2318 }
2319 case UnaryOperator::Real:
2320 case UnaryOperator::Imag:
2321 case UnaryOperator::Extension:
2322 return getPrimaryDecl(UO->getSubExpr());
2323 default:
2324 return 0;
2325 }
2326 }
2327 case Stmt::BinaryOperatorClass: {
2328 BinaryOperator *BO = cast<BinaryOperator>(E);
2329
2330 // Handle cases involving pointer arithmetic. The result of an
2331 // Assign or AddAssign is not an lvalue so they can be ignored.
2332
2333 // (x + n) or (n + x) => x
2334 if (BO->getOpcode() == BinaryOperator::Add) {
2335 if (BO->getLHS()->getType()->isPointerType()) {
2336 return getPrimaryDecl(BO->getLHS());
2337 } else if (BO->getRHS()->getType()->isPointerType()) {
2338 return getPrimaryDecl(BO->getRHS());
2339 }
2340 }
2341
2342 return 0;
2343 }
Chris Lattner4b009652007-07-25 00:24:17 +00002344 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002345 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002346 case Stmt::ImplicitCastExprClass:
2347 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002348 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002349 default:
2350 return 0;
2351 }
2352}
2353
2354/// CheckAddressOfOperand - The operand of & must be either a function
2355/// designator or an lvalue designating an object. If it is an lvalue, the
2356/// object cannot be declared with storage class register or be a bit field.
2357/// Note: The usual conversions are *not* applied to the operand of the &
2358/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2359QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002360 if (getLangOptions().C99) {
2361 // Implement C99-only parts of addressof rules.
2362 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2363 if (uOp->getOpcode() == UnaryOperator::Deref)
2364 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2365 // (assuming the deref expression is valid).
2366 return uOp->getSubExpr()->getType();
2367 }
2368 // Technically, there should be a check for array subscript
2369 // expressions here, but the result of one is always an lvalue anyway.
2370 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002371 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002372 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002373
2374 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002375 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2376 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002377 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2378 op->getSourceRange());
2379 return QualType();
2380 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002381 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2382 if (MemExpr->getMemberDecl()->isBitField()) {
2383 Diag(OpLoc, diag::err_typecheck_address_of,
2384 std::string("bit-field"), op->getSourceRange());
2385 return QualType();
2386 }
2387 // Check for Apple extension for accessing vector components.
2388 } else if (isa<ArraySubscriptExpr>(op) &&
2389 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2390 Diag(OpLoc, diag::err_typecheck_address_of,
2391 std::string("vector"), op->getSourceRange());
2392 return QualType();
2393 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002394 // We have an lvalue with a decl. Make sure the decl is not declared
2395 // with the register storage-class specifier.
2396 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2397 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002398 Diag(OpLoc, diag::err_typecheck_address_of,
2399 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002400 return QualType();
2401 }
2402 } else
2403 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002404 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002405
Chris Lattner4b009652007-07-25 00:24:17 +00002406 // If the operand has type "type", the result has type "pointer to type".
2407 return Context.getPointerType(op->getType());
2408}
2409
2410QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2411 UsualUnaryConversions(op);
2412 QualType qType = op->getType();
2413
Chris Lattner7931f4a2007-07-31 16:53:04 +00002414 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002415 // Note that per both C89 and C99, this is always legal, even
2416 // if ptype is an incomplete type or void.
2417 // It would be possible to warn about dereferencing a
2418 // void pointer, but it's completely well-defined,
2419 // and such a warning is unlikely to catch any mistakes.
2420 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002421 }
2422 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2423 qType.getAsString(), op->getSourceRange());
2424 return QualType();
2425}
2426
2427static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2428 tok::TokenKind Kind) {
2429 BinaryOperator::Opcode Opc;
2430 switch (Kind) {
2431 default: assert(0 && "Unknown binop!");
2432 case tok::star: Opc = BinaryOperator::Mul; break;
2433 case tok::slash: Opc = BinaryOperator::Div; break;
2434 case tok::percent: Opc = BinaryOperator::Rem; break;
2435 case tok::plus: Opc = BinaryOperator::Add; break;
2436 case tok::minus: Opc = BinaryOperator::Sub; break;
2437 case tok::lessless: Opc = BinaryOperator::Shl; break;
2438 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2439 case tok::lessequal: Opc = BinaryOperator::LE; break;
2440 case tok::less: Opc = BinaryOperator::LT; break;
2441 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2442 case tok::greater: Opc = BinaryOperator::GT; break;
2443 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2444 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2445 case tok::amp: Opc = BinaryOperator::And; break;
2446 case tok::caret: Opc = BinaryOperator::Xor; break;
2447 case tok::pipe: Opc = BinaryOperator::Or; break;
2448 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2449 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2450 case tok::equal: Opc = BinaryOperator::Assign; break;
2451 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2452 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2453 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2454 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2455 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2456 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2457 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2458 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2459 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2460 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2461 case tok::comma: Opc = BinaryOperator::Comma; break;
2462 }
2463 return Opc;
2464}
2465
2466static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2467 tok::TokenKind Kind) {
2468 UnaryOperator::Opcode Opc;
2469 switch (Kind) {
2470 default: assert(0 && "Unknown unary op!");
2471 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2472 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2473 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2474 case tok::star: Opc = UnaryOperator::Deref; break;
2475 case tok::plus: Opc = UnaryOperator::Plus; break;
2476 case tok::minus: Opc = UnaryOperator::Minus; break;
2477 case tok::tilde: Opc = UnaryOperator::Not; break;
2478 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2479 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2480 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2481 case tok::kw___real: Opc = UnaryOperator::Real; break;
2482 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2483 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2484 }
2485 return Opc;
2486}
2487
2488// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002489Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002490 ExprTy *LHS, ExprTy *RHS) {
2491 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2492 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2493
Steve Naroff87d58b42007-09-16 03:34:24 +00002494 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2495 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002496
2497 QualType ResultTy; // Result type of the binary operator.
2498 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2499
2500 switch (Opc) {
2501 default:
2502 assert(0 && "Unknown binary expr!");
2503 case BinaryOperator::Assign:
2504 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2505 break;
2506 case BinaryOperator::Mul:
2507 case BinaryOperator::Div:
2508 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2509 break;
2510 case BinaryOperator::Rem:
2511 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2512 break;
2513 case BinaryOperator::Add:
2514 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2515 break;
2516 case BinaryOperator::Sub:
2517 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2518 break;
2519 case BinaryOperator::Shl:
2520 case BinaryOperator::Shr:
2521 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2522 break;
2523 case BinaryOperator::LE:
2524 case BinaryOperator::LT:
2525 case BinaryOperator::GE:
2526 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002527 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002528 break;
2529 case BinaryOperator::EQ:
2530 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002531 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00002532 break;
2533 case BinaryOperator::And:
2534 case BinaryOperator::Xor:
2535 case BinaryOperator::Or:
2536 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2537 break;
2538 case BinaryOperator::LAnd:
2539 case BinaryOperator::LOr:
2540 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2541 break;
2542 case BinaryOperator::MulAssign:
2543 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002544 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002545 if (!CompTy.isNull())
2546 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2547 break;
2548 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002549 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002550 if (!CompTy.isNull())
2551 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2552 break;
2553 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002554 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002555 if (!CompTy.isNull())
2556 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2557 break;
2558 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002559 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002560 if (!CompTy.isNull())
2561 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2562 break;
2563 case BinaryOperator::ShlAssign:
2564 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002565 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002566 if (!CompTy.isNull())
2567 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2568 break;
2569 case BinaryOperator::AndAssign:
2570 case BinaryOperator::XorAssign:
2571 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002572 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002573 if (!CompTy.isNull())
2574 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2575 break;
2576 case BinaryOperator::Comma:
2577 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2578 break;
2579 }
2580 if (ResultTy.isNull())
2581 return true;
2582 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00002583 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002584 else
Chris Lattnerf420df12007-08-28 18:36:55 +00002585 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002586}
2587
2588// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002589Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002590 ExprTy *input) {
2591 Expr *Input = (Expr*)input;
2592 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2593 QualType resultType;
2594 switch (Opc) {
2595 default:
2596 assert(0 && "Unimplemented unary expr!");
2597 case UnaryOperator::PreInc:
2598 case UnaryOperator::PreDec:
2599 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2600 break;
2601 case UnaryOperator::AddrOf:
2602 resultType = CheckAddressOfOperand(Input, OpLoc);
2603 break;
2604 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002605 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002606 resultType = CheckIndirectionOperand(Input, OpLoc);
2607 break;
2608 case UnaryOperator::Plus:
2609 case UnaryOperator::Minus:
2610 UsualUnaryConversions(Input);
2611 resultType = Input->getType();
2612 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2613 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2614 resultType.getAsString());
2615 break;
2616 case UnaryOperator::Not: // bitwise complement
2617 UsualUnaryConversions(Input);
2618 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002619 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2620 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2621 // C99 does not support '~' for complex conjugation.
2622 Diag(OpLoc, diag::ext_integer_complement_complex,
2623 resultType.getAsString(), Input->getSourceRange());
2624 else if (!resultType->isIntegerType())
2625 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2626 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002627 break;
2628 case UnaryOperator::LNot: // logical negation
2629 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2630 DefaultFunctionArrayConversion(Input);
2631 resultType = Input->getType();
2632 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2633 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2634 resultType.getAsString());
2635 // LNot always has type int. C99 6.5.3.3p5.
2636 resultType = Context.IntTy;
2637 break;
2638 case UnaryOperator::SizeOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002639 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2640 Input->getSourceRange(), true);
Chris Lattner4b009652007-07-25 00:24:17 +00002641 break;
2642 case UnaryOperator::AlignOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002643 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2644 Input->getSourceRange(), false);
Chris Lattner4b009652007-07-25 00:24:17 +00002645 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002646 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002647 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002648 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002649 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002650 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002651 resultType = Input->getType();
2652 break;
2653 }
2654 if (resultType.isNull())
2655 return true;
2656 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2657}
2658
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002659/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2660Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002661 SourceLocation LabLoc,
2662 IdentifierInfo *LabelII) {
2663 // Look up the record for this label identifier.
2664 LabelStmt *&LabelDecl = LabelMap[LabelII];
2665
Daniel Dunbar879788d2008-08-04 16:51:22 +00002666 // If we haven't seen this label yet, create a forward reference. It
2667 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00002668 if (LabelDecl == 0)
2669 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2670
2671 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002672 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2673 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002674}
2675
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002676Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002677 SourceLocation RPLoc) { // "({..})"
2678 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2679 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2680 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2681
2682 // FIXME: there are a variety of strange constraints to enforce here, for
2683 // example, it is not possible to goto into a stmt expression apparently.
2684 // More semantic analysis is needed.
2685
2686 // FIXME: the last statement in the compount stmt has its value used. We
2687 // should not warn about it being unused.
2688
2689 // If there are sub stmts in the compound stmt, take the type of the last one
2690 // as the type of the stmtexpr.
2691 QualType Ty = Context.VoidTy;
2692
Chris Lattner200964f2008-07-26 19:51:01 +00002693 if (!Compound->body_empty()) {
2694 Stmt *LastStmt = Compound->body_back();
2695 // If LastStmt is a label, skip down through into the body.
2696 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2697 LastStmt = Label->getSubStmt();
2698
2699 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00002700 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00002701 }
Chris Lattner4b009652007-07-25 00:24:17 +00002702
2703 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2704}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002705
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002706Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002707 SourceLocation TypeLoc,
2708 TypeTy *argty,
2709 OffsetOfComponent *CompPtr,
2710 unsigned NumComponents,
2711 SourceLocation RPLoc) {
2712 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2713 assert(!ArgTy.isNull() && "Missing type argument!");
2714
2715 // We must have at least one component that refers to the type, and the first
2716 // one is known to be a field designator. Verify that the ArgTy represents
2717 // a struct/union/class.
2718 if (!ArgTy->isRecordType())
2719 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2720
2721 // Otherwise, create a compound literal expression as the base, and
2722 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002723 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002724
Chris Lattnerb37522e2007-08-31 21:49:13 +00002725 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2726 // GCC extension, diagnose them.
2727 if (NumComponents != 1)
2728 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2729 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2730
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002731 for (unsigned i = 0; i != NumComponents; ++i) {
2732 const OffsetOfComponent &OC = CompPtr[i];
2733 if (OC.isBrackets) {
2734 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00002735 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002736 if (!AT) {
2737 delete Res;
2738 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2739 Res->getType().getAsString());
2740 }
2741
Chris Lattner2af6a802007-08-30 17:59:59 +00002742 // FIXME: C++: Verify that operator[] isn't overloaded.
2743
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002744 // C99 6.5.2.1p1
2745 Expr *Idx = static_cast<Expr*>(OC.U.E);
2746 if (!Idx->getType()->isIntegerType())
2747 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2748 Idx->getSourceRange());
2749
2750 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2751 continue;
2752 }
2753
2754 const RecordType *RC = Res->getType()->getAsRecordType();
2755 if (!RC) {
2756 delete Res;
2757 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2758 Res->getType().getAsString());
2759 }
2760
2761 // Get the decl corresponding to this.
2762 RecordDecl *RD = RC->getDecl();
2763 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2764 if (!MemberDecl)
2765 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2766 OC.U.IdentInfo->getName(),
2767 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002768
2769 // FIXME: C++: Verify that MemberDecl isn't a static field.
2770 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002771 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2772 // matter here.
2773 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002774 }
2775
2776 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2777 BuiltinLoc);
2778}
2779
2780
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002781Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002782 TypeTy *arg1, TypeTy *arg2,
2783 SourceLocation RPLoc) {
2784 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2785 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2786
2787 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2788
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002789 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002790}
2791
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002792Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002793 ExprTy *expr1, ExprTy *expr2,
2794 SourceLocation RPLoc) {
2795 Expr *CondExpr = static_cast<Expr*>(cond);
2796 Expr *LHSExpr = static_cast<Expr*>(expr1);
2797 Expr *RHSExpr = static_cast<Expr*>(expr2);
2798
2799 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2800
2801 // The conditional expression is required to be a constant expression.
2802 llvm::APSInt condEval(32);
2803 SourceLocation ExpLoc;
2804 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2805 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2806 CondExpr->getSourceRange());
2807
2808 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2809 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2810 RHSExpr->getType();
2811 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2812}
2813
Steve Naroff52a81c02008-09-03 18:15:37 +00002814//===----------------------------------------------------------------------===//
2815// Clang Extensions.
2816//===----------------------------------------------------------------------===//
2817
2818/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00002819void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00002820 // Analyze block parameters.
2821 BlockSemaInfo *BSI = new BlockSemaInfo();
2822
2823 // Add BSI to CurBlock.
2824 BSI->PrevBlockInfo = CurBlock;
2825 CurBlock = BSI;
2826
2827 BSI->ReturnType = 0;
2828 BSI->TheScope = BlockScope;
2829
Steve Naroff52059382008-10-10 01:28:17 +00002830 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
2831 PushDeclContext(BSI->TheDecl);
2832}
2833
2834void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00002835 // Analyze arguments to block.
2836 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2837 "Not a function declarator!");
2838 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2839
Steve Naroff52059382008-10-10 01:28:17 +00002840 CurBlock->hasPrototype = FTI.hasPrototype;
2841 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00002842
2843 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2844 // no arguments, not a function that takes a single void argument.
2845 if (FTI.hasPrototype &&
2846 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2847 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2848 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2849 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00002850 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00002851 } else if (FTI.hasPrototype) {
2852 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00002853 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2854 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00002855 }
Steve Naroff52059382008-10-10 01:28:17 +00002856 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
2857
2858 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
2859 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
2860 // If this has an identifier, add it to the scope stack.
2861 if ((*AI)->getIdentifier())
2862 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00002863}
2864
2865/// ActOnBlockError - If there is an error parsing a block, this callback
2866/// is invoked to pop the information about the block from the action impl.
2867void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
2868 // Ensure that CurBlock is deleted.
2869 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
2870
2871 // Pop off CurBlock, handle nested blocks.
2872 CurBlock = CurBlock->PrevBlockInfo;
2873
2874 // FIXME: Delete the ParmVarDecl objects as well???
2875
2876}
2877
2878/// ActOnBlockStmtExpr - This is called when the body of a block statement
2879/// literal was successfully completed. ^(int x){...}
2880Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
2881 Scope *CurScope) {
2882 // Ensure that CurBlock is deleted.
2883 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2884 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
2885
Steve Naroff52059382008-10-10 01:28:17 +00002886 PopDeclContext();
2887
Steve Naroff52a81c02008-09-03 18:15:37 +00002888 // Pop off CurBlock, handle nested blocks.
2889 CurBlock = CurBlock->PrevBlockInfo;
2890
2891 QualType RetTy = Context.VoidTy;
2892 if (BSI->ReturnType)
2893 RetTy = QualType(BSI->ReturnType, 0);
2894
2895 llvm::SmallVector<QualType, 8> ArgTypes;
2896 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
2897 ArgTypes.push_back(BSI->Params[i]->getType());
2898
2899 QualType BlockTy;
2900 if (!BSI->hasPrototype)
2901 BlockTy = Context.getFunctionTypeNoProto(RetTy);
2902 else
2903 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
2904 BSI->isVariadic);
2905
2906 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00002907
Steve Naroff95029d92008-10-08 18:44:00 +00002908 BSI->TheDecl->setBody(Body.take());
2909 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00002910}
2911
Nate Begemanbd881ef2008-01-30 20:50:20 +00002912/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002913/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002914/// The number of arguments has already been validated to match the number of
2915/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002916static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2917 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002918 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00002919 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002920 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2921 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00002922
2923 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002924 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00002925 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002926 return true;
2927}
2928
2929Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2930 SourceLocation *CommaLocs,
2931 SourceLocation BuiltinLoc,
2932 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002933 // __builtin_overload requires at least 2 arguments
2934 if (NumArgs < 2)
2935 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2936 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002937
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002938 // The first argument is required to be a constant expression. It tells us
2939 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002940 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002941 Expr *NParamsExpr = Args[0];
2942 llvm::APSInt constEval(32);
2943 SourceLocation ExpLoc;
2944 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2945 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2946 NParamsExpr->getSourceRange());
2947
2948 // Verify that the number of parameters is > 0
2949 unsigned NumParams = constEval.getZExtValue();
2950 if (NumParams == 0)
2951 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2952 NParamsExpr->getSourceRange());
2953 // Verify that we have at least 1 + NumParams arguments to the builtin.
2954 if ((NumParams + 1) > NumArgs)
2955 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2956 SourceRange(BuiltinLoc, RParenLoc));
2957
2958 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002959 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002960 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002961 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2962 // UsualUnaryConversions will convert the function DeclRefExpr into a
2963 // pointer to function.
2964 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002965 const FunctionTypeProto *FnType = 0;
2966 if (const PointerType *PT = Fn->getType()->getAsPointerType())
2967 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002968
2969 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2970 // parameters, and the number of parameters must match the value passed to
2971 // the builtin.
2972 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002973 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2974 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002975
2976 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002977 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002978 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002979 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002980 if (OE)
2981 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2982 OE->getFn()->getSourceRange());
2983 // Remember our match, and continue processing the remaining arguments
2984 // to catch any errors.
2985 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2986 BuiltinLoc, RParenLoc);
2987 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002988 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002989 // Return the newly created OverloadExpr node, if we succeded in matching
2990 // exactly one of the candidate functions.
2991 if (OE)
2992 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002993
2994 // If we didn't find a matching function Expr in the __builtin_overload list
2995 // the return an error.
2996 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002997 for (unsigned i = 0; i != NumParams; ++i) {
2998 if (i != 0) typeNames += ", ";
2999 typeNames += Args[i+1]->getType().getAsString();
3000 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003001
3002 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3003 SourceRange(BuiltinLoc, RParenLoc));
3004}
3005
Anders Carlsson36760332007-10-15 20:28:48 +00003006Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3007 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003008 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003009 Expr *E = static_cast<Expr*>(expr);
3010 QualType T = QualType::getFromOpaquePtr(type);
3011
3012 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003013
3014 // Get the va_list type
3015 QualType VaListType = Context.getBuiltinVaListType();
3016 // Deal with implicit array decay; for example, on x86-64,
3017 // va_list is an array, but it's supposed to decay to
3018 // a pointer for va_arg.
3019 if (VaListType->isArrayType())
3020 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003021 // Make sure the input expression also decays appropriately.
3022 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003023
3024 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003025 return Diag(E->getLocStart(),
3026 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3027 E->getType().getAsString(),
3028 E->getSourceRange());
3029
3030 // FIXME: Warn if a non-POD type is passed in.
3031
3032 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
3033}
3034
Chris Lattner005ed752008-01-04 18:04:52 +00003035bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3036 SourceLocation Loc,
3037 QualType DstType, QualType SrcType,
3038 Expr *SrcExpr, const char *Flavor) {
3039 // Decode the result (notice that AST's are still created for extensions).
3040 bool isInvalid = false;
3041 unsigned DiagKind;
3042 switch (ConvTy) {
3043 default: assert(0 && "Unknown conversion type");
3044 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003045 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003046 DiagKind = diag::ext_typecheck_convert_pointer_int;
3047 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003048 case IntToPointer:
3049 DiagKind = diag::ext_typecheck_convert_int_pointer;
3050 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003051 case IncompatiblePointer:
3052 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3053 break;
3054 case FunctionVoidPointer:
3055 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3056 break;
3057 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003058 // If the qualifiers lost were because we were applying the
3059 // (deprecated) C++ conversion from a string literal to a char*
3060 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3061 // Ideally, this check would be performed in
3062 // CheckPointerTypesForAssignment. However, that would require a
3063 // bit of refactoring (so that the second argument is an
3064 // expression, rather than a type), which should be done as part
3065 // of a larger effort to fix CheckPointerTypesForAssignment for
3066 // C++ semantics.
3067 if (getLangOptions().CPlusPlus &&
3068 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3069 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003070 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3071 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003072 case IntToBlockPointer:
3073 DiagKind = diag::err_int_to_block_pointer;
3074 break;
3075 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003076 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003077 break;
3078 case BlockVoidPointer:
3079 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3080 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003081 case Incompatible:
3082 DiagKind = diag::err_typecheck_convert_incompatible;
3083 isInvalid = true;
3084 break;
3085 }
3086
3087 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3088 SrcExpr->getSourceRange());
3089 return isInvalid;
3090}