blob: b7d5c8e12c0e5a10d8c81c55de2bd91eef610915 [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 Naroffd6163f32008-09-05 22:11:13 +0000312/// DeclDefinedWithinScope - Return true if the specified decl is defined at or
313/// within the 'Within' scope. The current Scope is CurScope.
314///
315/// NOTE: This method is extremely inefficient (linear scan), this should not be
316/// used in common cases.
317///
318static bool DeclDefinedWithinScope(ScopedDecl *D, Scope *Within,
319 Scope *CurScope) {
320 while (1) {
321 assert(CurScope && "CurScope not nested within 'Within'?");
322
323 // Check this scope for the decl.
324 if (CurScope->isDeclScope(D)) return true;
325
326 if (CurScope == Within) return false;
327 CurScope = CurScope->getParent();
328 }
329}
Chris Lattner4b009652007-07-25 00:24:17 +0000330
Steve Naroff0acc9c92007-09-15 18:49:24 +0000331/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000332/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000333/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000334Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000335 IdentifierInfo &II,
336 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000337 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +0000338 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000339
340 // If this reference is in an Objective-C method, then ivar lookup happens as
341 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000342 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000343 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000344 // There are two cases to handle here. 1) scoped lookup could have failed,
345 // in which case we should look for an ivar. 2) scoped lookup could have
346 // found a decl, but that decl is outside the current method (i.e. a global
347 // variable). In these two cases, we do a lookup for an ivar with this
348 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000349 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000350 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattnered94f762008-07-21 04:44:44 +0000351 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000352 // FIXME: This should use a new expr for a direct reference, don't turn
353 // this into Self->ivar, just return a BareIVarExpr or something.
354 IdentifierInfo &II = Context.Idents.get("self");
355 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
356 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
357 static_cast<Expr*>(SelfExpr.Val), true, true);
358 }
359 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000360 // Needed to implement property "super.method" notation.
Daniel Dunbar4837ae72008-08-14 22:04:54 +0000361 if (SD == 0 && &II == SuperID) {
Steve Naroff6f786252008-06-02 23:03:37 +0000362 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000363 getCurMethodDecl()->getClassInterface()));
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000364 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroff6f786252008-06-02 23:03:37 +0000365 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000366 }
Steve Naroff4d1b93d2008-09-10 18:33:00 +0000367 // If we are parsing a block, check the block parameter list.
368 if (CurBlock) {
369 for (unsigned i = 0, e = CurBlock->Params.size(); i != e; ++i)
370 if (CurBlock->Params[i]->getIdentifier() == &II)
371 D = CurBlock->Params[i];
372 }
Chris Lattner4b009652007-07-25 00:24:17 +0000373 if (D == 0) {
374 // Otherwise, this could be an implicitly declared function reference (legal
375 // in C90, extension in C99).
376 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000377 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000378 D = ImplicitlyDefineFunction(Loc, II, S);
379 else {
380 // If this name wasn't predeclared and if this is not a function call,
381 // diagnose the problem.
382 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
383 }
384 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000385
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000386 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
387 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
388 if (MD->isStatic())
389 // "invalid use of member 'x' in static member function"
390 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
391 FD->getName());
392 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
393 // "invalid use of nonstatic data member 'x'"
394 return Diag(Loc, diag::err_invalid_non_static_member_use,
395 FD->getName());
396
397 if (FD->isInvalidDecl())
398 return true;
399
400 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
401 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
402 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
403 true, FD, Loc, FD->getType());
404 }
405
406 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
407 }
Chris Lattner4b009652007-07-25 00:24:17 +0000408 if (isa<TypedefDecl>(D))
409 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000410 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000411 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000412 if (isa<NamespaceDecl>(D))
413 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000414
Steve Naroffd6163f32008-09-05 22:11:13 +0000415 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
416 ValueDecl *VD = cast<ValueDecl>(D);
417
418 // check if referencing an identifier with __attribute__((deprecated)).
419 if (VD->getAttr<DeprecatedAttr>())
420 Diag(Loc, diag::warn_deprecated, VD->getName());
421
422 // Only create DeclRefExpr's for valid Decl's.
423 if (VD->isInvalidDecl())
424 return true;
425
426 // If this reference is not in a block or if the referenced variable is
427 // within the block, create a normal DeclRefExpr.
428 //
429 // FIXME: This will create BlockDeclRefExprs for global variables,
430 // function references, enums constants, etc which is suboptimal :) and breaks
431 // things like "integer constant expression" tests.
432 //
433 if (!CurBlock || DeclDefinedWithinScope(VD, CurBlock->TheScope, S))
434 return new DeclRefExpr(VD, VD->getType(), Loc);
435
436 // If we are in a block and the variable is outside the current block,
437 // bind the variable reference with a BlockDeclRefExpr.
438
439 // If the variable is in the byref set, bind it directly, otherwise it will be
440 // bound by-copy, thus we make it const within the closure.
441 if (!CurBlock->ByRefVars.count(VD))
442 VD->getType().addConst();
443
444 return new BlockDeclRefExpr(VD, VD->getType(), Loc, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000445}
446
Chris Lattner69909292008-08-10 01:53:14 +0000447Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000448 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000449 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000450
451 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000452 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000453 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
454 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
455 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000456 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000457
458 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000459 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000460 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000461
Chris Lattner7e637512008-01-12 08:14:25 +0000462 // Pre-defined identifiers are of type char[x], where x is the length of the
463 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000464 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000465 if (getCurFunctionDecl())
466 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000467 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000468 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000469
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000470 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000471 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000472 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000473 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000474}
475
Steve Naroff87d58b42007-09-16 03:34:24 +0000476Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000477 llvm::SmallString<16> CharBuffer;
478 CharBuffer.resize(Tok.getLength());
479 const char *ThisTokBegin = &CharBuffer[0];
480 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
481
482 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
483 Tok.getLocation(), PP);
484 if (Literal.hadError())
485 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000486
487 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
488
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000489 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
490 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000491}
492
Steve Naroff87d58b42007-09-16 03:34:24 +0000493Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000494 // fast path for a single digit (which is quite common). A single digit
495 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
496 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000497 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000498
Chris Lattner8cd0e932008-03-05 18:54:05 +0000499 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000500 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000501 Context.IntTy,
502 Tok.getLocation()));
503 }
504 llvm::SmallString<512> IntegerBuffer;
505 IntegerBuffer.resize(Tok.getLength());
506 const char *ThisTokBegin = &IntegerBuffer[0];
507
508 // Get the spelling of the token, which eliminates trigraphs, etc.
509 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
510 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
511 Tok.getLocation(), PP);
512 if (Literal.hadError)
513 return ExprResult(true);
514
Chris Lattner1de66eb2007-08-26 03:42:43 +0000515 Expr *Res;
516
517 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000518 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000519 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000520 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000521 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000522 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000523 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000524 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000525
526 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
527
Ted Kremenekddedbe22007-11-29 00:56:49 +0000528 // isExact will be set by GetFloatValue().
529 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000530 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000531 Ty, Tok.getLocation());
532
Chris Lattner1de66eb2007-08-26 03:42:43 +0000533 } else if (!Literal.isIntegerLiteral()) {
534 return ExprResult(true);
535 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000536 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000537
Neil Booth7421e9c2007-08-29 22:00:19 +0000538 // long long is a C99 feature.
539 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000540 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000541 Diag(Tok.getLocation(), diag::ext_longlong);
542
Chris Lattner4b009652007-07-25 00:24:17 +0000543 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000544 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000545
546 if (Literal.GetIntegerValue(ResultVal)) {
547 // If this value didn't fit into uintmax_t, warn and force to ull.
548 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000549 Ty = Context.UnsignedLongLongTy;
550 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000551 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000552 } else {
553 // If this value fits into a ULL, try to figure out what else it fits into
554 // according to the rules of C99 6.4.4.1p5.
555
556 // Octal, Hexadecimal, and integers with a U suffix are allowed to
557 // be an unsigned int.
558 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
559
560 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000561 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000562 if (!Literal.isLong && !Literal.isLongLong) {
563 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000564 unsigned IntSize = Context.Target.getIntWidth();
565
Chris Lattner4b009652007-07-25 00:24:17 +0000566 // Does it fit in a unsigned int?
567 if (ResultVal.isIntN(IntSize)) {
568 // Does it fit in a signed int?
569 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000570 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000571 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000572 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000573 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000574 }
Chris Lattner4b009652007-07-25 00:24:17 +0000575 }
576
577 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000578 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000579 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000580
581 // Does it fit in a unsigned long?
582 if (ResultVal.isIntN(LongSize)) {
583 // Does it fit in a signed long?
584 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000585 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000586 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000587 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000588 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000589 }
Chris Lattner4b009652007-07-25 00:24:17 +0000590 }
591
592 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000593 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000594 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000595
596 // Does it fit in a unsigned long long?
597 if (ResultVal.isIntN(LongLongSize)) {
598 // Does it fit in a signed long long?
599 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000600 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000601 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000602 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000603 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000604 }
605 }
606
607 // If we still couldn't decide a type, we probably have something that
608 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000609 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000610 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000611 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000612 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000613 }
Chris Lattnere4068872008-05-09 05:59:00 +0000614
615 if (ResultVal.getBitWidth() != Width)
616 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000617 }
618
Chris Lattner48d7f382008-04-02 04:24:33 +0000619 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000620 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000621
622 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
623 if (Literal.isImaginary)
624 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
625
626 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000627}
628
Steve Naroff87d58b42007-09-16 03:34:24 +0000629Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000630 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000631 Expr *E = (Expr *)Val;
632 assert((E != 0) && "ActOnParenExpr() missing expr");
633 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000634}
635
636/// The UsualUnaryConversions() function is *not* called by this routine.
637/// See C99 6.3.2.1p[2-4] for more details.
638QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerf814d882008-07-25 21:45:37 +0000639 SourceLocation OpLoc,
640 const SourceRange &ExprRange,
641 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000642 // C99 6.5.3.4p1:
643 if (isa<FunctionType>(exprType) && isSizeof)
644 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000645 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000646 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000647 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
648 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000649 else if (exprType->isIncompleteType()) {
650 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
651 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000652 exprType.getAsString(), ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000653 return QualType(); // error
654 }
655 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
656 return Context.getSizeType();
657}
658
659Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000660ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000661 SourceLocation LPLoc, TypeTy *Ty,
662 SourceLocation RPLoc) {
663 // If error parsing type, ignore.
664 if (Ty == 0) return true;
665
666 // Verify that this is a valid expression.
667 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
668
Chris Lattnerf814d882008-07-25 21:45:37 +0000669 QualType resultType =
670 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Chris Lattner4b009652007-07-25 00:24:17 +0000671
672 if (resultType.isNull())
673 return true;
674 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
675}
676
Chris Lattner5110ad52007-08-24 21:41:10 +0000677QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000678 DefaultFunctionArrayConversion(V);
679
Chris Lattnera16e42d2007-08-26 05:39:26 +0000680 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000681 if (const ComplexType *CT = V->getType()->getAsComplexType())
682 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000683
684 // Otherwise they pass through real integer and floating point types here.
685 if (V->getType()->isArithmeticType())
686 return V->getType();
687
688 // Reject anything else.
689 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
690 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000691}
692
693
Chris Lattner4b009652007-07-25 00:24:17 +0000694
Steve Naroff87d58b42007-09-16 03:34:24 +0000695Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000696 tok::TokenKind Kind,
697 ExprTy *Input) {
698 UnaryOperator::Opcode Opc;
699 switch (Kind) {
700 default: assert(0 && "Unknown unary op!");
701 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
702 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
703 }
704 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
705 if (result.isNull())
706 return true;
707 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
708}
709
710Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000711ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000712 ExprTy *Idx, SourceLocation RLoc) {
713 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
714
715 // Perform default conversions.
716 DefaultFunctionArrayConversion(LHSExp);
717 DefaultFunctionArrayConversion(RHSExp);
718
719 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
720
721 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000722 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000723 // in the subscript position. As a result, we need to derive the array base
724 // and index from the expression types.
725 Expr *BaseExpr, *IndexExpr;
726 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000727 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000728 BaseExpr = LHSExp;
729 IndexExpr = RHSExp;
730 // FIXME: need to deal with const...
731 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000732 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000733 // Handle the uncommon case of "123[Ptr]".
734 BaseExpr = RHSExp;
735 IndexExpr = LHSExp;
736 // FIXME: need to deal with const...
737 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000738 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
739 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000740 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000741
742 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000743 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
744 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000745 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000746 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000747 // FIXME: need to deal with const...
748 ResultType = VTy->getElementType();
749 } else {
750 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
751 RHSExp->getSourceRange());
752 }
753 // C99 6.5.2.1p1
754 if (!IndexExpr->getType()->isIntegerType())
755 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
756 IndexExpr->getSourceRange());
757
758 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
759 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000760 // void (*)(int)) and pointers to incomplete types. Functions are not
761 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000762 if (!ResultType->isObjectType())
763 return Diag(BaseExpr->getLocStart(),
764 diag::err_typecheck_subscript_not_object,
765 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
766
767 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
768}
769
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000770QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000771CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000772 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000773 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000774
775 // This flag determines whether or not the component is to be treated as a
776 // special name, or a regular GLSL-style component access.
777 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000778
779 // The vector accessor can't exceed the number of elements.
780 const char *compStr = CompName.getName();
781 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000782 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000783 baseType.getAsString(), SourceRange(CompLoc));
784 return QualType();
785 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000786
787 // Check that we've found one of the special components, or that the component
788 // names must come from the same set.
789 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
790 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
791 SpecialComponent = true;
792 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000793 do
794 compStr++;
795 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
796 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
797 do
798 compStr++;
799 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
800 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
801 do
802 compStr++;
803 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
804 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000805
Nate Begemanc8e51f82008-05-09 06:41:27 +0000806 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000807 // We didn't get to the end of the string. This means the component names
808 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000809 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000810 std::string(compStr,compStr+1), SourceRange(CompLoc));
811 return QualType();
812 }
813 // Each component accessor can't exceed the vector type.
814 compStr = CompName.getName();
815 while (*compStr) {
816 if (vecType->isAccessorWithinNumElements(*compStr))
817 compStr++;
818 else
819 break;
820 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000821 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000822 // We didn't get to the end of the string. This means a component accessor
823 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000824 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000825 baseType.getAsString(), SourceRange(CompLoc));
826 return QualType();
827 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000828
829 // If we have a special component name, verify that the current vector length
830 // is an even number, since all special component names return exactly half
831 // the elements.
832 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
833 return QualType();
834 }
835
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000836 // The component accessor looks fine - now we need to compute the actual type.
837 // The vector type is implied by the component accessor. For example,
838 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000839 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
840 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
841 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000842 if (CompSize == 1)
843 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000844
Nate Begemanaf6ed502008-04-18 23:10:10 +0000845 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000846 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000847 // diagostics look bad. We want extended vector types to appear built-in.
848 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
849 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
850 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000851 }
852 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000853}
854
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000855/// constructSetterName - Return the setter name for the given
856/// identifier, i.e. "set" + Name where the initial character of Name
857/// has been capitalized.
858// FIXME: Merge with same routine in Parser. But where should this
859// live?
860static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
861 const IdentifierInfo *Name) {
862 unsigned N = Name->getLength();
863 char *SelectorName = new char[3 + N];
864 memcpy(SelectorName, "set", 3);
865 memcpy(&SelectorName[3], Name->getName(), N);
866 SelectorName[3] = toupper(SelectorName[3]);
867
868 IdentifierInfo *Setter =
869 &Idents.get(SelectorName, &SelectorName[3 + N]);
870 delete[] SelectorName;
871 return Setter;
872}
873
Chris Lattner4b009652007-07-25 00:24:17 +0000874Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000875ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000876 tok::TokenKind OpKind, SourceLocation MemberLoc,
877 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000878 Expr *BaseExpr = static_cast<Expr *>(Base);
879 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000880
881 // Perform default conversions.
882 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000883
Steve Naroff2cb66382007-07-26 03:11:44 +0000884 QualType BaseType = BaseExpr->getType();
885 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000886
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000887 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
888 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000889 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000890 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000891 BaseType = PT->getPointeeType();
892 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000893 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
894 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000895 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000896
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000897 // Handle field access to simple records. This also handles access to fields
898 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000899 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000900 RecordDecl *RDecl = RTy->getDecl();
901 if (RTy->isIncompleteType())
902 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
903 BaseExpr->getSourceRange());
904 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000905 FieldDecl *MemberDecl = RDecl->getMember(&Member);
906 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000907 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
908 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000909
910 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000911 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000912 QualType MemberType = MemberDecl->getType();
913 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000914 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000915 MemberType = MemberType.getQualifiedType(combinedQualifiers);
916
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000917 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000918 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000919 }
920
Chris Lattnere9d71612008-07-21 04:59:05 +0000921 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
922 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000923 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
924 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000925 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000926 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000927 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000928 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000929 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000930 }
931
Chris Lattnere9d71612008-07-21 04:59:05 +0000932 // Handle Objective-C property access, which is "Obj.property" where Obj is a
933 // pointer to a (potentially qualified) interface type.
934 const PointerType *PTy;
935 const ObjCInterfaceType *IFTy;
936 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
937 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
938 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +0000939
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000940 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +0000941 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
942 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
943
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000944 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000945 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
946 E = IFTy->qual_end(); I != E; ++I)
947 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
948 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000949
950 // If that failed, look for an "implicit" property by seeing if the nullary
951 // selector is implemented.
952
953 // FIXME: The logic for looking up nullary and unary selectors should be
954 // shared with the code in ActOnInstanceMessage.
955
956 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
957 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
958
959 // If this reference is in an @implementation, check for 'private' methods.
960 if (!Getter)
961 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
962 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
963 if (ObjCImplementationDecl *ImpDecl =
964 ObjCImplementations[ClassDecl->getIdentifier()])
965 Getter = ImpDecl->getInstanceMethod(Sel);
966
967 if (Getter) {
968 // If we found a getter then this may be a valid dot-reference, we
969 // need to also look for the matching setter.
970 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
971 &Member);
972 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
973 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
974
975 if (!Setter) {
976 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
977 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
978 if (ObjCImplementationDecl *ImpDecl =
979 ObjCImplementations[ClassDecl->getIdentifier()])
980 Setter = ImpDecl->getInstanceMethod(SetterSel);
981 }
982
983 // FIXME: There are some issues here. First, we are not
984 // diagnosing accesses to read-only properties because we do not
985 // know if this is a getter or setter yet. Second, we are
986 // checking that the type of the setter matches the type we
987 // expect.
988 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
989 MemberLoc, BaseExpr);
990 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000991 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000992
993 // Handle 'field access' to vectors, such as 'V.xx'.
994 if (BaseType->isExtVectorType() && OpKind == tok::period) {
995 // Component access limited to variables (reject vec4.rg.g).
996 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
997 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +0000998 return Diag(MemberLoc, diag::err_ext_vector_component_access,
999 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001000 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1001 if (ret.isNull())
1002 return true;
1003 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1004 }
1005
Chris Lattner7d5a8762008-07-21 05:35:34 +00001006 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1007 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001008}
1009
Steve Naroff87d58b42007-09-16 03:34:24 +00001010/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001011/// This provides the location of the left/right parens and a list of comma
1012/// locations.
1013Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001014ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001015 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001016 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1017 Expr *Fn = static_cast<Expr *>(fn);
1018 Expr **Args = reinterpret_cast<Expr**>(args);
1019 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001020 FunctionDecl *FDecl = NULL;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001021
1022 // Promote the function operand.
1023 UsualUnaryConversions(Fn);
1024
1025 // If we're directly calling a function, get the declaration for
1026 // that function.
1027 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1028 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
1029 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1030
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001031 // Make the call expr early, before semantic checks. This guarantees cleanup
1032 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001033 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001034 Context.BoolTy, RParenLoc));
Steve Naroffd6163f32008-09-05 22:11:13 +00001035 const FunctionType *FuncT;
1036 if (!Fn->getType()->isBlockPointerType()) {
1037 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1038 // have type pointer to function".
1039 const PointerType *PT = Fn->getType()->getAsPointerType();
1040 if (PT == 0)
1041 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1042 Fn->getSourceRange());
1043 FuncT = PT->getPointeeType()->getAsFunctionType();
1044 } else { // This is a block call.
1045 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1046 getAsFunctionType();
1047 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001048 if (FuncT == 0)
Chris Lattner61000b12008-08-14 04:33:24 +00001049 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1050 Fn->getSourceRange());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001051
1052 // We know the result type of the call, set it.
1053 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +00001054
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001055 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001056 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1057 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001058 unsigned NumArgsInProto = Proto->getNumArgs();
1059 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001060
Chris Lattner3e254fb2008-04-08 04:40:51 +00001061 // If too few arguments are available (and we don't have default
1062 // arguments for the remaining parameters), don't make the call.
1063 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +00001064 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001065 // Use default arguments for missing arguments
1066 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +00001067 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001068 } else
Steve Naroffd6163f32008-09-05 22:11:13 +00001069 return Diag(RParenLoc,
1070 !Fn->getType()->isBlockPointerType()
1071 ? diag::err_typecheck_call_too_few_args
1072 : diag::err_typecheck_block_too_few_args,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001073 Fn->getSourceRange());
1074 }
1075
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001076 // If too many are passed and not variadic, error on the extras and drop
1077 // them.
1078 if (NumArgs > NumArgsInProto) {
1079 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001080 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffd6163f32008-09-05 22:11:13 +00001081 !Fn->getType()->isBlockPointerType()
1082 ? diag::err_typecheck_call_too_many_args
1083 : diag::err_typecheck_block_too_many_args,
1084 Fn->getSourceRange(),
Chris Lattner4b009652007-07-25 00:24:17 +00001085 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001086 Args[NumArgs-1]->getLocEnd()));
1087 // This deletes the extra arguments.
1088 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001089 }
1090 NumArgsToCheck = NumArgsInProto;
1091 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001092
Chris Lattner4b009652007-07-25 00:24:17 +00001093 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001094 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001095 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001096
1097 Expr *Arg;
1098 if (i < NumArgs)
1099 Arg = Args[i];
1100 else
1101 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001102 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001103
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001104 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +00001105 AssignConvertType ConvTy =
1106 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001107 TheCall->setArg(i, Arg);
Eli Friedman583c31e2008-09-02 05:09:35 +00001108
Chris Lattner005ed752008-01-04 18:04:52 +00001109 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1110 ArgType, Arg, "passing"))
1111 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001112 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001113
1114 // If this is a variadic call, handle args passed through "...".
1115 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001116 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001117 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1118 Expr *Arg = Args[i];
1119 DefaultArgumentPromotion(Arg);
1120 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001121 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001122 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001123 } else {
1124 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1125
Steve Naroffdb65e052007-08-28 23:30:39 +00001126 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001127 for (unsigned i = 0; i != NumArgs; i++) {
1128 Expr *Arg = Args[i];
1129 DefaultArgumentPromotion(Arg);
1130 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001131 }
Chris Lattner4b009652007-07-25 00:24:17 +00001132 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001133
Chris Lattner2e64c072007-08-10 20:18:51 +00001134 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001135 if (FDecl)
1136 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001137
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001138 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001139}
1140
1141Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001142ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001143 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001144 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001145 QualType literalType = QualType::getFromOpaquePtr(Ty);
1146 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001147 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001148 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001149
Eli Friedman8c2173d2008-05-20 05:22:08 +00001150 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001151 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001152 return Diag(LParenLoc,
1153 diag::err_variable_object_no_init,
1154 SourceRange(LParenLoc,
1155 literalExpr->getSourceRange().getEnd()));
1156 } else if (literalType->isIncompleteType()) {
1157 return Diag(LParenLoc,
1158 diag::err_typecheck_decl_incomplete_type,
1159 literalType.getAsString(),
1160 SourceRange(LParenLoc,
1161 literalExpr->getSourceRange().getEnd()));
1162 }
1163
Steve Narofff0b23542008-01-10 22:15:12 +00001164 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +00001165 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001166
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001167 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001168 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001169 if (CheckForConstantInitializer(literalExpr, literalType))
1170 return true;
1171 }
Steve Naroffbe37fc02008-01-14 18:19:28 +00001172 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001173}
1174
1175Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001176ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001177 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001178 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001179
Steve Naroff0acc9c92007-09-15 18:49:24 +00001180 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001181 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001182
Chris Lattner48d7f382008-04-02 04:24:33 +00001183 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1184 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1185 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001186}
1187
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001188/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001189bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001190 UsualUnaryConversions(castExpr);
1191
1192 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1193 // type needs to be scalar.
1194 if (castType->isVoidType()) {
1195 // Cast to void allows any expr type.
1196 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1197 // GCC struct/union extension: allow cast to self.
1198 if (Context.getCanonicalType(castType) !=
1199 Context.getCanonicalType(castExpr->getType()) ||
1200 (!castType->isStructureType() && !castType->isUnionType())) {
1201 // Reject any other conversions to non-scalar types.
1202 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1203 castType.getAsString(), castExpr->getSourceRange());
1204 }
1205
1206 // accept this, but emit an ext-warn.
1207 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1208 castType.getAsString(), castExpr->getSourceRange());
1209 } else if (!castExpr->getType()->isScalarType() &&
1210 !castExpr->getType()->isVectorType()) {
1211 return Diag(castExpr->getLocStart(),
1212 diag::err_typecheck_expect_scalar_operand,
1213 castExpr->getType().getAsString(),castExpr->getSourceRange());
1214 } else if (castExpr->getType()->isVectorType()) {
1215 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1216 return true;
1217 } else if (castType->isVectorType()) {
1218 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1219 return true;
1220 }
1221 return false;
1222}
1223
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001224bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001225 assert(VectorTy->isVectorType() && "Not a vector type!");
1226
1227 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001228 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001229 return Diag(R.getBegin(),
1230 Ty->isVectorType() ?
1231 diag::err_invalid_conversion_between_vectors :
1232 diag::err_invalid_conversion_between_vector_and_integer,
1233 VectorTy.getAsString().c_str(),
1234 Ty.getAsString().c_str(), R);
1235 } else
1236 return Diag(R.getBegin(),
1237 diag::err_invalid_conversion_between_vector_and_scalar,
1238 VectorTy.getAsString().c_str(),
1239 Ty.getAsString().c_str(), R);
1240
1241 return false;
1242}
1243
Chris Lattner4b009652007-07-25 00:24:17 +00001244Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001245ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001246 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001247 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001248
1249 Expr *castExpr = static_cast<Expr*>(Op);
1250 QualType castType = QualType::getFromOpaquePtr(Ty);
1251
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001252 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1253 return true;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001254 return new ExplicitCastExpr(castType, castExpr, LParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001255}
1256
Chris Lattner98a425c2007-11-26 01:40:58 +00001257/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1258/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001259inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1260 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1261 UsualUnaryConversions(cond);
1262 UsualUnaryConversions(lex);
1263 UsualUnaryConversions(rex);
1264 QualType condT = cond->getType();
1265 QualType lexT = lex->getType();
1266 QualType rexT = rex->getType();
1267
1268 // first, check the condition.
1269 if (!condT->isScalarType()) { // C99 6.5.15p2
1270 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1271 condT.getAsString());
1272 return QualType();
1273 }
Chris Lattner992ae932008-01-06 22:42:25 +00001274
1275 // Now check the two expressions.
1276
1277 // If both operands have arithmetic type, do the usual arithmetic conversions
1278 // to find a common type: C99 6.5.15p3,5.
1279 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001280 UsualArithmeticConversions(lex, rex);
1281 return lex->getType();
1282 }
Chris Lattner992ae932008-01-06 22:42:25 +00001283
1284 // If both operands are the same structure or union type, the result is that
1285 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001286 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001287 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001288 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001289 // "If both the operands have structure or union type, the result has
1290 // that type." This implies that CV qualifiers are dropped.
1291 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001292 }
Chris Lattner992ae932008-01-06 22:42:25 +00001293
1294 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001295 // The following || allows only one side to be void (a GCC-ism).
1296 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001297 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001298 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1299 rex->getSourceRange());
1300 if (!rexT->isVoidType())
1301 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001302 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001303 ImpCastExprToType(lex, Context.VoidTy);
1304 ImpCastExprToType(rex, Context.VoidTy);
1305 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001306 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001307 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1308 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001309 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1310 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001311 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001312 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001313 return lexT;
1314 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001315 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1316 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001317 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001318 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001319 return rexT;
1320 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001321 // Handle the case where both operands are pointers before we handle null
1322 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001323 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1324 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1325 // get the "pointed to" types
1326 QualType lhptee = LHSPT->getPointeeType();
1327 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001328
Chris Lattner71225142007-07-31 21:27:01 +00001329 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1330 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001331 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001332 // Figure out necessary qualifiers (C99 6.5.15p6)
1333 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001334 QualType destType = Context.getPointerType(destPointee);
1335 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1336 ImpCastExprToType(rex, destType); // promote to void*
1337 return destType;
1338 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001339 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001340 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001341 QualType destType = Context.getPointerType(destPointee);
1342 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1343 ImpCastExprToType(rex, destType); // promote to void*
1344 return destType;
1345 }
Chris Lattner4b009652007-07-25 00:24:17 +00001346
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001347 QualType compositeType = lexT;
1348
1349 // If either type is an Objective-C object type then check
1350 // compatibility according to Objective-C.
1351 if (Context.isObjCObjectPointerType(lexT) ||
1352 Context.isObjCObjectPointerType(rexT)) {
1353 // If both operands are interfaces and either operand can be
1354 // assigned to the other, use that type as the composite
1355 // type. This allows
1356 // xxx ? (A*) a : (B*) b
1357 // where B is a subclass of A.
1358 //
1359 // Additionally, as for assignment, if either type is 'id'
1360 // allow silent coercion. Finally, if the types are
1361 // incompatible then make sure to use 'id' as the composite
1362 // type so the result is acceptable for sending messages to.
1363
1364 // FIXME: This code should not be localized to here. Also this
1365 // should use a compatible check instead of abusing the
1366 // canAssignObjCInterfaces code.
1367 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1368 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1369 if (LHSIface && RHSIface &&
1370 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1371 compositeType = lexT;
1372 } else if (LHSIface && RHSIface &&
1373 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1374 compositeType = rexT;
1375 } else if (Context.isObjCIdType(lhptee) ||
1376 Context.isObjCIdType(rhptee)) {
1377 // FIXME: This code looks wrong, because isObjCIdType checks
1378 // the struct but getObjCIdType returns the pointer to
1379 // struct. This is horrible and should be fixed.
1380 compositeType = Context.getObjCIdType();
1381 } else {
1382 QualType incompatTy = Context.getObjCIdType();
1383 ImpCastExprToType(lex, incompatTy);
1384 ImpCastExprToType(rex, incompatTy);
1385 return incompatTy;
1386 }
1387 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1388 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001389 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001390 lexT.getAsString(), rexT.getAsString(),
1391 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001392 // In this situation, we assume void* type. No especially good
1393 // reason, but this is what gcc does, and we do have to pick
1394 // to get a consistent AST.
1395 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001396 ImpCastExprToType(lex, incompatTy);
1397 ImpCastExprToType(rex, incompatTy);
1398 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001399 }
1400 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001401 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1402 // differently qualified versions of compatible types, the result type is
1403 // a pointer to an appropriately qualified version of the *composite*
1404 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001405 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001406 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001407 ImpCastExprToType(lex, compositeType);
1408 ImpCastExprToType(rex, compositeType);
1409 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001410 }
Chris Lattner4b009652007-07-25 00:24:17 +00001411 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001412 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1413 // evaluates to "struct objc_object *" (and is handled above when comparing
1414 // id with statically typed objects).
1415 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1416 // GCC allows qualified id and any Objective-C type to devolve to
1417 // id. Currently localizing to here until clear this should be
1418 // part of ObjCQualifiedIdTypesAreCompatible.
1419 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1420 (lexT->isObjCQualifiedIdType() &&
1421 Context.isObjCObjectPointerType(rexT)) ||
1422 (rexT->isObjCQualifiedIdType() &&
1423 Context.isObjCObjectPointerType(lexT))) {
1424 // FIXME: This is not the correct composite type. This only
1425 // happens to work because id can more or less be used anywhere,
1426 // however this may change the type of method sends.
1427 // FIXME: gcc adds some type-checking of the arguments and emits
1428 // (confusing) incompatible comparison warnings in some
1429 // cases. Investigate.
1430 QualType compositeType = Context.getObjCIdType();
1431 ImpCastExprToType(lex, compositeType);
1432 ImpCastExprToType(rex, compositeType);
1433 return compositeType;
1434 }
1435 }
1436
Steve Naroff3eac7692008-09-10 19:17:48 +00001437 // Selection between block pointer types is ok as long as they are the same.
1438 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1439 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1440 return lexT;
1441
Chris Lattner992ae932008-01-06 22:42:25 +00001442 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001443 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1444 lexT.getAsString(), rexT.getAsString(),
1445 lex->getSourceRange(), rex->getSourceRange());
1446 return QualType();
1447}
1448
Steve Naroff87d58b42007-09-16 03:34:24 +00001449/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001450/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001451Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001452 SourceLocation ColonLoc,
1453 ExprTy *Cond, ExprTy *LHS,
1454 ExprTy *RHS) {
1455 Expr *CondExpr = (Expr *) Cond;
1456 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001457
1458 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1459 // was the condition.
1460 bool isLHSNull = LHSExpr == 0;
1461 if (isLHSNull)
1462 LHSExpr = CondExpr;
1463
Chris Lattner4b009652007-07-25 00:24:17 +00001464 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1465 RHSExpr, QuestionLoc);
1466 if (result.isNull())
1467 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001468 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1469 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001470}
1471
Chris Lattner4b009652007-07-25 00:24:17 +00001472
1473// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1474// being closely modeled after the C99 spec:-). The odd characteristic of this
1475// routine is it effectively iqnores the qualifiers on the top level pointee.
1476// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1477// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001478Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001479Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1480 QualType lhptee, rhptee;
1481
1482 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001483 lhptee = lhsType->getAsPointerType()->getPointeeType();
1484 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001485
1486 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001487 lhptee = Context.getCanonicalType(lhptee);
1488 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001489
Chris Lattner005ed752008-01-04 18:04:52 +00001490 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001491
1492 // C99 6.5.16.1p1: This following citation is common to constraints
1493 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1494 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001495 // FIXME: Handle ASQualType
1496 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1497 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001498 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001499
1500 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1501 // incomplete type and the other is a pointer to a qualified or unqualified
1502 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001503 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001504 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001505 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001506
1507 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001508 assert(rhptee->isFunctionType());
1509 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001510 }
1511
1512 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001513 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001514 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001515
1516 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001517 assert(lhptee->isFunctionType());
1518 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001519 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001520
1521 // Check for ObjC interfaces
1522 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1523 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1524 if (LHSIface && RHSIface &&
1525 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1526 return ConvTy;
1527
1528 // ID acts sort of like void* for ObjC interfaces
1529 if (LHSIface && Context.isObjCIdType(rhptee))
1530 return ConvTy;
1531 if (RHSIface && Context.isObjCIdType(lhptee))
1532 return ConvTy;
1533
Chris Lattner4b009652007-07-25 00:24:17 +00001534 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1535 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001536 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1537 rhptee.getUnqualifiedType()))
1538 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001539 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001540}
1541
Steve Naroff3454b6c2008-09-04 15:10:53 +00001542/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1543/// block pointer types are compatible or whether a block and normal pointer
1544/// are compatible. It is more restrict than comparing two function pointer
1545// types.
1546Sema::AssignConvertType
1547Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1548 QualType rhsType) {
1549 QualType lhptee, rhptee;
1550
1551 // get the "pointed to" type (ignoring qualifiers at the top level)
1552 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1553 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1554
1555 // make sure we operate on the canonical type
1556 lhptee = Context.getCanonicalType(lhptee);
1557 rhptee = Context.getCanonicalType(rhptee);
1558
1559 AssignConvertType ConvTy = Compatible;
1560
1561 // For blocks we enforce that qualifiers are identical.
1562 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1563 ConvTy = CompatiblePointerDiscardsQualifiers;
1564
1565 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1566 return IncompatibleBlockPointer;
1567 return ConvTy;
1568}
1569
Chris Lattner4b009652007-07-25 00:24:17 +00001570/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1571/// has code to accommodate several GCC extensions when type checking
1572/// pointers. Here are some objectionable examples that GCC considers warnings:
1573///
1574/// int a, *pint;
1575/// short *pshort;
1576/// struct foo *pfoo;
1577///
1578/// pint = pshort; // warning: assignment from incompatible pointer type
1579/// a = pint; // warning: assignment makes integer from pointer without a cast
1580/// pint = a; // warning: assignment makes pointer from integer without a cast
1581/// pint = pfoo; // warning: assignment from incompatible pointer type
1582///
1583/// As a result, the code for dealing with pointers is more complex than the
1584/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001585///
Chris Lattner005ed752008-01-04 18:04:52 +00001586Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001587Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001588 // Get canonical types. We're not formatting these types, just comparing
1589 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001590 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1591 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001592
1593 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001594 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001595
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001596 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001597 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001598 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001599 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001600 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001601
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001602 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1603 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001604 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001605 // Relax integer conversions like we do for pointers below.
1606 if (rhsType->isIntegerType())
1607 return IntToPointer;
1608 if (lhsType->isIntegerType())
1609 return PointerToInt;
Chris Lattner1853da22008-01-04 23:18:45 +00001610 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001611 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001612
Nate Begemanc5f0f652008-07-14 18:02:46 +00001613 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001614 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001615 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1616 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001617 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001618
Nate Begemanc5f0f652008-07-14 18:02:46 +00001619 // If we are allowing lax vector conversions, and LHS and RHS are both
1620 // vectors, the total size only needs to be the same. This is a bitcast;
1621 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001622 if (getLangOptions().LaxVectorConversions &&
1623 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001624 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1625 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001626 }
1627 return Incompatible;
1628 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001629
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001630 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001631 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001632
Chris Lattner390564e2008-04-07 06:49:41 +00001633 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001634 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001635 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001636
Chris Lattner390564e2008-04-07 06:49:41 +00001637 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001638 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001639
Steve Naroffd6163f32008-09-05 22:11:13 +00001640 if (rhsType->getAsBlockPointerType())
1641 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff3454b6c2008-09-04 15:10:53 +00001642 return BlockVoidPointer;
1643
1644 return Incompatible;
1645 }
1646
1647 if (isa<BlockPointerType>(lhsType)) {
1648 if (rhsType->isIntegerType())
1649 return IntToPointer;
1650
1651 if (rhsType->isBlockPointerType())
1652 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1653
1654 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1655 if (RHSPT->getPointeeType()->isVoidType())
1656 return BlockVoidPointer;
1657 }
Chris Lattner1853da22008-01-04 23:18:45 +00001658 return Incompatible;
1659 }
1660
Chris Lattner390564e2008-04-07 06:49:41 +00001661 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001662 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001663 if (lhsType == Context.BoolTy)
1664 return Compatible;
1665
1666 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001667 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001668
Chris Lattner390564e2008-04-07 06:49:41 +00001669 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001670 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001671
1672 if (isa<BlockPointerType>(lhsType) &&
1673 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1674 return BlockVoidPointer;
Chris Lattner1853da22008-01-04 23:18:45 +00001675 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001676 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001677
Chris Lattner1853da22008-01-04 23:18:45 +00001678 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001679 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001680 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001681 }
1682 return Incompatible;
1683}
1684
Chris Lattner005ed752008-01-04 18:04:52 +00001685Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001686Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001687 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1688 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00001689 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1690 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001691 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001692 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001693 return Compatible;
1694 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001695
1696 // We don't allow conversion of non-null-pointer constants to integers.
1697 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1698 return IntToBlockPointer;
1699
Chris Lattner5f505bf2007-10-16 02:55:40 +00001700 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001701 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001702 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001703 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001704 //
1705 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1706 // are better understood.
1707 if (!lhsType->isReferenceType())
1708 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001709
Chris Lattner005ed752008-01-04 18:04:52 +00001710 Sema::AssignConvertType result =
1711 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001712
1713 // C99 6.5.16.1p2: The value of the right operand is converted to the
1714 // type of the assignment expression.
1715 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001716 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001717 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001718}
1719
Chris Lattner005ed752008-01-04 18:04:52 +00001720Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001721Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1722 return CheckAssignmentConstraints(lhsType, rhsType);
1723}
1724
Chris Lattner2c8bff72007-12-12 05:47:28 +00001725QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001726 Diag(loc, diag::err_typecheck_invalid_operands,
1727 lex->getType().getAsString(), rex->getType().getAsString(),
1728 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001729 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001730}
1731
1732inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1733 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001734 // For conversion purposes, we ignore any qualifiers.
1735 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001736 QualType lhsType =
1737 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1738 QualType rhsType =
1739 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001740
Nate Begemanc5f0f652008-07-14 18:02:46 +00001741 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001742 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001743 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001744
Nate Begemanc5f0f652008-07-14 18:02:46 +00001745 // Handle the case of a vector & extvector type of the same size and element
1746 // type. It would be nice if we only had one vector type someday.
1747 if (getLangOptions().LaxVectorConversions)
1748 if (const VectorType *LV = lhsType->getAsVectorType())
1749 if (const VectorType *RV = rhsType->getAsVectorType())
1750 if (LV->getElementType() == RV->getElementType() &&
1751 LV->getNumElements() == RV->getNumElements())
1752 return lhsType->isExtVectorType() ? lhsType : rhsType;
1753
1754 // If the lhs is an extended vector and the rhs is a scalar of the same type
1755 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001756 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001757 QualType eltType = V->getElementType();
1758
1759 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1760 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1761 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001762 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001763 return lhsType;
1764 }
1765 }
1766
Nate Begemanc5f0f652008-07-14 18:02:46 +00001767 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001768 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001769 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001770 QualType eltType = V->getElementType();
1771
1772 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1773 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1774 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001775 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001776 return rhsType;
1777 }
1778 }
1779
Chris Lattner4b009652007-07-25 00:24:17 +00001780 // You cannot convert between vector values of different size.
1781 Diag(loc, diag::err_typecheck_vector_not_convertable,
1782 lex->getType().getAsString(), rex->getType().getAsString(),
1783 lex->getSourceRange(), rex->getSourceRange());
1784 return QualType();
1785}
1786
1787inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001788 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001789{
1790 QualType lhsType = lex->getType(), rhsType = rex->getType();
1791
1792 if (lhsType->isVectorType() || rhsType->isVectorType())
1793 return CheckVectorOperands(loc, lex, rex);
1794
Steve Naroff8f708362007-08-24 19:07:16 +00001795 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001796
Chris Lattner4b009652007-07-25 00:24:17 +00001797 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001798 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001799 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001800}
1801
1802inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001803 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001804{
1805 QualType lhsType = lex->getType(), rhsType = rex->getType();
1806
Steve Naroff8f708362007-08-24 19:07:16 +00001807 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001808
Chris Lattner4b009652007-07-25 00:24:17 +00001809 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001810 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001811 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001812}
1813
1814inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001815 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001816{
1817 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1818 return CheckVectorOperands(loc, lex, rex);
1819
Steve Naroff8f708362007-08-24 19:07:16 +00001820 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001821
Chris Lattner4b009652007-07-25 00:24:17 +00001822 // handle the common case first (both operands are arithmetic).
1823 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001824 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001825
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001826 // Put any potential pointer into PExp
1827 Expr* PExp = lex, *IExp = rex;
1828 if (IExp->getType()->isPointerType())
1829 std::swap(PExp, IExp);
1830
1831 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1832 if (IExp->getType()->isIntegerType()) {
1833 // Check for arithmetic on pointers to incomplete types
1834 if (!PTy->getPointeeType()->isObjectType()) {
1835 if (PTy->getPointeeType()->isVoidType()) {
1836 Diag(loc, diag::ext_gnu_void_ptr,
1837 lex->getSourceRange(), rex->getSourceRange());
1838 } else {
1839 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1840 lex->getType().getAsString(), lex->getSourceRange());
1841 return QualType();
1842 }
1843 }
1844 return PExp->getType();
1845 }
1846 }
1847
Chris Lattner2c8bff72007-12-12 05:47:28 +00001848 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001849}
1850
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001851// C99 6.5.6
1852QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1853 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001854 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1855 return CheckVectorOperands(loc, lex, rex);
1856
Steve Naroff8f708362007-08-24 19:07:16 +00001857 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001858
Chris Lattnerf6da2912007-12-09 21:53:25 +00001859 // Enforce type constraints: C99 6.5.6p3.
1860
1861 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001862 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001863 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001864
1865 // Either ptr - int or ptr - ptr.
1866 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001867 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001868
Chris Lattnerf6da2912007-12-09 21:53:25 +00001869 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001870 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001871 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001872 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001873 Diag(loc, diag::ext_gnu_void_ptr,
1874 lex->getSourceRange(), rex->getSourceRange());
1875 } else {
1876 Diag(loc, diag::err_typecheck_sub_ptr_object,
1877 lex->getType().getAsString(), lex->getSourceRange());
1878 return QualType();
1879 }
1880 }
1881
1882 // The result type of a pointer-int computation is the pointer type.
1883 if (rex->getType()->isIntegerType())
1884 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001885
Chris Lattnerf6da2912007-12-09 21:53:25 +00001886 // Handle pointer-pointer subtractions.
1887 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001888 QualType rpointee = RHSPTy->getPointeeType();
1889
Chris Lattnerf6da2912007-12-09 21:53:25 +00001890 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001891 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001892 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001893 if (rpointee->isVoidType()) {
1894 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001895 Diag(loc, diag::ext_gnu_void_ptr,
1896 lex->getSourceRange(), rex->getSourceRange());
1897 } else {
1898 Diag(loc, diag::err_typecheck_sub_ptr_object,
1899 rex->getType().getAsString(), rex->getSourceRange());
1900 return QualType();
1901 }
1902 }
1903
1904 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00001905 if (!Context.typesAreCompatible(
1906 Context.getCanonicalType(lpointee).getUnqualifiedType(),
1907 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001908 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1909 lex->getType().getAsString(), rex->getType().getAsString(),
1910 lex->getSourceRange(), rex->getSourceRange());
1911 return QualType();
1912 }
1913
1914 return Context.getPointerDiffType();
1915 }
1916 }
1917
Chris Lattner2c8bff72007-12-12 05:47:28 +00001918 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001919}
1920
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001921// C99 6.5.7
1922QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1923 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00001924 // C99 6.5.7p2: Each of the operands shall have integer type.
1925 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1926 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001927
Chris Lattner2c8bff72007-12-12 05:47:28 +00001928 // Shifts don't perform usual arithmetic conversions, they just do integer
1929 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001930 if (!isCompAssign)
1931 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001932 UsualUnaryConversions(rex);
1933
1934 // "The type of the result is that of the promoted left operand."
1935 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001936}
1937
Eli Friedman0d9549b2008-08-22 00:56:42 +00001938static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
1939 ASTContext& Context) {
1940 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
1941 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
1942 // ID acts sort of like void* for ObjC interfaces
1943 if (LHSIface && Context.isObjCIdType(RHS))
1944 return true;
1945 if (RHSIface && Context.isObjCIdType(LHS))
1946 return true;
1947 if (!LHSIface || !RHSIface)
1948 return false;
1949 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
1950 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
1951}
1952
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001953// C99 6.5.8
1954QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1955 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001956 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1957 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1958
Chris Lattner254f3bc2007-08-26 01:18:55 +00001959 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001960 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1961 UsualArithmeticConversions(lex, rex);
1962 else {
1963 UsualUnaryConversions(lex);
1964 UsualUnaryConversions(rex);
1965 }
Chris Lattner4b009652007-07-25 00:24:17 +00001966 QualType lType = lex->getType();
1967 QualType rType = rex->getType();
1968
Ted Kremenek486509e2007-10-29 17:13:39 +00001969 // For non-floating point types, check for self-comparisons of the form
1970 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1971 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001972 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001973 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1974 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001975 if (DRL->getDecl() == DRR->getDecl())
1976 Diag(loc, diag::warn_selfcomparison);
1977 }
1978
Chris Lattner254f3bc2007-08-26 01:18:55 +00001979 if (isRelational) {
1980 if (lType->isRealType() && rType->isRealType())
1981 return Context.IntTy;
1982 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001983 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001984 if (lType->isFloatingType()) {
1985 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001986 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001987 }
1988
Chris Lattner254f3bc2007-08-26 01:18:55 +00001989 if (lType->isArithmeticType() && rType->isArithmeticType())
1990 return Context.IntTy;
1991 }
Chris Lattner4b009652007-07-25 00:24:17 +00001992
Chris Lattner22be8422007-08-26 01:10:14 +00001993 bool LHSIsNull = lex->isNullPointerConstant(Context);
1994 bool RHSIsNull = rex->isNullPointerConstant(Context);
1995
Chris Lattner254f3bc2007-08-26 01:18:55 +00001996 // All of the following pointer related warnings are GCC extensions, except
1997 // when handling null pointer constants. One day, we can consider making them
1998 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001999 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002000 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002001 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002002 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002003 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002004
Steve Naroff3b435622007-11-13 14:57:38 +00002005 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002006 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2007 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002008 RCanPointeeTy.getUnqualifiedType()) &&
2009 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroff4462cb02007-08-16 21:48:38 +00002010 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2011 lType.getAsString(), rType.getAsString(),
2012 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002013 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002014 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002015 return Context.IntTy;
2016 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002017 // Handle block pointer types.
2018 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2019 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2020 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2021
2022 if (!LHSIsNull && !RHSIsNull &&
2023 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2024 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2025 lType.getAsString(), rType.getAsString(),
2026 lex->getSourceRange(), rex->getSourceRange());
2027 }
2028 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2029 return Context.IntTy;
2030 }
2031
Steve Naroff936c4362008-06-03 14:04:54 +00002032 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
2033 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2034 ImpCastExprToType(rex, lType);
2035 return Context.IntTy;
2036 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002037 }
Steve Naroff936c4362008-06-03 14:04:54 +00002038 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2039 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002040 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002041 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2042 lType.getAsString(), rType.getAsString(),
2043 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002044 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002045 return Context.IntTy;
2046 }
Steve Naroff936c4362008-06-03 14:04:54 +00002047 if (lType->isIntegerType() &&
2048 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002049 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002050 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2051 lType.getAsString(), rType.getAsString(),
2052 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002053 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002054 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002055 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002056 // Handle block pointers.
2057 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2058 if (!RHSIsNull)
2059 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2060 lType.getAsString(), rType.getAsString(),
2061 lex->getSourceRange(), rex->getSourceRange());
2062 ImpCastExprToType(rex, lType); // promote the integer to pointer
2063 return Context.IntTy;
2064 }
2065 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2066 if (!LHSIsNull)
2067 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2068 lType.getAsString(), rType.getAsString(),
2069 lex->getSourceRange(), rex->getSourceRange());
2070 ImpCastExprToType(lex, rType); // promote the integer to pointer
2071 return Context.IntTy;
2072 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00002073 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002074}
2075
Nate Begemanc5f0f652008-07-14 18:02:46 +00002076/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2077/// operates on extended vector types. Instead of producing an IntTy result,
2078/// like a scalar comparison, a vector comparison produces a vector of integer
2079/// types.
2080QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2081 SourceLocation loc,
2082 bool isRelational) {
2083 // Check to make sure we're operating on vectors of the same type and width,
2084 // Allowing one side to be a scalar of element type.
2085 QualType vType = CheckVectorOperands(loc, lex, rex);
2086 if (vType.isNull())
2087 return vType;
2088
2089 QualType lType = lex->getType();
2090 QualType rType = rex->getType();
2091
2092 // For non-floating point types, check for self-comparisons of the form
2093 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2094 // often indicate logic errors in the program.
2095 if (!lType->isFloatingType()) {
2096 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2097 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2098 if (DRL->getDecl() == DRR->getDecl())
2099 Diag(loc, diag::warn_selfcomparison);
2100 }
2101
2102 // Check for comparisons of floating point operands using != and ==.
2103 if (!isRelational && lType->isFloatingType()) {
2104 assert (rType->isFloatingType());
2105 CheckFloatComparison(loc,lex,rex);
2106 }
2107
2108 // Return the type for the comparison, which is the same as vector type for
2109 // integer vectors, or an integer type of identical size and number of
2110 // elements for floating point vectors.
2111 if (lType->isIntegerType())
2112 return lType;
2113
2114 const VectorType *VTy = lType->getAsVectorType();
2115
2116 // FIXME: need to deal with non-32b int / non-64b long long
2117 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2118 if (TypeSize == 32) {
2119 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2120 }
2121 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2122 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2123}
2124
Chris Lattner4b009652007-07-25 00:24:17 +00002125inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00002126 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002127{
2128 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2129 return CheckVectorOperands(loc, lex, rex);
2130
Steve Naroff8f708362007-08-24 19:07:16 +00002131 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002132
2133 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002134 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002135 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002136}
2137
2138inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
2139 Expr *&lex, Expr *&rex, SourceLocation loc)
2140{
2141 UsualUnaryConversions(lex);
2142 UsualUnaryConversions(rex);
2143
Eli Friedmanbea3f842008-05-13 20:16:47 +00002144 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002145 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002146 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002147}
2148
2149inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00002150 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00002151{
2152 QualType lhsType = lex->getType();
2153 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner25168a52008-07-26 21:30:36 +00002154 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002155
2156 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00002157 case Expr::MLV_Valid:
2158 break;
2159 case Expr::MLV_ConstQualified:
2160 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2161 return QualType();
2162 case Expr::MLV_ArrayType:
2163 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2164 lhsType.getAsString(), lex->getSourceRange());
2165 return QualType();
2166 case Expr::MLV_NotObjectType:
2167 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2168 lhsType.getAsString(), lex->getSourceRange());
2169 return QualType();
2170 case Expr::MLV_InvalidExpression:
2171 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2172 lex->getSourceRange());
2173 return QualType();
2174 case Expr::MLV_IncompleteType:
2175 case Expr::MLV_IncompleteVoidType:
2176 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2177 lhsType.getAsString(), lex->getSourceRange());
2178 return QualType();
2179 case Expr::MLV_DuplicateVectorComponents:
2180 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2181 lex->getSourceRange());
2182 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002183 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002184
Chris Lattner005ed752008-01-04 18:04:52 +00002185 AssignConvertType ConvTy;
Chris Lattner34c85082008-08-21 18:04:13 +00002186 if (compoundType.isNull()) {
2187 // Simple assignment "x = y".
Chris Lattner005ed752008-01-04 18:04:52 +00002188 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner34c85082008-08-21 18:04:13 +00002189
2190 // If the RHS is a unary plus or minus, check to see if they = and + are
2191 // right next to each other. If so, the user may have typo'd "x =+ 4"
2192 // instead of "x += 4".
2193 Expr *RHSCheck = rex;
2194 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2195 RHSCheck = ICE->getSubExpr();
2196 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2197 if ((UO->getOpcode() == UnaryOperator::Plus ||
2198 UO->getOpcode() == UnaryOperator::Minus) &&
2199 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2200 // Only if the two operators are exactly adjacent.
2201 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2202 Diag(loc, diag::warn_not_compound_assign,
2203 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2204 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2205 }
2206 } else {
2207 // Compound assignment "x += y"
Chris Lattner005ed752008-01-04 18:04:52 +00002208 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner34c85082008-08-21 18:04:13 +00002209 }
Chris Lattner005ed752008-01-04 18:04:52 +00002210
2211 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2212 rex, "assigning"))
2213 return QualType();
2214
Chris Lattner4b009652007-07-25 00:24:17 +00002215 // C99 6.5.16p3: The type of an assignment expression is the type of the
2216 // left operand unless the left operand has qualified type, in which case
2217 // it is the unqualified version of the type of the left operand.
2218 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2219 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002220 // C++ 5.17p1: the type of the assignment expression is that of its left
2221 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00002222 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002223}
2224
2225inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2226 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00002227
2228 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2229 DefaultFunctionArrayConversion(rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002230 return rex->getType();
2231}
2232
2233/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2234/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2235QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2236 QualType resType = op->getType();
2237 assert(!resType.isNull() && "no type for increment/decrement expression");
2238
Steve Naroffd30e1932007-08-24 17:20:07 +00002239 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00002240 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002241 if (pt->getPointeeType()->isVoidType()) {
2242 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2243 } else if (!pt->getPointeeType()->isObjectType()) {
2244 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00002245 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2246 resType.getAsString(), op->getSourceRange());
2247 return QualType();
2248 }
Steve Naroffd30e1932007-08-24 17:20:07 +00002249 } else if (!resType->isRealType()) {
2250 if (resType->isComplexType())
2251 // C99 does not support ++/-- on complex types.
2252 Diag(OpLoc, diag::ext_integer_increment_complex,
2253 resType.getAsString(), op->getSourceRange());
2254 else {
2255 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2256 resType.getAsString(), op->getSourceRange());
2257 return QualType();
2258 }
Chris Lattner4b009652007-07-25 00:24:17 +00002259 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002260 // At this point, we know we have a real, complex or pointer type.
2261 // Now make sure the operand is a modifiable lvalue.
Chris Lattner25168a52008-07-26 21:30:36 +00002262 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002263 if (mlval != Expr::MLV_Valid) {
2264 // FIXME: emit a more precise diagnostic...
2265 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2266 op->getSourceRange());
2267 return QualType();
2268 }
2269 return resType;
2270}
2271
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002272/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002273/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002274/// where the declaration is needed for type checking. We only need to
2275/// handle cases when the expression references a function designator
2276/// or is an lvalue. Here are some examples:
2277/// - &(x) => x
2278/// - &*****f => f for f a function designator.
2279/// - &s.xx => s
2280/// - &s.zz[1].yy -> s, if zz is an array
2281/// - *(x + 1) -> x, if x is an array
2282/// - &"123"[2] -> 0
2283/// - & __real__ x -> x
Chris Lattner48d7f382008-04-02 04:24:33 +00002284static ValueDecl *getPrimaryDecl(Expr *E) {
2285 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002286 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002287 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002288 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002289 // Fields cannot be declared with a 'register' storage class.
2290 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002291 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002292 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002293 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002294 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002295 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002296
Chris Lattner48d7f382008-04-02 04:24:33 +00002297 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00002298 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002299 return 0;
2300 else
2301 return VD;
2302 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002303 case Stmt::UnaryOperatorClass: {
2304 UnaryOperator *UO = cast<UnaryOperator>(E);
2305
2306 switch(UO->getOpcode()) {
2307 case UnaryOperator::Deref: {
2308 // *(X + 1) refers to X if X is not a pointer.
2309 ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2310 if (!VD || VD->getType()->isPointerType())
2311 return 0;
2312 return VD;
2313 }
2314 case UnaryOperator::Real:
2315 case UnaryOperator::Imag:
2316 case UnaryOperator::Extension:
2317 return getPrimaryDecl(UO->getSubExpr());
2318 default:
2319 return 0;
2320 }
2321 }
2322 case Stmt::BinaryOperatorClass: {
2323 BinaryOperator *BO = cast<BinaryOperator>(E);
2324
2325 // Handle cases involving pointer arithmetic. The result of an
2326 // Assign or AddAssign is not an lvalue so they can be ignored.
2327
2328 // (x + n) or (n + x) => x
2329 if (BO->getOpcode() == BinaryOperator::Add) {
2330 if (BO->getLHS()->getType()->isPointerType()) {
2331 return getPrimaryDecl(BO->getLHS());
2332 } else if (BO->getRHS()->getType()->isPointerType()) {
2333 return getPrimaryDecl(BO->getRHS());
2334 }
2335 }
2336
2337 return 0;
2338 }
Chris Lattner4b009652007-07-25 00:24:17 +00002339 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002340 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002341 case Stmt::ImplicitCastExprClass:
2342 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002343 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002344 default:
2345 return 0;
2346 }
2347}
2348
2349/// CheckAddressOfOperand - The operand of & must be either a function
2350/// designator or an lvalue designating an object. If it is an lvalue, the
2351/// object cannot be declared with storage class register or be a bit field.
2352/// Note: The usual conversions are *not* applied to the operand of the &
2353/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2354QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002355 if (getLangOptions().C99) {
2356 // Implement C99-only parts of addressof rules.
2357 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2358 if (uOp->getOpcode() == UnaryOperator::Deref)
2359 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2360 // (assuming the deref expression is valid).
2361 return uOp->getSubExpr()->getType();
2362 }
2363 // Technically, there should be a check for array subscript
2364 // expressions here, but the result of one is always an lvalue anyway.
2365 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002366 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002367 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002368
2369 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002370 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2371 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002372 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2373 op->getSourceRange());
2374 return QualType();
2375 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002376 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2377 if (MemExpr->getMemberDecl()->isBitField()) {
2378 Diag(OpLoc, diag::err_typecheck_address_of,
2379 std::string("bit-field"), op->getSourceRange());
2380 return QualType();
2381 }
2382 // Check for Apple extension for accessing vector components.
2383 } else if (isa<ArraySubscriptExpr>(op) &&
2384 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2385 Diag(OpLoc, diag::err_typecheck_address_of,
2386 std::string("vector"), op->getSourceRange());
2387 return QualType();
2388 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002389 // We have an lvalue with a decl. Make sure the decl is not declared
2390 // with the register storage-class specifier.
2391 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2392 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002393 Diag(OpLoc, diag::err_typecheck_address_of,
2394 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002395 return QualType();
2396 }
2397 } else
2398 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002399 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002400
Chris Lattner4b009652007-07-25 00:24:17 +00002401 // If the operand has type "type", the result has type "pointer to type".
2402 return Context.getPointerType(op->getType());
2403}
2404
2405QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2406 UsualUnaryConversions(op);
2407 QualType qType = op->getType();
2408
Chris Lattner7931f4a2007-07-31 16:53:04 +00002409 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002410 // Note that per both C89 and C99, this is always legal, even
2411 // if ptype is an incomplete type or void.
2412 // It would be possible to warn about dereferencing a
2413 // void pointer, but it's completely well-defined,
2414 // and such a warning is unlikely to catch any mistakes.
2415 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002416 }
2417 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2418 qType.getAsString(), op->getSourceRange());
2419 return QualType();
2420}
2421
2422static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2423 tok::TokenKind Kind) {
2424 BinaryOperator::Opcode Opc;
2425 switch (Kind) {
2426 default: assert(0 && "Unknown binop!");
2427 case tok::star: Opc = BinaryOperator::Mul; break;
2428 case tok::slash: Opc = BinaryOperator::Div; break;
2429 case tok::percent: Opc = BinaryOperator::Rem; break;
2430 case tok::plus: Opc = BinaryOperator::Add; break;
2431 case tok::minus: Opc = BinaryOperator::Sub; break;
2432 case tok::lessless: Opc = BinaryOperator::Shl; break;
2433 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2434 case tok::lessequal: Opc = BinaryOperator::LE; break;
2435 case tok::less: Opc = BinaryOperator::LT; break;
2436 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2437 case tok::greater: Opc = BinaryOperator::GT; break;
2438 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2439 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2440 case tok::amp: Opc = BinaryOperator::And; break;
2441 case tok::caret: Opc = BinaryOperator::Xor; break;
2442 case tok::pipe: Opc = BinaryOperator::Or; break;
2443 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2444 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2445 case tok::equal: Opc = BinaryOperator::Assign; break;
2446 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2447 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2448 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2449 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2450 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2451 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2452 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2453 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2454 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2455 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2456 case tok::comma: Opc = BinaryOperator::Comma; break;
2457 }
2458 return Opc;
2459}
2460
2461static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2462 tok::TokenKind Kind) {
2463 UnaryOperator::Opcode Opc;
2464 switch (Kind) {
2465 default: assert(0 && "Unknown unary op!");
2466 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2467 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2468 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2469 case tok::star: Opc = UnaryOperator::Deref; break;
2470 case tok::plus: Opc = UnaryOperator::Plus; break;
2471 case tok::minus: Opc = UnaryOperator::Minus; break;
2472 case tok::tilde: Opc = UnaryOperator::Not; break;
2473 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2474 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2475 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2476 case tok::kw___real: Opc = UnaryOperator::Real; break;
2477 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2478 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2479 }
2480 return Opc;
2481}
2482
2483// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002484Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002485 ExprTy *LHS, ExprTy *RHS) {
2486 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2487 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2488
Steve Naroff87d58b42007-09-16 03:34:24 +00002489 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2490 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002491
2492 QualType ResultTy; // Result type of the binary operator.
2493 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2494
2495 switch (Opc) {
2496 default:
2497 assert(0 && "Unknown binary expr!");
2498 case BinaryOperator::Assign:
2499 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2500 break;
2501 case BinaryOperator::Mul:
2502 case BinaryOperator::Div:
2503 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2504 break;
2505 case BinaryOperator::Rem:
2506 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2507 break;
2508 case BinaryOperator::Add:
2509 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2510 break;
2511 case BinaryOperator::Sub:
2512 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2513 break;
2514 case BinaryOperator::Shl:
2515 case BinaryOperator::Shr:
2516 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2517 break;
2518 case BinaryOperator::LE:
2519 case BinaryOperator::LT:
2520 case BinaryOperator::GE:
2521 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002522 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002523 break;
2524 case BinaryOperator::EQ:
2525 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002526 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00002527 break;
2528 case BinaryOperator::And:
2529 case BinaryOperator::Xor:
2530 case BinaryOperator::Or:
2531 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2532 break;
2533 case BinaryOperator::LAnd:
2534 case BinaryOperator::LOr:
2535 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2536 break;
2537 case BinaryOperator::MulAssign:
2538 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002539 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002540 if (!CompTy.isNull())
2541 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2542 break;
2543 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002544 CompTy = CheckRemainderOperands(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::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002549 CompTy = CheckAdditionOperands(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::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002554 CompTy = CheckSubtractionOperands(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::ShlAssign:
2559 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002560 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002561 if (!CompTy.isNull())
2562 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2563 break;
2564 case BinaryOperator::AndAssign:
2565 case BinaryOperator::XorAssign:
2566 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002567 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002568 if (!CompTy.isNull())
2569 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2570 break;
2571 case BinaryOperator::Comma:
2572 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2573 break;
2574 }
2575 if (ResultTy.isNull())
2576 return true;
2577 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00002578 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002579 else
Chris Lattnerf420df12007-08-28 18:36:55 +00002580 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002581}
2582
2583// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002584Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002585 ExprTy *input) {
2586 Expr *Input = (Expr*)input;
2587 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2588 QualType resultType;
2589 switch (Opc) {
2590 default:
2591 assert(0 && "Unimplemented unary expr!");
2592 case UnaryOperator::PreInc:
2593 case UnaryOperator::PreDec:
2594 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2595 break;
2596 case UnaryOperator::AddrOf:
2597 resultType = CheckAddressOfOperand(Input, OpLoc);
2598 break;
2599 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002600 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002601 resultType = CheckIndirectionOperand(Input, OpLoc);
2602 break;
2603 case UnaryOperator::Plus:
2604 case UnaryOperator::Minus:
2605 UsualUnaryConversions(Input);
2606 resultType = Input->getType();
2607 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2608 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2609 resultType.getAsString());
2610 break;
2611 case UnaryOperator::Not: // bitwise complement
2612 UsualUnaryConversions(Input);
2613 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002614 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2615 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2616 // C99 does not support '~' for complex conjugation.
2617 Diag(OpLoc, diag::ext_integer_complement_complex,
2618 resultType.getAsString(), Input->getSourceRange());
2619 else if (!resultType->isIntegerType())
2620 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2621 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002622 break;
2623 case UnaryOperator::LNot: // logical negation
2624 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2625 DefaultFunctionArrayConversion(Input);
2626 resultType = Input->getType();
2627 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2628 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2629 resultType.getAsString());
2630 // LNot always has type int. C99 6.5.3.3p5.
2631 resultType = Context.IntTy;
2632 break;
2633 case UnaryOperator::SizeOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002634 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2635 Input->getSourceRange(), true);
Chris Lattner4b009652007-07-25 00:24:17 +00002636 break;
2637 case UnaryOperator::AlignOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002638 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2639 Input->getSourceRange(), false);
Chris Lattner4b009652007-07-25 00:24:17 +00002640 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002641 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002642 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002643 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002644 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002645 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002646 resultType = Input->getType();
2647 break;
2648 }
2649 if (resultType.isNull())
2650 return true;
2651 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2652}
2653
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002654/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2655Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002656 SourceLocation LabLoc,
2657 IdentifierInfo *LabelII) {
2658 // Look up the record for this label identifier.
2659 LabelStmt *&LabelDecl = LabelMap[LabelII];
2660
Daniel Dunbar879788d2008-08-04 16:51:22 +00002661 // If we haven't seen this label yet, create a forward reference. It
2662 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00002663 if (LabelDecl == 0)
2664 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2665
2666 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002667 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2668 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002669}
2670
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002671Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002672 SourceLocation RPLoc) { // "({..})"
2673 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2674 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2675 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2676
2677 // FIXME: there are a variety of strange constraints to enforce here, for
2678 // example, it is not possible to goto into a stmt expression apparently.
2679 // More semantic analysis is needed.
2680
2681 // FIXME: the last statement in the compount stmt has its value used. We
2682 // should not warn about it being unused.
2683
2684 // If there are sub stmts in the compound stmt, take the type of the last one
2685 // as the type of the stmtexpr.
2686 QualType Ty = Context.VoidTy;
2687
Chris Lattner200964f2008-07-26 19:51:01 +00002688 if (!Compound->body_empty()) {
2689 Stmt *LastStmt = Compound->body_back();
2690 // If LastStmt is a label, skip down through into the body.
2691 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2692 LastStmt = Label->getSubStmt();
2693
2694 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00002695 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00002696 }
Chris Lattner4b009652007-07-25 00:24:17 +00002697
2698 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2699}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002700
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002701Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002702 SourceLocation TypeLoc,
2703 TypeTy *argty,
2704 OffsetOfComponent *CompPtr,
2705 unsigned NumComponents,
2706 SourceLocation RPLoc) {
2707 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2708 assert(!ArgTy.isNull() && "Missing type argument!");
2709
2710 // We must have at least one component that refers to the type, and the first
2711 // one is known to be a field designator. Verify that the ArgTy represents
2712 // a struct/union/class.
2713 if (!ArgTy->isRecordType())
2714 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2715
2716 // Otherwise, create a compound literal expression as the base, and
2717 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002718 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002719
Chris Lattnerb37522e2007-08-31 21:49:13 +00002720 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2721 // GCC extension, diagnose them.
2722 if (NumComponents != 1)
2723 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2724 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2725
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002726 for (unsigned i = 0; i != NumComponents; ++i) {
2727 const OffsetOfComponent &OC = CompPtr[i];
2728 if (OC.isBrackets) {
2729 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00002730 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002731 if (!AT) {
2732 delete Res;
2733 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2734 Res->getType().getAsString());
2735 }
2736
Chris Lattner2af6a802007-08-30 17:59:59 +00002737 // FIXME: C++: Verify that operator[] isn't overloaded.
2738
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002739 // C99 6.5.2.1p1
2740 Expr *Idx = static_cast<Expr*>(OC.U.E);
2741 if (!Idx->getType()->isIntegerType())
2742 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2743 Idx->getSourceRange());
2744
2745 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2746 continue;
2747 }
2748
2749 const RecordType *RC = Res->getType()->getAsRecordType();
2750 if (!RC) {
2751 delete Res;
2752 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2753 Res->getType().getAsString());
2754 }
2755
2756 // Get the decl corresponding to this.
2757 RecordDecl *RD = RC->getDecl();
2758 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2759 if (!MemberDecl)
2760 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2761 OC.U.IdentInfo->getName(),
2762 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002763
2764 // FIXME: C++: Verify that MemberDecl isn't a static field.
2765 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002766 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2767 // matter here.
2768 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002769 }
2770
2771 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2772 BuiltinLoc);
2773}
2774
2775
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002776Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002777 TypeTy *arg1, TypeTy *arg2,
2778 SourceLocation RPLoc) {
2779 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2780 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2781
2782 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2783
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002784 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002785}
2786
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002787Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002788 ExprTy *expr1, ExprTy *expr2,
2789 SourceLocation RPLoc) {
2790 Expr *CondExpr = static_cast<Expr*>(cond);
2791 Expr *LHSExpr = static_cast<Expr*>(expr1);
2792 Expr *RHSExpr = static_cast<Expr*>(expr2);
2793
2794 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2795
2796 // The conditional expression is required to be a constant expression.
2797 llvm::APSInt condEval(32);
2798 SourceLocation ExpLoc;
2799 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2800 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2801 CondExpr->getSourceRange());
2802
2803 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2804 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2805 RHSExpr->getType();
2806 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2807}
2808
Steve Naroff52a81c02008-09-03 18:15:37 +00002809//===----------------------------------------------------------------------===//
2810// Clang Extensions.
2811//===----------------------------------------------------------------------===//
2812
2813/// ActOnBlockStart - This callback is invoked when a block literal is started.
2814void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope,
2815 Declarator &ParamInfo) {
2816 // Analyze block parameters.
2817 BlockSemaInfo *BSI = new BlockSemaInfo();
2818
2819 // Add BSI to CurBlock.
2820 BSI->PrevBlockInfo = CurBlock;
2821 CurBlock = BSI;
2822
2823 BSI->ReturnType = 0;
2824 BSI->TheScope = BlockScope;
2825
2826 // Analyze arguments to block.
2827 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2828 "Not a function declarator!");
2829 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2830
2831 BSI->hasPrototype = FTI.hasPrototype;
2832 BSI->isVariadic = true;
2833
2834 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2835 // no arguments, not a function that takes a single void argument.
2836 if (FTI.hasPrototype &&
2837 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2838 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2839 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2840 // empty arg list, don't push any params.
2841 BSI->isVariadic = false;
2842 } else if (FTI.hasPrototype) {
2843 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
2844 BSI->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2845 BSI->isVariadic = FTI.isVariadic;
2846 }
2847}
2848
2849/// ActOnBlockError - If there is an error parsing a block, this callback
2850/// is invoked to pop the information about the block from the action impl.
2851void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
2852 // Ensure that CurBlock is deleted.
2853 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
2854
2855 // Pop off CurBlock, handle nested blocks.
2856 CurBlock = CurBlock->PrevBlockInfo;
2857
2858 // FIXME: Delete the ParmVarDecl objects as well???
2859
2860}
2861
2862/// ActOnBlockStmtExpr - This is called when the body of a block statement
2863/// literal was successfully completed. ^(int x){...}
2864Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
2865 Scope *CurScope) {
2866 // Ensure that CurBlock is deleted.
2867 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2868 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
2869
2870 // Pop off CurBlock, handle nested blocks.
2871 CurBlock = CurBlock->PrevBlockInfo;
2872
2873 QualType RetTy = Context.VoidTy;
2874 if (BSI->ReturnType)
2875 RetTy = QualType(BSI->ReturnType, 0);
2876
2877 llvm::SmallVector<QualType, 8> ArgTypes;
2878 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
2879 ArgTypes.push_back(BSI->Params[i]->getType());
2880
2881 QualType BlockTy;
2882 if (!BSI->hasPrototype)
2883 BlockTy = Context.getFunctionTypeNoProto(RetTy);
2884 else
2885 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
2886 BSI->isVariadic);
2887
2888 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroffb31e2b32008-09-17 18:37:59 +00002889 return new BlockExpr(CaretLoc, BlockTy, &BSI->Params[0], BSI->Params.size(),
2890 Body.take());
Steve Naroff52a81c02008-09-03 18:15:37 +00002891}
2892
Nate Begemanbd881ef2008-01-30 20:50:20 +00002893/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002894/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002895/// The number of arguments has already been validated to match the number of
2896/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002897static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2898 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002899 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00002900 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002901 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2902 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00002903
2904 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002905 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00002906 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002907 return true;
2908}
2909
2910Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2911 SourceLocation *CommaLocs,
2912 SourceLocation BuiltinLoc,
2913 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002914 // __builtin_overload requires at least 2 arguments
2915 if (NumArgs < 2)
2916 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2917 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002918
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002919 // The first argument is required to be a constant expression. It tells us
2920 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002921 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002922 Expr *NParamsExpr = Args[0];
2923 llvm::APSInt constEval(32);
2924 SourceLocation ExpLoc;
2925 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2926 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2927 NParamsExpr->getSourceRange());
2928
2929 // Verify that the number of parameters is > 0
2930 unsigned NumParams = constEval.getZExtValue();
2931 if (NumParams == 0)
2932 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2933 NParamsExpr->getSourceRange());
2934 // Verify that we have at least 1 + NumParams arguments to the builtin.
2935 if ((NumParams + 1) > NumArgs)
2936 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2937 SourceRange(BuiltinLoc, RParenLoc));
2938
2939 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002940 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002941 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002942 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2943 // UsualUnaryConversions will convert the function DeclRefExpr into a
2944 // pointer to function.
2945 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002946 const FunctionTypeProto *FnType = 0;
2947 if (const PointerType *PT = Fn->getType()->getAsPointerType())
2948 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002949
2950 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2951 // parameters, and the number of parameters must match the value passed to
2952 // the builtin.
2953 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002954 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2955 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002956
2957 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002958 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002959 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002960 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002961 if (OE)
2962 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2963 OE->getFn()->getSourceRange());
2964 // Remember our match, and continue processing the remaining arguments
2965 // to catch any errors.
2966 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2967 BuiltinLoc, RParenLoc);
2968 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002969 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002970 // Return the newly created OverloadExpr node, if we succeded in matching
2971 // exactly one of the candidate functions.
2972 if (OE)
2973 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002974
2975 // If we didn't find a matching function Expr in the __builtin_overload list
2976 // the return an error.
2977 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002978 for (unsigned i = 0; i != NumParams; ++i) {
2979 if (i != 0) typeNames += ", ";
2980 typeNames += Args[i+1]->getType().getAsString();
2981 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002982
2983 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2984 SourceRange(BuiltinLoc, RParenLoc));
2985}
2986
Anders Carlsson36760332007-10-15 20:28:48 +00002987Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2988 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002989 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002990 Expr *E = static_cast<Expr*>(expr);
2991 QualType T = QualType::getFromOpaquePtr(type);
2992
2993 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00002994
2995 // Get the va_list type
2996 QualType VaListType = Context.getBuiltinVaListType();
2997 // Deal with implicit array decay; for example, on x86-64,
2998 // va_list is an array, but it's supposed to decay to
2999 // a pointer for va_arg.
3000 if (VaListType->isArrayType())
3001 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003002 // Make sure the input expression also decays appropriately.
3003 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003004
3005 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003006 return Diag(E->getLocStart(),
3007 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3008 E->getType().getAsString(),
3009 E->getSourceRange());
3010
3011 // FIXME: Warn if a non-POD type is passed in.
3012
3013 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
3014}
3015
Chris Lattner005ed752008-01-04 18:04:52 +00003016bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3017 SourceLocation Loc,
3018 QualType DstType, QualType SrcType,
3019 Expr *SrcExpr, const char *Flavor) {
3020 // Decode the result (notice that AST's are still created for extensions).
3021 bool isInvalid = false;
3022 unsigned DiagKind;
3023 switch (ConvTy) {
3024 default: assert(0 && "Unknown conversion type");
3025 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003026 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003027 DiagKind = diag::ext_typecheck_convert_pointer_int;
3028 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003029 case IntToPointer:
3030 DiagKind = diag::ext_typecheck_convert_int_pointer;
3031 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003032 case IncompatiblePointer:
3033 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3034 break;
3035 case FunctionVoidPointer:
3036 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3037 break;
3038 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003039 // If the qualifiers lost were because we were applying the
3040 // (deprecated) C++ conversion from a string literal to a char*
3041 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3042 // Ideally, this check would be performed in
3043 // CheckPointerTypesForAssignment. However, that would require a
3044 // bit of refactoring (so that the second argument is an
3045 // expression, rather than a type), which should be done as part
3046 // of a larger effort to fix CheckPointerTypesForAssignment for
3047 // C++ semantics.
3048 if (getLangOptions().CPlusPlus &&
3049 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3050 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003051 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3052 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003053 case IntToBlockPointer:
3054 DiagKind = diag::err_int_to_block_pointer;
3055 break;
3056 case IncompatibleBlockPointer:
3057 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
3058 break;
3059 case BlockVoidPointer:
3060 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3061 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003062 case Incompatible:
3063 DiagKind = diag::err_typecheck_convert_incompatible;
3064 isInvalid = true;
3065 break;
3066 }
3067
3068 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3069 SrcExpr->getSourceRange());
3070 return isInvalid;
3071}