blob: dfa53ac4398651113eb97c0eccc1ae1be8a147d4 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner04421082008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27
Chris Lattnere7a2e912008-07-25 21:10:04 +000028//===----------------------------------------------------------------------===//
29// Standard Promotions and Conversions
30//===----------------------------------------------------------------------===//
31
Chris Lattnere7a2e912008-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 Lattner67d33d82008-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).
Argyrios Kyrtzidisc39a3d72008-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 Lattner67d33d82008-07-25 21:33:13 +000057 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
58 }
Chris Lattnere7a2e912008-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 Lattner05faf172008-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 Lattnere7a2e912008-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 Lattnerb77792e2008-07-26 22:17:49 +0000111 QualType lhs =
112 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
113 QualType rhs =
114 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattnere7a2e912008-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 Narofff69936d2007-09-16 03:34:24 +0000266/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofff69936d2007-09-16 03:34:24 +0000273Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnera7ad98f2008-02-11 00:02:17 +0000283
284 // Verify that pascal strings aren't too large.
Anders Carlssonee98ac52007-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()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000289
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000290 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000291 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000292 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-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 Lattnera7ad98f2008-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
Reid Spencer5f016e22007-07-11 17:01:13 +0000305 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
306 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000307 Literal.AnyWide, StrTy,
Anders Carlssonee98ac52007-10-15 02:50:23 +0000308 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 StringToks[NumStringToks-1].getLocation());
310}
311
Steve Naroffdd972f22008-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}
Reid Spencer5f016e22007-07-11 17:01:13 +0000330
Steve Naroff08d92e42007-09-15 18:49:24 +0000331/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000332/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000333/// identifier is used in a function call context.
Steve Naroff08d92e42007-09-15 18:49:24 +0000334Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 IdentifierInfo &II,
336 bool HasTrailingLParen) {
Chris Lattner8a934232008-03-31 00:36:02 +0000337 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroffb327ce02008-04-02 14:35:35 +0000338 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattner8a934232008-03-31 00:36:02 +0000339
340 // If this reference is in an Objective-C method, then ivar lookup happens as
341 // well.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000342 if (getCurMethodDecl()) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000343 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattner8a934232008-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 Naroffe8043c32008-04-01 23:04:06 +0000349 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000350 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattner123a11f2008-07-21 04:44:44 +0000351 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattner8a934232008-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 Naroff76de9d72008-08-10 19:10:41 +0000360 // Needed to implement property "super.method" notation.
Daniel Dunbar662e8b52008-08-14 22:04:54 +0000361 if (SD == 0 && &II == SuperID) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000362 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000363 getCurMethodDecl()->getClassInterface()));
Steve Naroff76de9d72008-08-10 19:10:41 +0000364 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000365 }
Chris Lattner8a934232008-03-31 00:36:02 +0000366 }
Steve Naroff1f3b0d52008-09-10 18:33:00 +0000367 // If we are parsing a block, check the block parameter list.
368 if (CurBlock) {
Steve Naroff538afe32008-09-28 00:13:36 +0000369 BlockSemaInfo *BLK = CurBlock;
370 do {
371 for (unsigned i = 0, e = BLK->Params.size(); i != e && D == 0; ++i)
372 if (BLK->Params[i]->getIdentifier() == &II)
373 D = BLK->Params[i];
374 if (D)
375 break; // Found!
376 } while ((BLK = BLK->PrevBlockInfo)); // Look through any enclosing blocks.
Steve Naroff1f3b0d52008-09-10 18:33:00 +0000377 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 if (D == 0) {
379 // Otherwise, this could be an implicitly declared function reference (legal
380 // in C90, extension in C99).
381 if (HasTrailingLParen &&
Chris Lattner8a934232008-03-31 00:36:02 +0000382 !getLangOptions().CPlusPlus) // Not in C++.
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 D = ImplicitlyDefineFunction(Loc, II, S);
384 else {
385 // If this name wasn't predeclared and if this is not a function call,
386 // diagnose the problem.
387 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
388 }
389 }
Chris Lattner8a934232008-03-31 00:36:02 +0000390
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000391 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
392 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
393 if (MD->isStatic())
394 // "invalid use of member 'x' in static member function"
395 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
396 FD->getName());
397 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
398 // "invalid use of nonstatic data member 'x'"
399 return Diag(Loc, diag::err_invalid_non_static_member_use,
400 FD->getName());
401
402 if (FD->isInvalidDecl())
403 return true;
404
405 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
406 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
407 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
408 true, FD, Loc, FD->getType());
409 }
410
411 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
412 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000413 if (isa<TypedefDecl>(D))
414 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000415 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian5ef404f2007-12-05 18:16:33 +0000416 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000417 if (isa<NamespaceDecl>(D))
418 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000419
Steve Naroffdd972f22008-09-05 22:11:13 +0000420 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
421 ValueDecl *VD = cast<ValueDecl>(D);
422
423 // check if referencing an identifier with __attribute__((deprecated)).
424 if (VD->getAttr<DeprecatedAttr>())
425 Diag(Loc, diag::warn_deprecated, VD->getName());
426
427 // Only create DeclRefExpr's for valid Decl's.
428 if (VD->isInvalidDecl())
429 return true;
430
431 // If this reference is not in a block or if the referenced variable is
432 // within the block, create a normal DeclRefExpr.
433 //
434 // FIXME: This will create BlockDeclRefExprs for global variables,
435 // function references, enums constants, etc which is suboptimal :) and breaks
436 // things like "integer constant expression" tests.
437 //
438 if (!CurBlock || DeclDefinedWithinScope(VD, CurBlock->TheScope, S))
439 return new DeclRefExpr(VD, VD->getType(), Loc);
440
441 // If we are in a block and the variable is outside the current block,
442 // bind the variable reference with a BlockDeclRefExpr.
443
Steve Naroff33ae3af2008-09-22 15:31:56 +0000444 // The BlocksAttr indicates the variable is bound by-reference.
445 if (VD->getAttr<BlocksAttr>())
446 return new BlockDeclRefExpr(VD, VD->getType(), Loc, true);
Steve Naroffdd972f22008-09-05 22:11:13 +0000447
Steve Naroff33ae3af2008-09-22 15:31:56 +0000448 // Variable will be bound by-copy, make it const within the closure.
449 VD->getType().addConst();
Steve Naroffdd972f22008-09-05 22:11:13 +0000450 return new BlockDeclRefExpr(VD, VD->getType(), Loc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000451}
452
Chris Lattnerd9f69102008-08-10 01:53:14 +0000453Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000454 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000455 PredefinedExpr::IdentType IT;
Anders Carlsson22742662007-07-21 05:21:51 +0000456
Reid Spencer5f016e22007-07-11 17:01:13 +0000457 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000458 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000459 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
460 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
461 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000462 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000463
464 // Verify that this is in a function context.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000465 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattner1423ea42008-01-12 18:39:25 +0000466 return Diag(Loc, diag::err_predef_outside_function);
Anders Carlsson22742662007-07-21 05:21:51 +0000467
Chris Lattnerfa28b302008-01-12 08:14:25 +0000468 // Pre-defined identifiers are of type char[x], where x is the length of the
469 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000470 unsigned Length;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000471 if (getCurFunctionDecl())
472 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattner8f978d52008-01-12 19:32:28 +0000473 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000474 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattner1423ea42008-01-12 18:39:25 +0000475
Chris Lattner8f978d52008-01-12 19:32:28 +0000476 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000477 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000478 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerd9f69102008-08-10 01:53:14 +0000479 return new PredefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000480}
481
Steve Narofff69936d2007-09-16 03:34:24 +0000482Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000483 llvm::SmallString<16> CharBuffer;
484 CharBuffer.resize(Tok.getLength());
485 const char *ThisTokBegin = &CharBuffer[0];
486 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
487
488 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
489 Tok.getLocation(), PP);
490 if (Literal.hadError())
491 return ExprResult(true);
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000492
493 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
494
Chris Lattnerc250aae2008-06-07 22:35:38 +0000495 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
496 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000497}
498
Steve Narofff69936d2007-09-16 03:34:24 +0000499Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 // fast path for a single digit (which is quite common). A single digit
501 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
502 if (Tok.getLength() == 1) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000503 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000504
Chris Lattner98be4942008-03-05 18:54:05 +0000505 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000506 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +0000507 Context.IntTy,
508 Tok.getLocation()));
509 }
510 llvm::SmallString<512> IntegerBuffer;
511 IntegerBuffer.resize(Tok.getLength());
512 const char *ThisTokBegin = &IntegerBuffer[0];
513
514 // Get the spelling of the token, which eliminates trigraphs, etc.
515 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
516 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
517 Tok.getLocation(), PP);
518 if (Literal.hadError)
519 return ExprResult(true);
520
Chris Lattner5d661452007-08-26 03:42:43 +0000521 Expr *Res;
522
523 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000524 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000525 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000526 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000527 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000528 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000529 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000530 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000531
532 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
533
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000534 // isExact will be set by GetFloatValue().
535 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000536 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000537 Ty, Tok.getLocation());
538
Chris Lattner5d661452007-08-26 03:42:43 +0000539 } else if (!Literal.isIntegerLiteral()) {
540 return ExprResult(true);
541 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000542 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000543
Neil Boothb9449512007-08-29 22:00:19 +0000544 // long long is a C99 feature.
545 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000546 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000547 Diag(Tok.getLocation(), diag::ext_longlong);
548
Reid Spencer5f016e22007-07-11 17:01:13 +0000549 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000550 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000551
552 if (Literal.GetIntegerValue(ResultVal)) {
553 // If this value didn't fit into uintmax_t, warn and force to ull.
554 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000555 Ty = Context.UnsignedLongLongTy;
556 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000557 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000558 } else {
559 // If this value fits into a ULL, try to figure out what else it fits into
560 // according to the rules of C99 6.4.4.1p5.
561
562 // Octal, Hexadecimal, and integers with a U suffix are allowed to
563 // be an unsigned int.
564 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
565
566 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000567 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000568 if (!Literal.isLong && !Literal.isLongLong) {
569 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000570 unsigned IntSize = Context.Target.getIntWidth();
571
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 // Does it fit in a unsigned int?
573 if (ResultVal.isIntN(IntSize)) {
574 // Does it fit in a signed int?
575 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000576 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000578 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000579 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000580 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000581 }
582
583 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000584 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000585 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000586
587 // Does it fit in a unsigned long?
588 if (ResultVal.isIntN(LongSize)) {
589 // Does it fit in a signed long?
590 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000591 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000592 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000593 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000594 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000596 }
597
598 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000599 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000600 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000601
602 // Does it fit in a unsigned long long?
603 if (ResultVal.isIntN(LongLongSize)) {
604 // Does it fit in a signed long long?
605 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000606 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000607 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000608 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000609 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000610 }
611 }
612
613 // If we still couldn't decide a type, we probably have something that
614 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000615 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000616 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000617 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000618 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000619 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000620
621 if (ResultVal.getBitWidth() != Width)
622 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000623 }
624
Chris Lattnerf0467b32008-04-02 04:24:33 +0000625 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000626 }
Chris Lattner5d661452007-08-26 03:42:43 +0000627
628 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
629 if (Literal.isImaginary)
630 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
631
632 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000633}
634
Steve Narofff69936d2007-09-16 03:34:24 +0000635Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000636 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000637 Expr *E = (Expr *)Val;
638 assert((E != 0) && "ActOnParenExpr() missing expr");
639 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +0000640}
641
642/// The UsualUnaryConversions() function is *not* called by this routine.
643/// See C99 6.3.2.1p[2-4] for more details.
644QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000645 SourceLocation OpLoc,
646 const SourceRange &ExprRange,
647 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000648 // C99 6.5.3.4p1:
649 if (isa<FunctionType>(exprType) && isSizeof)
650 // alignof(function) is allowed.
Chris Lattnerbb280a42008-07-25 21:45:37 +0000651 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000652 else if (exprType->isVoidType())
Chris Lattnerbb280a42008-07-25 21:45:37 +0000653 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
654 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000655 else if (exprType->isIncompleteType()) {
656 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
657 diag::err_alignof_incomplete_type,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000658 exprType.getAsString(), ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000659 return QualType(); // error
660 }
661 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
662 return Context.getSizeType();
663}
664
665Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000666ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +0000667 SourceLocation LPLoc, TypeTy *Ty,
668 SourceLocation RPLoc) {
669 // If error parsing type, ignore.
670 if (Ty == 0) return true;
671
672 // Verify that this is a valid expression.
673 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
674
Chris Lattnerbb280a42008-07-25 21:45:37 +0000675 QualType resultType =
676 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Reid Spencer5f016e22007-07-11 17:01:13 +0000677
678 if (resultType.isNull())
679 return true;
680 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
681}
682
Chris Lattner5d794252007-08-24 21:41:10 +0000683QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000684 DefaultFunctionArrayConversion(V);
685
Chris Lattnercc26ed72007-08-26 05:39:26 +0000686 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000687 if (const ComplexType *CT = V->getType()->getAsComplexType())
688 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000689
690 // Otherwise they pass through real integer and floating point types here.
691 if (V->getType()->isArithmeticType())
692 return V->getType();
693
694 // Reject anything else.
695 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
696 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000697}
698
699
Reid Spencer5f016e22007-07-11 17:01:13 +0000700
Steve Narofff69936d2007-09-16 03:34:24 +0000701Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000702 tok::TokenKind Kind,
703 ExprTy *Input) {
704 UnaryOperator::Opcode Opc;
705 switch (Kind) {
706 default: assert(0 && "Unknown unary op!");
707 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
708 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
709 }
710 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
711 if (result.isNull())
712 return true;
713 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
714}
715
716Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000717ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000718 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000719 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000720
721 // Perform default conversions.
722 DefaultFunctionArrayConversion(LHSExp);
723 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000724
Chris Lattner12d9ff62007-07-16 00:14:47 +0000725 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000726
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000728 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000729 // in the subscript position. As a result, we need to derive the array base
730 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000731 Expr *BaseExpr, *IndexExpr;
732 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000733 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000734 BaseExpr = LHSExp;
735 IndexExpr = RHSExp;
736 // FIXME: need to deal with const...
737 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000738 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000739 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000740 BaseExpr = RHSExp;
741 IndexExpr = LHSExp;
742 // FIXME: need to deal with const...
743 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000744 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
745 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000746 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000747
748 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +0000749 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
750 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begeman213541a2008-04-18 23:10:10 +0000751 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff608e0ee2007-08-03 22:40:33 +0000752 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000753 // FIXME: need to deal with const...
754 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000755 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000756 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
757 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000758 }
759 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000760 if (!IndexExpr->getType()->isIntegerType())
761 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
762 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000763
Chris Lattner12d9ff62007-07-16 00:14:47 +0000764 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
765 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +0000766 // void (*)(int)) and pointers to incomplete types. Functions are not
767 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000768 if (!ResultType->isObjectType())
769 return Diag(BaseExpr->getLocStart(),
770 diag::err_typecheck_subscript_not_object,
771 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
772
773 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000774}
775
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000776QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +0000777CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000778 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +0000779 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +0000780
781 // This flag determines whether or not the component is to be treated as a
782 // special name, or a regular GLSL-style component access.
783 bool SpecialComponent = false;
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000784
785 // The vector accessor can't exceed the number of elements.
786 const char *compStr = CompName.getName();
787 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begeman213541a2008-04-18 23:10:10 +0000788 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000789 baseType.getAsString(), SourceRange(CompLoc));
790 return QualType();
791 }
Nate Begeman8a997642008-05-09 06:41:27 +0000792
793 // Check that we've found one of the special components, or that the component
794 // names must come from the same set.
795 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
796 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
797 SpecialComponent = true;
798 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +0000799 do
800 compStr++;
801 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
802 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
803 do
804 compStr++;
805 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
806 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
807 do
808 compStr++;
809 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
810 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000811
Nate Begeman8a997642008-05-09 06:41:27 +0000812 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000813 // We didn't get to the end of the string. This means the component names
814 // didn't come from the same set *or* we encountered an illegal name.
Nate Begeman213541a2008-04-18 23:10:10 +0000815 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000816 std::string(compStr,compStr+1), SourceRange(CompLoc));
817 return QualType();
818 }
819 // Each component accessor can't exceed the vector type.
820 compStr = CompName.getName();
821 while (*compStr) {
822 if (vecType->isAccessorWithinNumElements(*compStr))
823 compStr++;
824 else
825 break;
826 }
Nate Begeman8a997642008-05-09 06:41:27 +0000827 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000828 // We didn't get to the end of the string. This means a component accessor
829 // exceeds the number of elements in the vector.
Nate Begeman213541a2008-04-18 23:10:10 +0000830 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000831 baseType.getAsString(), SourceRange(CompLoc));
832 return QualType();
833 }
Nate Begeman8a997642008-05-09 06:41:27 +0000834
835 // If we have a special component name, verify that the current vector length
836 // is an even number, since all special component names return exactly half
837 // the elements.
838 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
839 return QualType();
840 }
841
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000842 // The component accessor looks fine - now we need to compute the actual type.
843 // The vector type is implied by the component accessor. For example,
844 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +0000845 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
846 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
847 : strlen(CompName.getName());
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000848 if (CompSize == 1)
849 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000850
Nate Begeman213541a2008-04-18 23:10:10 +0000851 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +0000852 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +0000853 // diagostics look bad. We want extended vector types to appear built-in.
854 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
855 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
856 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +0000857 }
858 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000859}
860
Daniel Dunbar2307d312008-09-03 01:05:41 +0000861/// constructSetterName - Return the setter name for the given
862/// identifier, i.e. "set" + Name where the initial character of Name
863/// has been capitalized.
864// FIXME: Merge with same routine in Parser. But where should this
865// live?
866static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
867 const IdentifierInfo *Name) {
868 unsigned N = Name->getLength();
869 char *SelectorName = new char[3 + N];
870 memcpy(SelectorName, "set", 3);
871 memcpy(&SelectorName[3], Name->getName(), N);
872 SelectorName[3] = toupper(SelectorName[3]);
873
874 IdentifierInfo *Setter =
875 &Idents.get(SelectorName, &SelectorName[3 + N]);
876 delete[] SelectorName;
877 return Setter;
878}
879
Reid Spencer5f016e22007-07-11 17:01:13 +0000880Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000881ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000882 tok::TokenKind OpKind, SourceLocation MemberLoc,
883 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000884 Expr *BaseExpr = static_cast<Expr *>(Base);
885 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +0000886
887 // Perform default conversions.
888 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000889
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000890 QualType BaseType = BaseExpr->getType();
891 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000892
Chris Lattner68a057b2008-07-21 04:36:39 +0000893 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
894 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +0000895 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000896 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000897 BaseType = PT->getPointeeType();
898 else
Chris Lattner2a01b722008-07-21 05:35:34 +0000899 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
900 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000901 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000902
Chris Lattner68a057b2008-07-21 04:36:39 +0000903 // Handle field access to simple records. This also handles access to fields
904 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +0000905 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000906 RecordDecl *RDecl = RTy->getDecl();
907 if (RTy->isIncompleteType())
908 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
909 BaseExpr->getSourceRange());
910 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000911 FieldDecl *MemberDecl = RDecl->getMember(&Member);
912 if (!MemberDecl)
Chris Lattner2a01b722008-07-21 05:35:34 +0000913 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
914 BaseExpr->getSourceRange());
Eli Friedman51019072008-02-06 22:48:16 +0000915
916 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedman64ec0cc2008-02-07 05:24:51 +0000917 // FIXME: Handle address space modifiers
Eli Friedman51019072008-02-06 22:48:16 +0000918 QualType MemberType = MemberDecl->getType();
919 unsigned combinedQualifiers =
Chris Lattnerf46699c2008-02-20 20:55:12 +0000920 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman51019072008-02-06 22:48:16 +0000921 MemberType = MemberType.getQualifiedType(combinedQualifiers);
922
Chris Lattner68a057b2008-07-21 04:36:39 +0000923 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman51019072008-02-06 22:48:16 +0000924 MemberLoc, MemberType);
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000925 }
926
Chris Lattnera38e6b12008-07-21 04:59:05 +0000927 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
928 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +0000929 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
930 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000931 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000932 OpKind == tok::arrow);
Chris Lattner2a01b722008-07-21 05:35:34 +0000933 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner1f719742008-07-21 04:42:08 +0000934 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner2a01b722008-07-21 05:35:34 +0000935 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000936 }
937
Chris Lattnera38e6b12008-07-21 04:59:05 +0000938 // Handle Objective-C property access, which is "Obj.property" where Obj is a
939 // pointer to a (potentially qualified) interface type.
940 const PointerType *PTy;
941 const ObjCInterfaceType *IFTy;
942 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
943 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
944 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000945
Daniel Dunbar2307d312008-09-03 01:05:41 +0000946 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +0000947 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
948 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
949
Daniel Dunbar2307d312008-09-03 01:05:41 +0000950 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +0000951 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
952 E = IFTy->qual_end(); I != E; ++I)
953 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
954 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +0000955
956 // If that failed, look for an "implicit" property by seeing if the nullary
957 // selector is implemented.
958
959 // FIXME: The logic for looking up nullary and unary selectors should be
960 // shared with the code in ActOnInstanceMessage.
961
962 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
963 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
964
965 // If this reference is in an @implementation, check for 'private' methods.
966 if (!Getter)
967 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
968 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
969 if (ObjCImplementationDecl *ImpDecl =
970 ObjCImplementations[ClassDecl->getIdentifier()])
971 Getter = ImpDecl->getInstanceMethod(Sel);
972
973 if (Getter) {
974 // If we found a getter then this may be a valid dot-reference, we
975 // need to also look for the matching setter.
976 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
977 &Member);
978 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
979 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
980
981 if (!Setter) {
982 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
983 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
984 if (ObjCImplementationDecl *ImpDecl =
985 ObjCImplementations[ClassDecl->getIdentifier()])
986 Setter = ImpDecl->getInstanceMethod(SetterSel);
987 }
988
989 // FIXME: There are some issues here. First, we are not
990 // diagnosing accesses to read-only properties because we do not
991 // know if this is a getter or setter yet. Second, we are
992 // checking that the type of the setter matches the type we
993 // expect.
994 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
995 MemberLoc, BaseExpr);
996 }
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000997 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000998
999 // Handle 'field access' to vectors, such as 'V.xx'.
1000 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1001 // Component access limited to variables (reject vec4.rg.g).
1002 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1003 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner2a01b722008-07-21 05:35:34 +00001004 return Diag(MemberLoc, diag::err_ext_vector_component_access,
1005 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001006 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1007 if (ret.isNull())
1008 return true;
1009 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1010 }
1011
Chris Lattner2a01b722008-07-21 05:35:34 +00001012 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1013 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001014}
1015
Steve Narofff69936d2007-09-16 03:34:24 +00001016/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001017/// This provides the location of the left/right parens and a list of comma
1018/// locations.
1019Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001020ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +00001021 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +00001022 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +00001023 Expr *Fn = static_cast<Expr *>(fn);
1024 Expr **Args = reinterpret_cast<Expr**>(args);
1025 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001026 FunctionDecl *FDecl = NULL;
Chris Lattner04421082008-04-08 04:40:51 +00001027
1028 // Promote the function operand.
1029 UsualUnaryConversions(Fn);
1030
1031 // If we're directly calling a function, get the declaration for
1032 // that function.
1033 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1034 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
1035 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1036
Chris Lattner925e60d2007-12-28 05:29:59 +00001037 // Make the call expr early, before semantic checks. This guarantees cleanup
1038 // of arguments and function on error.
Chris Lattner8123a952008-04-10 02:22:51 +00001039 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001040 Context.BoolTy, RParenLoc));
Steve Naroffdd972f22008-09-05 22:11:13 +00001041 const FunctionType *FuncT;
1042 if (!Fn->getType()->isBlockPointerType()) {
1043 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1044 // have type pointer to function".
1045 const PointerType *PT = Fn->getType()->getAsPointerType();
1046 if (PT == 0)
1047 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1048 Fn->getSourceRange());
1049 FuncT = PT->getPointeeType()->getAsFunctionType();
1050 } else { // This is a block call.
1051 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1052 getAsFunctionType();
1053 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001054 if (FuncT == 0)
Chris Lattnerad2018f2008-08-14 04:33:24 +00001055 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1056 Fn->getSourceRange());
Chris Lattner925e60d2007-12-28 05:29:59 +00001057
1058 // We know the result type of the call, set it.
1059 TheCall->setType(FuncT->getResultType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001060
Chris Lattner925e60d2007-12-28 05:29:59 +00001061 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001062 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1063 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +00001064 unsigned NumArgsInProto = Proto->getNumArgs();
1065 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001066
Chris Lattner04421082008-04-08 04:40:51 +00001067 // If too few arguments are available (and we don't have default
1068 // arguments for the remaining parameters), don't make the call.
1069 if (NumArgs < NumArgsInProto) {
Chris Lattner8123a952008-04-10 02:22:51 +00001070 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner04421082008-04-08 04:40:51 +00001071 // Use default arguments for missing arguments
1072 NumArgsToCheck = NumArgsInProto;
Chris Lattner8123a952008-04-10 02:22:51 +00001073 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner04421082008-04-08 04:40:51 +00001074 } else
Steve Naroffdd972f22008-09-05 22:11:13 +00001075 return Diag(RParenLoc,
1076 !Fn->getType()->isBlockPointerType()
1077 ? diag::err_typecheck_call_too_few_args
1078 : diag::err_typecheck_block_too_few_args,
Chris Lattner04421082008-04-08 04:40:51 +00001079 Fn->getSourceRange());
1080 }
1081
Chris Lattner925e60d2007-12-28 05:29:59 +00001082 // If too many are passed and not variadic, error on the extras and drop
1083 // them.
1084 if (NumArgs > NumArgsInProto) {
1085 if (!Proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +00001086 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffdd972f22008-09-05 22:11:13 +00001087 !Fn->getType()->isBlockPointerType()
1088 ? diag::err_typecheck_call_too_many_args
1089 : diag::err_typecheck_block_too_many_args,
1090 Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +00001091 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner925e60d2007-12-28 05:29:59 +00001092 Args[NumArgs-1]->getLocEnd()));
1093 // This deletes the extra arguments.
1094 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +00001095 }
1096 NumArgsToCheck = NumArgsInProto;
1097 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001098
Reid Spencer5f016e22007-07-11 17:01:13 +00001099 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +00001100 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00001101 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner04421082008-04-08 04:40:51 +00001102
1103 Expr *Arg;
1104 if (i < NumArgs)
1105 Arg = Args[i];
1106 else
1107 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner5cf216b2008-01-04 18:04:52 +00001108 QualType ArgType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +00001109
Chris Lattner925e60d2007-12-28 05:29:59 +00001110 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001111 AssignConvertType ConvTy =
1112 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner925e60d2007-12-28 05:29:59 +00001113 TheCall->setArg(i, Arg);
Eli Friedmanf1c7b482008-09-02 05:09:35 +00001114
Chris Lattner5cf216b2008-01-04 18:04:52 +00001115 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1116 ArgType, Arg, "passing"))
1117 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001118 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001119
1120 // If this is a variadic call, handle args passed through "...".
1121 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +00001122 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-12-28 05:29:59 +00001123 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1124 Expr *Arg = Args[i];
1125 DefaultArgumentPromotion(Arg);
1126 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001127 }
Steve Naroffb291ab62007-08-28 23:30:39 +00001128 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001129 } else {
1130 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1131
Steve Naroffb291ab62007-08-28 23:30:39 +00001132 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001133 for (unsigned i = 0; i != NumArgs; i++) {
1134 Expr *Arg = Args[i];
1135 DefaultArgumentPromotion(Arg);
1136 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001137 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001138 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001139
Chris Lattner59907c42007-08-10 20:18:51 +00001140 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001141 if (FDecl)
1142 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001143
Chris Lattner925e60d2007-12-28 05:29:59 +00001144 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001145}
1146
1147Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001148ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +00001149 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001150 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001151 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001152 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001153 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +00001154 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +00001155
Eli Friedman6223c222008-05-20 05:22:08 +00001156 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001157 if (literalType->isVariableArrayType())
Eli Friedman6223c222008-05-20 05:22:08 +00001158 return Diag(LParenLoc,
1159 diag::err_variable_object_no_init,
1160 SourceRange(LParenLoc,
1161 literalExpr->getSourceRange().getEnd()));
1162 } else if (literalType->isIncompleteType()) {
1163 return Diag(LParenLoc,
1164 diag::err_typecheck_decl_incomplete_type,
1165 literalType.getAsString(),
1166 SourceRange(LParenLoc,
1167 literalExpr->getSourceRange().getEnd()));
1168 }
1169
Steve Naroffd0091aa2008-01-10 22:15:12 +00001170 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff58d18212008-01-09 20:58:06 +00001171 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +00001172
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001173 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffe9b12192008-01-14 18:19:28 +00001174 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001175 if (CheckForConstantInitializer(literalExpr, literalType))
1176 return true;
1177 }
Steve Naroffe9b12192008-01-14 18:19:28 +00001178 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001179}
1180
1181Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001182ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001183 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +00001184 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001185
Steve Naroff08d92e42007-09-15 18:49:24 +00001186 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001187 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001188
Chris Lattnerf0467b32008-04-02 04:24:33 +00001189 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1190 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1191 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001192}
1193
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001194/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001195bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001196 UsualUnaryConversions(castExpr);
1197
1198 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1199 // type needs to be scalar.
1200 if (castType->isVoidType()) {
1201 // Cast to void allows any expr type.
1202 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1203 // GCC struct/union extension: allow cast to self.
1204 if (Context.getCanonicalType(castType) !=
1205 Context.getCanonicalType(castExpr->getType()) ||
1206 (!castType->isStructureType() && !castType->isUnionType())) {
1207 // Reject any other conversions to non-scalar types.
1208 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1209 castType.getAsString(), castExpr->getSourceRange());
1210 }
1211
1212 // accept this, but emit an ext-warn.
1213 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1214 castType.getAsString(), castExpr->getSourceRange());
1215 } else if (!castExpr->getType()->isScalarType() &&
1216 !castExpr->getType()->isVectorType()) {
1217 return Diag(castExpr->getLocStart(),
1218 diag::err_typecheck_expect_scalar_operand,
1219 castExpr->getType().getAsString(),castExpr->getSourceRange());
1220 } else if (castExpr->getType()->isVectorType()) {
1221 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1222 return true;
1223 } else if (castType->isVectorType()) {
1224 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1225 return true;
1226 }
1227 return false;
1228}
1229
Chris Lattnerfe23e212007-12-20 00:44:32 +00001230bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00001231 assert(VectorTy->isVectorType() && "Not a vector type!");
1232
1233 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00001234 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00001235 return Diag(R.getBegin(),
1236 Ty->isVectorType() ?
1237 diag::err_invalid_conversion_between_vectors :
1238 diag::err_invalid_conversion_between_vector_and_integer,
1239 VectorTy.getAsString().c_str(),
1240 Ty.getAsString().c_str(), R);
1241 } else
1242 return Diag(R.getBegin(),
1243 diag::err_invalid_conversion_between_vector_and_scalar,
1244 VectorTy.getAsString().c_str(),
1245 Ty.getAsString().c_str(), R);
1246
1247 return false;
1248}
1249
Steve Naroff4aa88f82007-07-19 01:06:55 +00001250Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001251ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +00001252 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +00001253 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00001254
1255 Expr *castExpr = static_cast<Expr*>(Op);
1256 QualType castType = QualType::getFromOpaquePtr(Ty);
1257
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001258 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1259 return true;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001260 return new ExplicitCastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001261}
1262
Chris Lattnera21ddb32007-11-26 01:40:58 +00001263/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1264/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00001265inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00001266 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001267 UsualUnaryConversions(cond);
1268 UsualUnaryConversions(lex);
1269 UsualUnaryConversions(rex);
1270 QualType condT = cond->getType();
1271 QualType lexT = lex->getType();
1272 QualType rexT = rex->getType();
1273
Reid Spencer5f016e22007-07-11 17:01:13 +00001274 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +00001275 if (!condT->isScalarType()) { // C99 6.5.15p2
1276 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1277 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +00001278 return QualType();
1279 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001280
1281 // Now check the two expressions.
1282
1283 // If both operands have arithmetic type, do the usual arithmetic conversions
1284 // to find a common type: C99 6.5.15p3,5.
1285 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00001286 UsualArithmeticConversions(lex, rex);
1287 return lex->getType();
1288 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001289
1290 // If both operands are the same structure or union type, the result is that
1291 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001292 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00001293 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00001294 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00001295 // "If both the operands have structure or union type, the result has
1296 // that type." This implies that CV qualifiers are dropped.
1297 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001299
1300 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00001301 // The following || allows only one side to be void (a GCC-ism).
1302 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00001303 if (!lexT->isVoidType())
Steve Naroffe701c0a2008-05-12 21:44:38 +00001304 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1305 rex->getSourceRange());
1306 if (!rexT->isVoidType())
1307 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopesd8de7252008-06-04 19:14:12 +00001308 lex->getSourceRange());
Eli Friedman0e724012008-06-04 19:47:51 +00001309 ImpCastExprToType(lex, Context.VoidTy);
1310 ImpCastExprToType(rex, Context.VoidTy);
1311 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00001312 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00001313 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1314 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001315 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1316 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001317 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001318 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001319 return lexT;
1320 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001321 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1322 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001323 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001324 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001325 return rexT;
1326 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00001327 // Handle the case where both operands are pointers before we handle null
1328 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001329 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1330 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1331 // get the "pointed to" types
1332 QualType lhptee = LHSPT->getPointeeType();
1333 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001334
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001335 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1336 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00001337 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001338 // Figure out necessary qualifiers (C99 6.5.15p6)
1339 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001340 QualType destType = Context.getPointerType(destPointee);
1341 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1342 ImpCastExprToType(rex, destType); // promote to void*
1343 return destType;
1344 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00001345 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001346 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001347 QualType destType = Context.getPointerType(destPointee);
1348 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1349 ImpCastExprToType(rex, destType); // promote to void*
1350 return destType;
1351 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001352
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001353 QualType compositeType = lexT;
1354
1355 // If either type is an Objective-C object type then check
1356 // compatibility according to Objective-C.
1357 if (Context.isObjCObjectPointerType(lexT) ||
1358 Context.isObjCObjectPointerType(rexT)) {
1359 // If both operands are interfaces and either operand can be
1360 // assigned to the other, use that type as the composite
1361 // type. This allows
1362 // xxx ? (A*) a : (B*) b
1363 // where B is a subclass of A.
1364 //
1365 // Additionally, as for assignment, if either type is 'id'
1366 // allow silent coercion. Finally, if the types are
1367 // incompatible then make sure to use 'id' as the composite
1368 // type so the result is acceptable for sending messages to.
1369
1370 // FIXME: This code should not be localized to here. Also this
1371 // should use a compatible check instead of abusing the
1372 // canAssignObjCInterfaces code.
1373 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1374 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1375 if (LHSIface && RHSIface &&
1376 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1377 compositeType = lexT;
1378 } else if (LHSIface && RHSIface &&
1379 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1380 compositeType = rexT;
1381 } else if (Context.isObjCIdType(lhptee) ||
1382 Context.isObjCIdType(rhptee)) {
1383 // FIXME: This code looks wrong, because isObjCIdType checks
1384 // the struct but getObjCIdType returns the pointer to
1385 // struct. This is horrible and should be fixed.
1386 compositeType = Context.getObjCIdType();
1387 } else {
1388 QualType incompatTy = Context.getObjCIdType();
1389 ImpCastExprToType(lex, incompatTy);
1390 ImpCastExprToType(rex, incompatTy);
1391 return incompatTy;
1392 }
1393 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1394 rhptee.getUnqualifiedType())) {
Steve Naroffc0ff1ca2008-02-01 22:44:48 +00001395 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001396 lexT.getAsString(), rexT.getAsString(),
1397 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001398 // In this situation, we assume void* type. No especially good
1399 // reason, but this is what gcc does, and we do have to pick
1400 // to get a consistent AST.
1401 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00001402 ImpCastExprToType(lex, incompatTy);
1403 ImpCastExprToType(rex, incompatTy);
1404 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001405 }
1406 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001407 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1408 // differently qualified versions of compatible types, the result type is
1409 // a pointer to an appropriately qualified version of the *composite*
1410 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00001411 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00001412 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00001413 ImpCastExprToType(lex, compositeType);
1414 ImpCastExprToType(rex, compositeType);
1415 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001416 }
1417 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001418 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1419 // evaluates to "struct objc_object *" (and is handled above when comparing
1420 // id with statically typed objects).
1421 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1422 // GCC allows qualified id and any Objective-C type to devolve to
1423 // id. Currently localizing to here until clear this should be
1424 // part of ObjCQualifiedIdTypesAreCompatible.
1425 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1426 (lexT->isObjCQualifiedIdType() &&
1427 Context.isObjCObjectPointerType(rexT)) ||
1428 (rexT->isObjCQualifiedIdType() &&
1429 Context.isObjCObjectPointerType(lexT))) {
1430 // FIXME: This is not the correct composite type. This only
1431 // happens to work because id can more or less be used anywhere,
1432 // however this may change the type of method sends.
1433 // FIXME: gcc adds some type-checking of the arguments and emits
1434 // (confusing) incompatible comparison warnings in some
1435 // cases. Investigate.
1436 QualType compositeType = Context.getObjCIdType();
1437 ImpCastExprToType(lex, compositeType);
1438 ImpCastExprToType(rex, compositeType);
1439 return compositeType;
1440 }
1441 }
1442
Steve Naroff61f40a22008-09-10 19:17:48 +00001443 // Selection between block pointer types is ok as long as they are the same.
1444 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1445 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1446 return lexT;
1447
Chris Lattner70d67a92008-01-06 22:42:25 +00001448 // Otherwise, the operands are not compatible.
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +00001450 lexT.getAsString(), rexT.getAsString(),
1451 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001452 return QualType();
1453}
1454
Steve Narofff69936d2007-09-16 03:34:24 +00001455/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00001456/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00001457Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001458 SourceLocation ColonLoc,
1459 ExprTy *Cond, ExprTy *LHS,
1460 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00001461 Expr *CondExpr = (Expr *) Cond;
1462 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001463
1464 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1465 // was the condition.
1466 bool isLHSNull = LHSExpr == 0;
1467 if (isLHSNull)
1468 LHSExpr = CondExpr;
1469
Chris Lattner26824902007-07-16 21:39:03 +00001470 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1471 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 if (result.isNull())
1473 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001474 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1475 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001476}
1477
Reid Spencer5f016e22007-07-11 17:01:13 +00001478
1479// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1480// being closely modeled after the C99 spec:-). The odd characteristic of this
1481// routine is it effectively iqnores the qualifiers on the top level pointee.
1482// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1483// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001484Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001485Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1486 QualType lhptee, rhptee;
1487
1488 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001489 lhptee = lhsType->getAsPointerType()->getPointeeType();
1490 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001491
1492 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00001493 lhptee = Context.getCanonicalType(lhptee);
1494 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00001495
Chris Lattner5cf216b2008-01-04 18:04:52 +00001496 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001497
1498 // C99 6.5.16.1p1: This following citation is common to constraints
1499 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1500 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00001501 // FIXME: Handle ASQualType
1502 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1503 rhptee.getCVRQualifiers())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001504 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001505
1506 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1507 // incomplete type and the other is a pointer to a qualified or unqualified
1508 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001509 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001510 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001511 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001512
1513 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001514 assert(rhptee->isFunctionType());
1515 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001516 }
1517
1518 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001519 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001520 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001521
1522 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001523 assert(lhptee->isFunctionType());
1524 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001525 }
Eli Friedman3d815e72008-08-22 00:56:42 +00001526
1527 // Check for ObjC interfaces
1528 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1529 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1530 if (LHSIface && RHSIface &&
1531 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1532 return ConvTy;
1533
1534 // ID acts sort of like void* for ObjC interfaces
1535 if (LHSIface && Context.isObjCIdType(rhptee))
1536 return ConvTy;
1537 if (RHSIface && Context.isObjCIdType(lhptee))
1538 return ConvTy;
1539
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1541 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001542 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1543 rhptee.getUnqualifiedType()))
1544 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00001545 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001546}
1547
Steve Naroff1c7d0672008-09-04 15:10:53 +00001548/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1549/// block pointer types are compatible or whether a block and normal pointer
1550/// are compatible. It is more restrict than comparing two function pointer
1551// types.
1552Sema::AssignConvertType
1553Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1554 QualType rhsType) {
1555 QualType lhptee, rhptee;
1556
1557 // get the "pointed to" type (ignoring qualifiers at the top level)
1558 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1559 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1560
1561 // make sure we operate on the canonical type
1562 lhptee = Context.getCanonicalType(lhptee);
1563 rhptee = Context.getCanonicalType(rhptee);
1564
1565 AssignConvertType ConvTy = Compatible;
1566
1567 // For blocks we enforce that qualifiers are identical.
1568 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1569 ConvTy = CompatiblePointerDiscardsQualifiers;
1570
1571 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1572 return IncompatibleBlockPointer;
1573 return ConvTy;
1574}
1575
Reid Spencer5f016e22007-07-11 17:01:13 +00001576/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1577/// has code to accommodate several GCC extensions when type checking
1578/// pointers. Here are some objectionable examples that GCC considers warnings:
1579///
1580/// int a, *pint;
1581/// short *pshort;
1582/// struct foo *pfoo;
1583///
1584/// pint = pshort; // warning: assignment from incompatible pointer type
1585/// a = pint; // warning: assignment makes integer from pointer without a cast
1586/// pint = a; // warning: assignment makes pointer from integer without a cast
1587/// pint = pfoo; // warning: assignment from incompatible pointer type
1588///
1589/// As a result, the code for dealing with pointers is more complex than the
1590/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00001591///
Chris Lattner5cf216b2008-01-04 18:04:52 +00001592Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001593Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00001594 // Get canonical types. We're not formatting these types, just comparing
1595 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001596 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1597 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001598
1599 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00001600 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00001601
Anders Carlsson793680e2007-10-12 23:56:29 +00001602 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattner8f8fc7b2008-04-07 06:52:53 +00001603 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001604 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001605 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001606 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001607
Chris Lattnereca7be62008-04-07 05:30:13 +00001608 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1609 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001610 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00001611 // Relax integer conversions like we do for pointers below.
1612 if (rhsType->isIntegerType())
1613 return IntToPointer;
1614 if (lhsType->isIntegerType())
1615 return PointerToInt;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001616 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001617 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00001618
Nate Begemanbe2341d2008-07-14 18:02:46 +00001619 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001620 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00001621 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1622 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00001623 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001624
Nate Begemanbe2341d2008-07-14 18:02:46 +00001625 // If we are allowing lax vector conversions, and LHS and RHS are both
1626 // vectors, the total size only needs to be the same. This is a bitcast;
1627 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00001628 if (getLangOptions().LaxVectorConversions &&
1629 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001630 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1631 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00001632 }
1633 return Incompatible;
1634 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001635
Chris Lattnere8b3e962008-01-04 23:32:24 +00001636 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001637 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001638
Chris Lattner78eca282008-04-07 06:49:41 +00001639 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001641 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001642
Chris Lattner78eca282008-04-07 06:49:41 +00001643 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001644 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001645
Steve Naroffdd972f22008-09-05 22:11:13 +00001646 if (rhsType->getAsBlockPointerType())
1647 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff1c7d0672008-09-04 15:10:53 +00001648 return BlockVoidPointer;
1649
1650 return Incompatible;
1651 }
1652
1653 if (isa<BlockPointerType>(lhsType)) {
1654 if (rhsType->isIntegerType())
1655 return IntToPointer;
1656
1657 if (rhsType->isBlockPointerType())
1658 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1659
1660 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1661 if (RHSPT->getPointeeType()->isVoidType())
1662 return BlockVoidPointer;
1663 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00001664 return Incompatible;
1665 }
1666
Chris Lattner78eca282008-04-07 06:49:41 +00001667 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001669 if (lhsType == Context.BoolTy)
1670 return Compatible;
1671
1672 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001673 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00001674
Chris Lattner78eca282008-04-07 06:49:41 +00001675 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001676 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001677
1678 if (isa<BlockPointerType>(lhsType) &&
1679 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1680 return BlockVoidPointer;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001681 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001682 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001683
Chris Lattnerfc144e22008-01-04 23:18:45 +00001684 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00001685 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001686 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001687 }
1688 return Incompatible;
1689}
1690
Chris Lattner5cf216b2008-01-04 18:04:52 +00001691Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001692Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroff529a4ad2007-11-27 17:58:44 +00001693 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1694 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00001695 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1696 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00001697 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001698 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00001699 return Compatible;
1700 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001701
1702 // We don't allow conversion of non-null-pointer constants to integers.
1703 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1704 return IntToBlockPointer;
1705
Chris Lattner943140e2007-10-16 02:55:40 +00001706 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001707 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001708 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001709 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001710 //
1711 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1712 // are better understood.
1713 if (!lhsType->isReferenceType())
1714 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001715
Chris Lattner5cf216b2008-01-04 18:04:52 +00001716 Sema::AssignConvertType result =
1717 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00001718
1719 // C99 6.5.16.1p2: The value of the right operand is converted to the
1720 // type of the assignment expression.
1721 if (rExpr->getType() != lhsType)
Chris Lattner1e0a3902008-01-16 19:17:22 +00001722 ImpCastExprToType(rExpr, lhsType);
Steve Narofff1120de2007-08-24 22:33:52 +00001723 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001724}
1725
Chris Lattner5cf216b2008-01-04 18:04:52 +00001726Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001727Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1728 return CheckAssignmentConstraints(lhsType, rhsType);
1729}
1730
Chris Lattnerca5eede2007-12-12 05:47:28 +00001731QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001732 Diag(loc, diag::err_typecheck_invalid_operands,
1733 lex->getType().getAsString(), rex->getType().getAsString(),
1734 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerca5eede2007-12-12 05:47:28 +00001735 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001736}
1737
Steve Naroff49b45262007-07-13 16:58:59 +00001738inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1739 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00001740 // For conversion purposes, we ignore any qualifiers.
1741 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001742 QualType lhsType =
1743 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1744 QualType rhsType =
1745 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001746
Nate Begemanbe2341d2008-07-14 18:02:46 +00001747 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00001748 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001749 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00001750
Nate Begemanbe2341d2008-07-14 18:02:46 +00001751 // Handle the case of a vector & extvector type of the same size and element
1752 // type. It would be nice if we only had one vector type someday.
1753 if (getLangOptions().LaxVectorConversions)
1754 if (const VectorType *LV = lhsType->getAsVectorType())
1755 if (const VectorType *RV = rhsType->getAsVectorType())
1756 if (LV->getElementType() == RV->getElementType() &&
1757 LV->getNumElements() == RV->getNumElements())
1758 return lhsType->isExtVectorType() ? lhsType : rhsType;
1759
1760 // If the lhs is an extended vector and the rhs is a scalar of the same type
1761 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001762 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001763 QualType eltType = V->getElementType();
1764
1765 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1766 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1767 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001768 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001769 return lhsType;
1770 }
1771 }
1772
Nate Begemanbe2341d2008-07-14 18:02:46 +00001773 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00001774 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001775 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001776 QualType eltType = V->getElementType();
1777
1778 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1779 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1780 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001781 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001782 return rhsType;
1783 }
1784 }
1785
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 // You cannot convert between vector values of different size.
1787 Diag(loc, diag::err_typecheck_vector_not_convertable,
1788 lex->getType().getAsString(), rex->getType().getAsString(),
1789 lex->getSourceRange(), rex->getSourceRange());
1790 return QualType();
1791}
1792
1793inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001794 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001795{
Steve Naroff90045e82007-07-13 23:32:42 +00001796 QualType lhsType = lex->getType(), rhsType = rex->getType();
1797
1798 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001799 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001800
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001801 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001802
Steve Naroffa4332e22007-07-17 00:58:39 +00001803 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001804 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001805 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001806}
1807
1808inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001809 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001810{
Steve Naroff90045e82007-07-13 23:32:42 +00001811 QualType lhsType = lex->getType(), rhsType = rex->getType();
1812
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001813 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001814
Steve Naroffa4332e22007-07-17 00:58:39 +00001815 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001816 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001817 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001818}
1819
1820inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001821 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001822{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001823 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001824 return CheckVectorOperands(loc, lex, rex);
1825
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001826 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00001827
Reid Spencer5f016e22007-07-11 17:01:13 +00001828 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001829 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001830 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001831
Eli Friedmand72d16e2008-05-18 18:08:51 +00001832 // Put any potential pointer into PExp
1833 Expr* PExp = lex, *IExp = rex;
1834 if (IExp->getType()->isPointerType())
1835 std::swap(PExp, IExp);
1836
1837 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1838 if (IExp->getType()->isIntegerType()) {
1839 // Check for arithmetic on pointers to incomplete types
1840 if (!PTy->getPointeeType()->isObjectType()) {
1841 if (PTy->getPointeeType()->isVoidType()) {
1842 Diag(loc, diag::ext_gnu_void_ptr,
1843 lex->getSourceRange(), rex->getSourceRange());
1844 } else {
1845 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1846 lex->getType().getAsString(), lex->getSourceRange());
1847 return QualType();
1848 }
1849 }
1850 return PExp->getType();
1851 }
1852 }
1853
Chris Lattnerca5eede2007-12-12 05:47:28 +00001854 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001855}
1856
Chris Lattnereca7be62008-04-07 05:30:13 +00001857// C99 6.5.6
1858QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1859 SourceLocation loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00001860 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001861 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001862
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001863 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001864
Chris Lattner6e4ab612007-12-09 21:53:25 +00001865 // Enforce type constraints: C99 6.5.6p3.
1866
1867 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001868 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001869 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001870
1871 // Either ptr - int or ptr - ptr.
1872 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00001873 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00001874
Chris Lattner6e4ab612007-12-09 21:53:25 +00001875 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00001876 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001877 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001878 if (lpointee->isVoidType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001879 Diag(loc, diag::ext_gnu_void_ptr,
1880 lex->getSourceRange(), rex->getSourceRange());
1881 } else {
1882 Diag(loc, diag::err_typecheck_sub_ptr_object,
1883 lex->getType().getAsString(), lex->getSourceRange());
1884 return QualType();
1885 }
1886 }
1887
1888 // The result type of a pointer-int computation is the pointer type.
1889 if (rex->getType()->isIntegerType())
1890 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001891
Chris Lattner6e4ab612007-12-09 21:53:25 +00001892 // Handle pointer-pointer subtractions.
1893 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00001894 QualType rpointee = RHSPTy->getPointeeType();
1895
Chris Lattner6e4ab612007-12-09 21:53:25 +00001896 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00001897 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001898 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001899 if (rpointee->isVoidType()) {
1900 if (!lpointee->isVoidType())
Chris Lattner6e4ab612007-12-09 21:53:25 +00001901 Diag(loc, diag::ext_gnu_void_ptr,
1902 lex->getSourceRange(), rex->getSourceRange());
1903 } else {
1904 Diag(loc, diag::err_typecheck_sub_ptr_object,
1905 rex->getType().getAsString(), rex->getSourceRange());
1906 return QualType();
1907 }
1908 }
1909
1910 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00001911 if (!Context.typesAreCompatible(
1912 Context.getCanonicalType(lpointee).getUnqualifiedType(),
1913 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001914 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1915 lex->getType().getAsString(), rex->getType().getAsString(),
1916 lex->getSourceRange(), rex->getSourceRange());
1917 return QualType();
1918 }
1919
1920 return Context.getPointerDiffType();
1921 }
1922 }
1923
Chris Lattnerca5eede2007-12-12 05:47:28 +00001924 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001925}
1926
Chris Lattnereca7be62008-04-07 05:30:13 +00001927// C99 6.5.7
1928QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1929 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00001930 // C99 6.5.7p2: Each of the operands shall have integer type.
1931 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1932 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001933
Chris Lattnerca5eede2007-12-12 05:47:28 +00001934 // Shifts don't perform usual arithmetic conversions, they just do integer
1935 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00001936 if (!isCompAssign)
1937 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00001938 UsualUnaryConversions(rex);
1939
1940 // "The type of the result is that of the promoted left operand."
1941 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001942}
1943
Eli Friedman3d815e72008-08-22 00:56:42 +00001944static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
1945 ASTContext& Context) {
1946 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
1947 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
1948 // ID acts sort of like void* for ObjC interfaces
1949 if (LHSIface && Context.isObjCIdType(RHS))
1950 return true;
1951 if (RHSIface && Context.isObjCIdType(LHS))
1952 return true;
1953 if (!LHSIface || !RHSIface)
1954 return false;
1955 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
1956 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
1957}
1958
Chris Lattnereca7be62008-04-07 05:30:13 +00001959// C99 6.5.8
1960QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1961 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001962 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1963 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1964
Chris Lattnera5937dd2007-08-26 01:18:55 +00001965 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00001966 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1967 UsualArithmeticConversions(lex, rex);
1968 else {
1969 UsualUnaryConversions(lex);
1970 UsualUnaryConversions(rex);
1971 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001972 QualType lType = lex->getType();
1973 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001974
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001975 // For non-floating point types, check for self-comparisons of the form
1976 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1977 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001978 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001979 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1980 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001981 if (DRL->getDecl() == DRR->getDecl())
1982 Diag(loc, diag::warn_selfcomparison);
1983 }
1984
Chris Lattnera5937dd2007-08-26 01:18:55 +00001985 if (isRelational) {
1986 if (lType->isRealType() && rType->isRealType())
1987 return Context.IntTy;
1988 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001989 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001990 if (lType->isFloatingType()) {
1991 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001992 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00001993 }
1994
Chris Lattnera5937dd2007-08-26 01:18:55 +00001995 if (lType->isArithmeticType() && rType->isArithmeticType())
1996 return Context.IntTy;
1997 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001998
Chris Lattnerd28f8152007-08-26 01:10:14 +00001999 bool LHSIsNull = lex->isNullPointerConstant(Context);
2000 bool RHSIsNull = rex->isNullPointerConstant(Context);
2001
Chris Lattnera5937dd2007-08-26 01:18:55 +00002002 // All of the following pointer related warnings are GCC extensions, except
2003 // when handling null pointer constants. One day, we can consider making them
2004 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002005 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002006 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002007 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002008 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002009 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002010
Steve Naroff66296cb2007-11-13 14:57:38 +00002011 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002012 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2013 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002014 RCanPointeeTy.getUnqualifiedType()) &&
2015 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002016 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2017 lType.getAsString(), rType.getAsString(),
2018 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002019 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002020 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002021 return Context.IntTy;
2022 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002023 // Handle block pointer types.
2024 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2025 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2026 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2027
2028 if (!LHSIsNull && !RHSIsNull &&
2029 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2030 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2031 lType.getAsString(), rType.getAsString(),
2032 lex->getSourceRange(), rex->getSourceRange());
2033 }
2034 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2035 return Context.IntTy;
2036 }
2037
Steve Naroff20373222008-06-03 14:04:54 +00002038 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
2039 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2040 ImpCastExprToType(rex, lType);
2041 return Context.IntTy;
2042 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00002043 }
Steve Naroff20373222008-06-03 14:04:54 +00002044 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2045 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002046 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002047 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2048 lType.getAsString(), rType.getAsString(),
2049 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00002050 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002051 return Context.IntTy;
2052 }
Steve Naroff20373222008-06-03 14:04:54 +00002053 if (lType->isIntegerType() &&
2054 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002055 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002056 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2057 lType.getAsString(), rType.getAsString(),
2058 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00002059 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002060 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002061 }
Steve Naroff39218df2008-09-04 16:56:14 +00002062 // Handle block pointers.
2063 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2064 if (!RHSIsNull)
2065 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2066 lType.getAsString(), rType.getAsString(),
2067 lex->getSourceRange(), rex->getSourceRange());
2068 ImpCastExprToType(rex, lType); // promote the integer to pointer
2069 return Context.IntTy;
2070 }
2071 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2072 if (!LHSIsNull)
2073 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2074 lType.getAsString(), rType.getAsString(),
2075 lex->getSourceRange(), rex->getSourceRange());
2076 ImpCastExprToType(lex, rType); // promote the integer to pointer
2077 return Context.IntTy;
2078 }
Chris Lattnerca5eede2007-12-12 05:47:28 +00002079 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002080}
2081
Nate Begemanbe2341d2008-07-14 18:02:46 +00002082/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2083/// operates on extended vector types. Instead of producing an IntTy result,
2084/// like a scalar comparison, a vector comparison produces a vector of integer
2085/// types.
2086QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2087 SourceLocation loc,
2088 bool isRelational) {
2089 // Check to make sure we're operating on vectors of the same type and width,
2090 // Allowing one side to be a scalar of element type.
2091 QualType vType = CheckVectorOperands(loc, lex, rex);
2092 if (vType.isNull())
2093 return vType;
2094
2095 QualType lType = lex->getType();
2096 QualType rType = rex->getType();
2097
2098 // For non-floating point types, check for self-comparisons of the form
2099 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2100 // often indicate logic errors in the program.
2101 if (!lType->isFloatingType()) {
2102 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2103 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2104 if (DRL->getDecl() == DRR->getDecl())
2105 Diag(loc, diag::warn_selfcomparison);
2106 }
2107
2108 // Check for comparisons of floating point operands using != and ==.
2109 if (!isRelational && lType->isFloatingType()) {
2110 assert (rType->isFloatingType());
2111 CheckFloatComparison(loc,lex,rex);
2112 }
2113
2114 // Return the type for the comparison, which is the same as vector type for
2115 // integer vectors, or an integer type of identical size and number of
2116 // elements for floating point vectors.
2117 if (lType->isIntegerType())
2118 return lType;
2119
2120 const VectorType *VTy = lType->getAsVectorType();
2121
2122 // FIXME: need to deal with non-32b int / non-64b long long
2123 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2124 if (TypeSize == 32) {
2125 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2126 }
2127 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2128 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2129}
2130
Reid Spencer5f016e22007-07-11 17:01:13 +00002131inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002132 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002133{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002134 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002135 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002136
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002137 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002138
Steve Naroffa4332e22007-07-17 00:58:39 +00002139 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002140 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00002141 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002142}
2143
2144inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00002145 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00002146{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002147 UsualUnaryConversions(lex);
2148 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002149
Eli Friedman5773a6c2008-05-13 20:16:47 +00002150 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002151 return Context.IntTy;
Chris Lattnerca5eede2007-12-12 05:47:28 +00002152 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002153}
2154
2155inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00002156 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002157{
2158 QualType lhsType = lex->getType();
2159 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner28be73f2008-07-26 21:30:36 +00002160 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002161
2162 switch (mlval) { // C99 6.5.16p2
Chris Lattner5cf216b2008-01-04 18:04:52 +00002163 case Expr::MLV_Valid:
2164 break;
2165 case Expr::MLV_ConstQualified:
2166 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2167 return QualType();
2168 case Expr::MLV_ArrayType:
2169 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2170 lhsType.getAsString(), lex->getSourceRange());
2171 return QualType();
2172 case Expr::MLV_NotObjectType:
2173 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2174 lhsType.getAsString(), lex->getSourceRange());
2175 return QualType();
2176 case Expr::MLV_InvalidExpression:
2177 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2178 lex->getSourceRange());
2179 return QualType();
2180 case Expr::MLV_IncompleteType:
2181 case Expr::MLV_IncompleteVoidType:
2182 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2183 lhsType.getAsString(), lex->getSourceRange());
2184 return QualType();
2185 case Expr::MLV_DuplicateVectorComponents:
2186 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2187 lex->getSourceRange());
2188 return QualType();
Steve Naroff4f6a7d72008-09-26 14:41:28 +00002189 case Expr::MLV_NotBlockQualified:
2190 Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2191 lex->getSourceRange());
2192 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002193 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00002194
Chris Lattner5cf216b2008-01-04 18:04:52 +00002195 AssignConvertType ConvTy;
Chris Lattner2c156472008-08-21 18:04:13 +00002196 if (compoundType.isNull()) {
2197 // Simple assignment "x = y".
Chris Lattner5cf216b2008-01-04 18:04:52 +00002198 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner2c156472008-08-21 18:04:13 +00002199
2200 // If the RHS is a unary plus or minus, check to see if they = and + are
2201 // right next to each other. If so, the user may have typo'd "x =+ 4"
2202 // instead of "x += 4".
2203 Expr *RHSCheck = rex;
2204 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2205 RHSCheck = ICE->getSubExpr();
2206 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2207 if ((UO->getOpcode() == UnaryOperator::Plus ||
2208 UO->getOpcode() == UnaryOperator::Minus) &&
2209 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2210 // Only if the two operators are exactly adjacent.
2211 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2212 Diag(loc, diag::warn_not_compound_assign,
2213 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2214 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2215 }
2216 } else {
2217 // Compound assignment "x += y"
Chris Lattner5cf216b2008-01-04 18:04:52 +00002218 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner2c156472008-08-21 18:04:13 +00002219 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00002220
2221 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2222 rex, "assigning"))
2223 return QualType();
2224
Reid Spencer5f016e22007-07-11 17:01:13 +00002225 // C99 6.5.16p3: The type of an assignment expression is the type of the
2226 // left operand unless the left operand has qualified type, in which case
2227 // it is the unqualified version of the type of the left operand.
2228 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2229 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002230 // C++ 5.17p1: the type of the assignment expression is that of its left
2231 // oprdu.
Chris Lattner5cf216b2008-01-04 18:04:52 +00002232 return lhsType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002233}
2234
2235inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00002236 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00002237
2238 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2239 DefaultFunctionArrayConversion(rex);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002240 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002241}
2242
Steve Naroff49b45262007-07-13 16:58:59 +00002243/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2244/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00002245QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00002246 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002247 assert(!resType.isNull() && "no type for increment/decrement expression");
2248
Steve Naroff084f9ed2007-08-24 17:20:07 +00002249 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00002250 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00002251 if (pt->getPointeeType()->isVoidType()) {
2252 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2253 } else if (!pt->getPointeeType()->isObjectType()) {
2254 // C99 6.5.2.4p2, 6.5.6p2
Reid Spencer5f016e22007-07-11 17:01:13 +00002255 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2256 resType.getAsString(), op->getSourceRange());
2257 return QualType();
2258 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00002259 } else if (!resType->isRealType()) {
2260 if (resType->isComplexType())
2261 // C99 does not support ++/-- on complex types.
2262 Diag(OpLoc, diag::ext_integer_increment_complex,
2263 resType.getAsString(), op->getSourceRange());
2264 else {
2265 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2266 resType.getAsString(), op->getSourceRange());
2267 return QualType();
2268 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002269 }
Steve Naroffdd10e022007-08-23 21:37:33 +00002270 // At this point, we know we have a real, complex or pointer type.
2271 // Now make sure the operand is a modifiable lvalue.
Chris Lattner28be73f2008-07-26 21:30:36 +00002272 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002273 if (mlval != Expr::MLV_Valid) {
2274 // FIXME: emit a more precise diagnostic...
2275 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2276 op->getSourceRange());
2277 return QualType();
2278 }
2279 return resType;
2280}
2281
Anders Carlsson369dee42008-02-01 07:15:58 +00002282/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00002283/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002284/// where the declaration is needed for type checking. We only need to
2285/// handle cases when the expression references a function designator
2286/// or is an lvalue. Here are some examples:
2287/// - &(x) => x
2288/// - &*****f => f for f a function designator.
2289/// - &s.xx => s
2290/// - &s.zz[1].yy -> s, if zz is an array
2291/// - *(x + 1) -> x, if x is an array
2292/// - &"123"[2] -> 0
2293/// - & __real__ x -> x
Chris Lattnerf0467b32008-04-02 04:24:33 +00002294static ValueDecl *getPrimaryDecl(Expr *E) {
2295 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002296 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002297 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002298 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00002299 // Fields cannot be declared with a 'register' storage class.
2300 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002301 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00002302 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00002303 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00002304 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002305 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00002306
Chris Lattnerf0467b32008-04-02 04:24:33 +00002307 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlssonf2a4b842008-02-01 16:01:31 +00002308 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00002309 return 0;
2310 else
2311 return VD;
2312 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002313 case Stmt::UnaryOperatorClass: {
2314 UnaryOperator *UO = cast<UnaryOperator>(E);
2315
2316 switch(UO->getOpcode()) {
2317 case UnaryOperator::Deref: {
2318 // *(X + 1) refers to X if X is not a pointer.
2319 ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2320 if (!VD || VD->getType()->isPointerType())
2321 return 0;
2322 return VD;
2323 }
2324 case UnaryOperator::Real:
2325 case UnaryOperator::Imag:
2326 case UnaryOperator::Extension:
2327 return getPrimaryDecl(UO->getSubExpr());
2328 default:
2329 return 0;
2330 }
2331 }
2332 case Stmt::BinaryOperatorClass: {
2333 BinaryOperator *BO = cast<BinaryOperator>(E);
2334
2335 // Handle cases involving pointer arithmetic. The result of an
2336 // Assign or AddAssign is not an lvalue so they can be ignored.
2337
2338 // (x + n) or (n + x) => x
2339 if (BO->getOpcode() == BinaryOperator::Add) {
2340 if (BO->getLHS()->getType()->isPointerType()) {
2341 return getPrimaryDecl(BO->getLHS());
2342 } else if (BO->getRHS()->getType()->isPointerType()) {
2343 return getPrimaryDecl(BO->getRHS());
2344 }
2345 }
2346
2347 return 0;
2348 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002349 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002350 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00002351 case Stmt::ImplicitCastExprClass:
2352 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002353 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00002354 default:
2355 return 0;
2356 }
2357}
2358
2359/// CheckAddressOfOperand - The operand of & must be either a function
2360/// designator or an lvalue designating an object. If it is an lvalue, the
2361/// object cannot be declared with storage class register or be a bit field.
2362/// Note: The usual conversions are *not* applied to the operand of the &
2363/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2364QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff08f19672008-01-13 17:10:08 +00002365 if (getLangOptions().C99) {
2366 // Implement C99-only parts of addressof rules.
2367 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2368 if (uOp->getOpcode() == UnaryOperator::Deref)
2369 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2370 // (assuming the deref expression is valid).
2371 return uOp->getSubExpr()->getType();
2372 }
2373 // Technically, there should be a check for array subscript
2374 // expressions here, but the result of one is always an lvalue anyway.
2375 }
Anders Carlsson369dee42008-02-01 07:15:58 +00002376 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00002377 Expr::isLvalueResult lval = op->isLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002378
2379 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00002380 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2381 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00002382 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2383 op->getSourceRange());
2384 return QualType();
2385 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00002386 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2387 if (MemExpr->getMemberDecl()->isBitField()) {
2388 Diag(OpLoc, diag::err_typecheck_address_of,
2389 std::string("bit-field"), op->getSourceRange());
2390 return QualType();
2391 }
2392 // Check for Apple extension for accessing vector components.
2393 } else if (isa<ArraySubscriptExpr>(op) &&
2394 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2395 Diag(OpLoc, diag::err_typecheck_address_of,
2396 std::string("vector"), op->getSourceRange());
2397 return QualType();
2398 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00002399 // We have an lvalue with a decl. Make sure the decl is not declared
2400 // with the register storage-class specifier.
2401 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2402 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroffbcb2b612008-02-29 23:30:25 +00002403 Diag(OpLoc, diag::err_typecheck_address_of,
2404 std::string("register variable"), op->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002405 return QualType();
2406 }
2407 } else
2408 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002409 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00002410
Reid Spencer5f016e22007-07-11 17:01:13 +00002411 // If the operand has type "type", the result has type "pointer to type".
2412 return Context.getPointerType(op->getType());
2413}
2414
2415QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002416 UsualUnaryConversions(op);
2417 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002418
Chris Lattnerbefee482007-07-31 16:53:04 +00002419 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff08f19672008-01-13 17:10:08 +00002420 // Note that per both C89 and C99, this is always legal, even
2421 // if ptype is an incomplete type or void.
2422 // It would be possible to warn about dereferencing a
2423 // void pointer, but it's completely well-defined,
2424 // and such a warning is unlikely to catch any mistakes.
2425 return PT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002426 }
2427 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2428 qType.getAsString(), op->getSourceRange());
2429 return QualType();
2430}
2431
2432static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2433 tok::TokenKind Kind) {
2434 BinaryOperator::Opcode Opc;
2435 switch (Kind) {
2436 default: assert(0 && "Unknown binop!");
2437 case tok::star: Opc = BinaryOperator::Mul; break;
2438 case tok::slash: Opc = BinaryOperator::Div; break;
2439 case tok::percent: Opc = BinaryOperator::Rem; break;
2440 case tok::plus: Opc = BinaryOperator::Add; break;
2441 case tok::minus: Opc = BinaryOperator::Sub; break;
2442 case tok::lessless: Opc = BinaryOperator::Shl; break;
2443 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2444 case tok::lessequal: Opc = BinaryOperator::LE; break;
2445 case tok::less: Opc = BinaryOperator::LT; break;
2446 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2447 case tok::greater: Opc = BinaryOperator::GT; break;
2448 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2449 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2450 case tok::amp: Opc = BinaryOperator::And; break;
2451 case tok::caret: Opc = BinaryOperator::Xor; break;
2452 case tok::pipe: Opc = BinaryOperator::Or; break;
2453 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2454 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2455 case tok::equal: Opc = BinaryOperator::Assign; break;
2456 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2457 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2458 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2459 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2460 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2461 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2462 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2463 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2464 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2465 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2466 case tok::comma: Opc = BinaryOperator::Comma; break;
2467 }
2468 return Opc;
2469}
2470
2471static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2472 tok::TokenKind Kind) {
2473 UnaryOperator::Opcode Opc;
2474 switch (Kind) {
2475 default: assert(0 && "Unknown unary op!");
2476 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2477 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2478 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2479 case tok::star: Opc = UnaryOperator::Deref; break;
2480 case tok::plus: Opc = UnaryOperator::Plus; break;
2481 case tok::minus: Opc = UnaryOperator::Minus; break;
2482 case tok::tilde: Opc = UnaryOperator::Not; break;
2483 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2484 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2485 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2486 case tok::kw___real: Opc = UnaryOperator::Real; break;
2487 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2488 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2489 }
2490 return Opc;
2491}
2492
2493// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002494Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00002495 ExprTy *LHS, ExprTy *RHS) {
2496 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2497 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2498
Steve Narofff69936d2007-09-16 03:34:24 +00002499 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2500 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00002501
2502 QualType ResultTy; // Result type of the binary operator.
2503 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2504
2505 switch (Opc) {
2506 default:
2507 assert(0 && "Unknown binary expr!");
2508 case BinaryOperator::Assign:
2509 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2510 break;
2511 case BinaryOperator::Mul:
2512 case BinaryOperator::Div:
2513 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2514 break;
2515 case BinaryOperator::Rem:
2516 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2517 break;
2518 case BinaryOperator::Add:
2519 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2520 break;
2521 case BinaryOperator::Sub:
2522 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2523 break;
2524 case BinaryOperator::Shl:
2525 case BinaryOperator::Shr:
2526 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2527 break;
2528 case BinaryOperator::LE:
2529 case BinaryOperator::LT:
2530 case BinaryOperator::GE:
2531 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002532 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002533 break;
2534 case BinaryOperator::EQ:
2535 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002536 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002537 break;
2538 case BinaryOperator::And:
2539 case BinaryOperator::Xor:
2540 case BinaryOperator::Or:
2541 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2542 break;
2543 case BinaryOperator::LAnd:
2544 case BinaryOperator::LOr:
2545 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2546 break;
2547 case BinaryOperator::MulAssign:
2548 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002549 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002550 if (!CompTy.isNull())
2551 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2552 break;
2553 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002554 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002555 if (!CompTy.isNull())
2556 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2557 break;
2558 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002559 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002560 if (!CompTy.isNull())
2561 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2562 break;
2563 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002564 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002565 if (!CompTy.isNull())
2566 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2567 break;
2568 case BinaryOperator::ShlAssign:
2569 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002570 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002571 if (!CompTy.isNull())
2572 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2573 break;
2574 case BinaryOperator::AndAssign:
2575 case BinaryOperator::XorAssign:
2576 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002577 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002578 if (!CompTy.isNull())
2579 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2580 break;
2581 case BinaryOperator::Comma:
2582 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2583 break;
2584 }
2585 if (ResultTy.isNull())
2586 return true;
2587 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002588 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002589 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002590 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002591}
2592
2593// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002594Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00002595 ExprTy *input) {
2596 Expr *Input = (Expr*)input;
2597 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2598 QualType resultType;
2599 switch (Opc) {
2600 default:
2601 assert(0 && "Unimplemented unary expr!");
2602 case UnaryOperator::PreInc:
2603 case UnaryOperator::PreDec:
2604 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2605 break;
2606 case UnaryOperator::AddrOf:
2607 resultType = CheckAddressOfOperand(Input, OpLoc);
2608 break;
2609 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00002610 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002611 resultType = CheckIndirectionOperand(Input, OpLoc);
2612 break;
2613 case UnaryOperator::Plus:
2614 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002615 UsualUnaryConversions(Input);
2616 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002617 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2618 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2619 resultType.getAsString());
2620 break;
2621 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002622 UsualUnaryConversions(Input);
2623 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00002624 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2625 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2626 // C99 does not support '~' for complex conjugation.
2627 Diag(OpLoc, diag::ext_integer_complement_complex,
2628 resultType.getAsString(), Input->getSourceRange());
2629 else if (!resultType->isIntegerType())
2630 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2631 resultType.getAsString(), Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002632 break;
2633 case UnaryOperator::LNot: // logical negation
2634 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002635 DefaultFunctionArrayConversion(Input);
2636 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002637 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2638 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2639 resultType.getAsString());
2640 // LNot always has type int. C99 6.5.3.3p5.
2641 resultType = Context.IntTy;
2642 break;
2643 case UnaryOperator::SizeOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002644 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2645 Input->getSourceRange(), true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002646 break;
2647 case UnaryOperator::AlignOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002648 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2649 Input->getSourceRange(), false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002650 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00002651 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00002652 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00002653 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00002654 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002655 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 resultType = Input->getType();
2657 break;
2658 }
2659 if (resultType.isNull())
2660 return true;
2661 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2662}
2663
Steve Naroff1b273c42007-09-16 14:56:35 +00002664/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2665Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00002666 SourceLocation LabLoc,
2667 IdentifierInfo *LabelII) {
2668 // Look up the record for this label identifier.
2669 LabelStmt *&LabelDecl = LabelMap[LabelII];
2670
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00002671 // If we haven't seen this label yet, create a forward reference. It
2672 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00002673 if (LabelDecl == 0)
2674 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2675
2676 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00002677 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2678 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00002679}
2680
Steve Naroff1b273c42007-09-16 14:56:35 +00002681Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002682 SourceLocation RPLoc) { // "({..})"
2683 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2684 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2685 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2686
2687 // FIXME: there are a variety of strange constraints to enforce here, for
2688 // example, it is not possible to goto into a stmt expression apparently.
2689 // More semantic analysis is needed.
2690
2691 // FIXME: the last statement in the compount stmt has its value used. We
2692 // should not warn about it being unused.
2693
2694 // If there are sub stmts in the compound stmt, take the type of the last one
2695 // as the type of the stmtexpr.
2696 QualType Ty = Context.VoidTy;
2697
Chris Lattner611b2ec2008-07-26 19:51:01 +00002698 if (!Compound->body_empty()) {
2699 Stmt *LastStmt = Compound->body_back();
2700 // If LastStmt is a label, skip down through into the body.
2701 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2702 LastStmt = Label->getSubStmt();
2703
2704 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002705 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00002706 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002707
2708 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2709}
Steve Naroffd34e9152007-08-01 22:05:33 +00002710
Steve Naroff1b273c42007-09-16 14:56:35 +00002711Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002712 SourceLocation TypeLoc,
2713 TypeTy *argty,
2714 OffsetOfComponent *CompPtr,
2715 unsigned NumComponents,
2716 SourceLocation RPLoc) {
2717 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2718 assert(!ArgTy.isNull() && "Missing type argument!");
2719
2720 // We must have at least one component that refers to the type, and the first
2721 // one is known to be a field designator. Verify that the ArgTy represents
2722 // a struct/union/class.
2723 if (!ArgTy->isRecordType())
2724 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2725
2726 // Otherwise, create a compound literal expression as the base, and
2727 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00002728 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002729
Chris Lattner9e2b75c2007-08-31 21:49:13 +00002730 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2731 // GCC extension, diagnose them.
2732 if (NumComponents != 1)
2733 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2734 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2735
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002736 for (unsigned i = 0; i != NumComponents; ++i) {
2737 const OffsetOfComponent &OC = CompPtr[i];
2738 if (OC.isBrackets) {
2739 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002740 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002741 if (!AT) {
2742 delete Res;
2743 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2744 Res->getType().getAsString());
2745 }
2746
Chris Lattner704fe352007-08-30 17:59:59 +00002747 // FIXME: C++: Verify that operator[] isn't overloaded.
2748
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002749 // C99 6.5.2.1p1
2750 Expr *Idx = static_cast<Expr*>(OC.U.E);
2751 if (!Idx->getType()->isIntegerType())
2752 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2753 Idx->getSourceRange());
2754
2755 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2756 continue;
2757 }
2758
2759 const RecordType *RC = Res->getType()->getAsRecordType();
2760 if (!RC) {
2761 delete Res;
2762 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2763 Res->getType().getAsString());
2764 }
2765
2766 // Get the decl corresponding to this.
2767 RecordDecl *RD = RC->getDecl();
2768 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2769 if (!MemberDecl)
2770 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2771 OC.U.IdentInfo->getName(),
2772 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00002773
2774 // FIXME: C++: Verify that MemberDecl isn't a static field.
2775 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00002776 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2777 // matter here.
2778 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002779 }
2780
2781 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2782 BuiltinLoc);
2783}
2784
2785
Steve Naroff1b273c42007-09-16 14:56:35 +00002786Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00002787 TypeTy *arg1, TypeTy *arg2,
2788 SourceLocation RPLoc) {
2789 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2790 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2791
2792 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2793
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002794 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00002795}
2796
Steve Naroff1b273c42007-09-16 14:56:35 +00002797Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00002798 ExprTy *expr1, ExprTy *expr2,
2799 SourceLocation RPLoc) {
2800 Expr *CondExpr = static_cast<Expr*>(cond);
2801 Expr *LHSExpr = static_cast<Expr*>(expr1);
2802 Expr *RHSExpr = static_cast<Expr*>(expr2);
2803
2804 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2805
2806 // The conditional expression is required to be a constant expression.
2807 llvm::APSInt condEval(32);
2808 SourceLocation ExpLoc;
2809 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2810 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2811 CondExpr->getSourceRange());
2812
2813 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2814 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2815 RHSExpr->getType();
2816 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2817}
2818
Steve Naroff4eb206b2008-09-03 18:15:37 +00002819//===----------------------------------------------------------------------===//
2820// Clang Extensions.
2821//===----------------------------------------------------------------------===//
2822
2823/// ActOnBlockStart - This callback is invoked when a block literal is started.
2824void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope,
2825 Declarator &ParamInfo) {
2826 // Analyze block parameters.
2827 BlockSemaInfo *BSI = new BlockSemaInfo();
2828
2829 // Add BSI to CurBlock.
2830 BSI->PrevBlockInfo = CurBlock;
2831 CurBlock = BSI;
2832
2833 BSI->ReturnType = 0;
2834 BSI->TheScope = BlockScope;
2835
2836 // Analyze arguments to block.
2837 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2838 "Not a function declarator!");
2839 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2840
2841 BSI->hasPrototype = FTI.hasPrototype;
2842 BSI->isVariadic = true;
2843
2844 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2845 // no arguments, not a function that takes a single void argument.
2846 if (FTI.hasPrototype &&
2847 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2848 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2849 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2850 // empty arg list, don't push any params.
2851 BSI->isVariadic = false;
2852 } else if (FTI.hasPrototype) {
2853 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
2854 BSI->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2855 BSI->isVariadic = FTI.isVariadic;
2856 }
2857}
2858
2859/// ActOnBlockError - If there is an error parsing a block, this callback
2860/// is invoked to pop the information about the block from the action impl.
2861void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
2862 // Ensure that CurBlock is deleted.
2863 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
2864
2865 // Pop off CurBlock, handle nested blocks.
2866 CurBlock = CurBlock->PrevBlockInfo;
2867
2868 // FIXME: Delete the ParmVarDecl objects as well???
2869
2870}
2871
2872/// ActOnBlockStmtExpr - This is called when the body of a block statement
2873/// literal was successfully completed. ^(int x){...}
2874Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
2875 Scope *CurScope) {
2876 // Ensure that CurBlock is deleted.
2877 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2878 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
2879
2880 // Pop off CurBlock, handle nested blocks.
2881 CurBlock = CurBlock->PrevBlockInfo;
2882
2883 QualType RetTy = Context.VoidTy;
2884 if (BSI->ReturnType)
2885 RetTy = QualType(BSI->ReturnType, 0);
2886
2887 llvm::SmallVector<QualType, 8> ArgTypes;
2888 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
2889 ArgTypes.push_back(BSI->Params[i]->getType());
2890
2891 QualType BlockTy;
2892 if (!BSI->hasPrototype)
2893 BlockTy = Context.getFunctionTypeNoProto(RetTy);
2894 else
2895 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
2896 BSI->isVariadic);
2897
2898 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9c3c9022008-09-17 18:37:59 +00002899 return new BlockExpr(CaretLoc, BlockTy, &BSI->Params[0], BSI->Params.size(),
2900 Body.take());
Steve Naroff4eb206b2008-09-03 18:15:37 +00002901}
2902
Nate Begeman67295d02008-01-30 20:50:20 +00002903/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00002904/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00002905/// The number of arguments has already been validated to match the number of
2906/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002907static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2908 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00002909 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00002910 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002911 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2912 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00002913
2914 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00002915 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00002916 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00002917 return true;
2918}
2919
2920Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2921 SourceLocation *CommaLocs,
2922 SourceLocation BuiltinLoc,
2923 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00002924 // __builtin_overload requires at least 2 arguments
2925 if (NumArgs < 2)
2926 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2927 SourceRange(BuiltinLoc, RParenLoc));
Nate Begemane2ce1d92008-01-17 17:46:27 +00002928
Nate Begemane2ce1d92008-01-17 17:46:27 +00002929 // The first argument is required to be a constant expression. It tells us
2930 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00002931 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00002932 Expr *NParamsExpr = Args[0];
2933 llvm::APSInt constEval(32);
2934 SourceLocation ExpLoc;
2935 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2936 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2937 NParamsExpr->getSourceRange());
2938
2939 // Verify that the number of parameters is > 0
2940 unsigned NumParams = constEval.getZExtValue();
2941 if (NumParams == 0)
2942 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2943 NParamsExpr->getSourceRange());
2944 // Verify that we have at least 1 + NumParams arguments to the builtin.
2945 if ((NumParams + 1) > NumArgs)
2946 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2947 SourceRange(BuiltinLoc, RParenLoc));
2948
2949 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00002950 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00002951 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00002952 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2953 // UsualUnaryConversions will convert the function DeclRefExpr into a
2954 // pointer to function.
2955 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00002956 const FunctionTypeProto *FnType = 0;
2957 if (const PointerType *PT = Fn->getType()->getAsPointerType())
2958 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00002959
2960 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2961 // parameters, and the number of parameters must match the value passed to
2962 // the builtin.
2963 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begeman67295d02008-01-30 20:50:20 +00002964 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2965 Fn->getSourceRange());
Nate Begemane2ce1d92008-01-17 17:46:27 +00002966
2967 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00002968 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00002969 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002970 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00002971 if (OE)
2972 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2973 OE->getFn()->getSourceRange());
2974 // Remember our match, and continue processing the remaining arguments
2975 // to catch any errors.
2976 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2977 BuiltinLoc, RParenLoc);
2978 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00002979 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00002980 // Return the newly created OverloadExpr node, if we succeded in matching
2981 // exactly one of the candidate functions.
2982 if (OE)
2983 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00002984
2985 // If we didn't find a matching function Expr in the __builtin_overload list
2986 // the return an error.
2987 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00002988 for (unsigned i = 0; i != NumParams; ++i) {
2989 if (i != 0) typeNames += ", ";
2990 typeNames += Args[i+1]->getType().getAsString();
2991 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00002992
2993 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2994 SourceRange(BuiltinLoc, RParenLoc));
2995}
2996
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002997Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2998 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00002999 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003000 Expr *E = static_cast<Expr*>(expr);
3001 QualType T = QualType::getFromOpaquePtr(type);
3002
3003 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003004
3005 // Get the va_list type
3006 QualType VaListType = Context.getBuiltinVaListType();
3007 // Deal with implicit array decay; for example, on x86-64,
3008 // va_list is an array, but it's supposed to decay to
3009 // a pointer for va_arg.
3010 if (VaListType->isArrayType())
3011 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00003012 // Make sure the input expression also decays appropriately.
3013 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003014
3015 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003016 return Diag(E->getLocStart(),
3017 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3018 E->getType().getAsString(),
3019 E->getSourceRange());
3020
3021 // FIXME: Warn if a non-POD type is passed in.
3022
3023 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
3024}
3025
Chris Lattner5cf216b2008-01-04 18:04:52 +00003026bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3027 SourceLocation Loc,
3028 QualType DstType, QualType SrcType,
3029 Expr *SrcExpr, const char *Flavor) {
3030 // Decode the result (notice that AST's are still created for extensions).
3031 bool isInvalid = false;
3032 unsigned DiagKind;
3033 switch (ConvTy) {
3034 default: assert(0 && "Unknown conversion type");
3035 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003036 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00003037 DiagKind = diag::ext_typecheck_convert_pointer_int;
3038 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003039 case IntToPointer:
3040 DiagKind = diag::ext_typecheck_convert_int_pointer;
3041 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003042 case IncompatiblePointer:
3043 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3044 break;
3045 case FunctionVoidPointer:
3046 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3047 break;
3048 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00003049 // If the qualifiers lost were because we were applying the
3050 // (deprecated) C++ conversion from a string literal to a char*
3051 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3052 // Ideally, this check would be performed in
3053 // CheckPointerTypesForAssignment. However, that would require a
3054 // bit of refactoring (so that the second argument is an
3055 // expression, rather than a type), which should be done as part
3056 // of a larger effort to fix CheckPointerTypesForAssignment for
3057 // C++ semantics.
3058 if (getLangOptions().CPlusPlus &&
3059 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3060 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003061 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3062 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003063 case IntToBlockPointer:
3064 DiagKind = diag::err_int_to_block_pointer;
3065 break;
3066 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00003067 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003068 break;
3069 case BlockVoidPointer:
3070 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3071 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003072 case Incompatible:
3073 DiagKind = diag::err_typecheck_convert_incompatible;
3074 isInvalid = true;
3075 break;
3076 }
3077
3078 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3079 SrcExpr->getSourceRange());
3080 return isInvalid;
3081}