blob: 7886976aaf2bbdbabf83ebda6b891b6232785d19 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024using namespace clang;
25
Chris Lattner299b8842008-07-25 21:10:04 +000026//===----------------------------------------------------------------------===//
27// Standard Promotions and Conversions
28//===----------------------------------------------------------------------===//
29
Chris Lattner299b8842008-07-25 21:10:04 +000030/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
31void Sema::DefaultFunctionArrayConversion(Expr *&E) {
32 QualType Ty = E->getType();
33 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
34
35 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
36 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
37 Ty = E->getType();
38 }
39 if (Ty->isFunctionType())
40 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000041 else if (Ty->isArrayType()) {
42 // In C90 mode, arrays only promote to pointers if the array expression is
43 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
44 // type 'array of type' is converted to an expression that has type 'pointer
45 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
46 // that has type 'array of type' ...". The relevant change is "an lvalue"
47 // (C90) to "an expression" (C99).
Chris Lattner25168a52008-07-26 21:30:36 +000048 if (getLangOptions().C99 || E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000049 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
50 }
Chris Lattner299b8842008-07-25 21:10:04 +000051}
52
53/// UsualUnaryConversions - Performs various conversions that are common to most
54/// operators (C99 6.3). The conversions of array and function types are
55/// sometimes surpressed. For example, the array->pointer conversion doesn't
56/// apply if the array is an argument to the sizeof or address (&) operators.
57/// In these instances, this routine should *not* be called.
58Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
59 QualType Ty = Expr->getType();
60 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
61
62 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
63 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
64 Ty = Expr->getType();
65 }
66 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
67 ImpCastExprToType(Expr, Context.IntTy);
68 else
69 DefaultFunctionArrayConversion(Expr);
70
71 return Expr;
72}
73
Chris Lattner9305c3d2008-07-25 22:25:12 +000074/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
75/// do not have a prototype. Arguments that have type float are promoted to
76/// double. All other argument types are converted by UsualUnaryConversions().
77void Sema::DefaultArgumentPromotion(Expr *&Expr) {
78 QualType Ty = Expr->getType();
79 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
80
81 // If this is a 'float' (CVR qualified or typedef) promote to double.
82 if (const BuiltinType *BT = Ty->getAsBuiltinType())
83 if (BT->getKind() == BuiltinType::Float)
84 return ImpCastExprToType(Expr, Context.DoubleTy);
85
86 UsualUnaryConversions(Expr);
87}
88
Chris Lattner299b8842008-07-25 21:10:04 +000089/// UsualArithmeticConversions - Performs various conversions that are common to
90/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
91/// routine returns the first non-arithmetic type found. The client is
92/// responsible for emitting appropriate error diagnostics.
93/// FIXME: verify the conversion rules for "complex int" are consistent with
94/// GCC.
95QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
96 bool isCompAssign) {
97 if (!isCompAssign) {
98 UsualUnaryConversions(lhsExpr);
99 UsualUnaryConversions(rhsExpr);
100 }
101 // For conversion purposes, we ignore any qualifiers.
102 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000103 QualType lhs =
104 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
105 QualType rhs =
106 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattner299b8842008-07-25 21:10:04 +0000107
108 // If both types are identical, no conversion is needed.
109 if (lhs == rhs)
110 return lhs;
111
112 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
113 // The caller can deal with this (e.g. pointer + int).
114 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
115 return lhs;
116
117 // At this point, we have two different arithmetic types.
118
119 // Handle complex types first (C99 6.3.1.8p1).
120 if (lhs->isComplexType() || rhs->isComplexType()) {
121 // if we have an integer operand, the result is the complex type.
122 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
123 // convert the rhs to the lhs complex type.
124 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
125 return lhs;
126 }
127 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
128 // convert the lhs to the rhs complex type.
129 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
130 return rhs;
131 }
132 // This handles complex/complex, complex/float, or float/complex.
133 // When both operands are complex, the shorter operand is converted to the
134 // type of the longer, and that is the type of the result. This corresponds
135 // to what is done when combining two real floating-point operands.
136 // The fun begins when size promotion occur across type domains.
137 // From H&S 6.3.4: When one operand is complex and the other is a real
138 // floating-point type, the less precise type is converted, within it's
139 // real or complex domain, to the precision of the other type. For example,
140 // when combining a "long double" with a "double _Complex", the
141 // "double _Complex" is promoted to "long double _Complex".
142 int result = Context.getFloatingTypeOrder(lhs, rhs);
143
144 if (result > 0) { // The left side is bigger, convert rhs.
145 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
146 if (!isCompAssign)
147 ImpCastExprToType(rhsExpr, rhs);
148 } else if (result < 0) { // The right side is bigger, convert lhs.
149 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
150 if (!isCompAssign)
151 ImpCastExprToType(lhsExpr, lhs);
152 }
153 // At this point, lhs and rhs have the same rank/size. Now, make sure the
154 // domains match. This is a requirement for our implementation, C99
155 // does not require this promotion.
156 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
157 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
158 if (!isCompAssign)
159 ImpCastExprToType(lhsExpr, rhs);
160 return rhs;
161 } else { // handle "_Complex double, double".
162 if (!isCompAssign)
163 ImpCastExprToType(rhsExpr, lhs);
164 return lhs;
165 }
166 }
167 return lhs; // The domain/size match exactly.
168 }
169 // Now handle "real" floating types (i.e. float, double, long double).
170 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
171 // if we have an integer operand, the result is the real floating type.
172 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
173 // convert rhs to the lhs floating point type.
174 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
175 return lhs;
176 }
177 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
178 // convert lhs to the rhs floating point type.
179 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
180 return rhs;
181 }
182 // We have two real floating types, float/complex combos were handled above.
183 // Convert the smaller operand to the bigger result.
184 int result = Context.getFloatingTypeOrder(lhs, rhs);
185
186 if (result > 0) { // convert the rhs
187 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
188 return lhs;
189 }
190 if (result < 0) { // convert the lhs
191 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
192 return rhs;
193 }
194 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
195 }
196 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
197 // Handle GCC complex int extension.
198 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
199 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
200
201 if (lhsComplexInt && rhsComplexInt) {
202 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
203 rhsComplexInt->getElementType()) >= 0) {
204 // convert the rhs
205 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
206 return lhs;
207 }
208 if (!isCompAssign)
209 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
210 return rhs;
211 } else if (lhsComplexInt && rhs->isIntegerType()) {
212 // convert the rhs to the lhs complex type.
213 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
214 return lhs;
215 } else if (rhsComplexInt && lhs->isIntegerType()) {
216 // convert the lhs to the rhs complex type.
217 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
218 return rhs;
219 }
220 }
221 // Finally, we have two differing integer types.
222 // The rules for this case are in C99 6.3.1.8
223 int compare = Context.getIntegerTypeOrder(lhs, rhs);
224 bool lhsSigned = lhs->isSignedIntegerType(),
225 rhsSigned = rhs->isSignedIntegerType();
226 QualType destType;
227 if (lhsSigned == rhsSigned) {
228 // Same signedness; use the higher-ranked type
229 destType = compare >= 0 ? lhs : rhs;
230 } else if (compare != (lhsSigned ? 1 : -1)) {
231 // The unsigned type has greater than or equal rank to the
232 // signed type, so use the unsigned type
233 destType = lhsSigned ? rhs : lhs;
234 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
235 // The two types are different widths; if we are here, that
236 // means the signed type is larger than the unsigned type, so
237 // use the signed type.
238 destType = lhsSigned ? lhs : rhs;
239 } else {
240 // The signed type is higher-ranked than the unsigned type,
241 // but isn't actually any bigger (like unsigned int and long
242 // on most 32-bit systems). Use the unsigned type corresponding
243 // to the signed type.
244 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
245 }
246 if (!isCompAssign) {
247 ImpCastExprToType(lhsExpr, destType);
248 ImpCastExprToType(rhsExpr, destType);
249 }
250 return destType;
251}
252
253//===----------------------------------------------------------------------===//
254// Semantic Analysis for various Expression Types
255//===----------------------------------------------------------------------===//
256
257
Steve Naroff87d58b42007-09-16 03:34:24 +0000258/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000259/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
260/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
261/// multiple tokens. However, the common case is that StringToks points to one
262/// string.
263///
264Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000265Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000266 assert(NumStringToks && "Must have at least one string!");
267
268 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
269 if (Literal.hadError)
270 return ExprResult(true);
271
272 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
273 for (unsigned i = 0; i != NumStringToks; ++i)
274 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000275
276 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000277 if (Literal.Pascal && Literal.GetStringLength() > 256)
278 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
279 SourceRange(StringToks[0].getLocation(),
280 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000281
Chris Lattnera6dcce32008-02-11 00:02:17 +0000282 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000283 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000284 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
285
286 // Get an array type for the string, according to C99 6.4.5. This includes
287 // the nul terminator character as well as the string length for pascal
288 // strings.
289 StrTy = Context.getConstantArrayType(StrTy,
290 llvm::APInt(32, Literal.GetStringLength()+1),
291 ArrayType::Normal, 0);
292
Chris Lattner4b009652007-07-25 00:24:17 +0000293 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
294 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000295 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000296 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000297 StringToks[NumStringToks-1].getLocation());
298}
299
300
Steve Naroff0acc9c92007-09-15 18:49:24 +0000301/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000302/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000303/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000304Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000305 IdentifierInfo &II,
306 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000307 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +0000308 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000309
310 // If this reference is in an Objective-C method, then ivar lookup happens as
311 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000312 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000313 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000314 // There are two cases to handle here. 1) scoped lookup could have failed,
315 // in which case we should look for an ivar. 2) scoped lookup could have
316 // found a decl, but that decl is outside the current method (i.e. a global
317 // variable). In these two cases, we do a lookup for an ivar with this
318 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000319 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000320 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattnered94f762008-07-21 04:44:44 +0000321 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000322 // FIXME: This should use a new expr for a direct reference, don't turn
323 // this into Self->ivar, just return a BareIVarExpr or something.
324 IdentifierInfo &II = Context.Idents.get("self");
325 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
326 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
327 static_cast<Expr*>(SelfExpr.Val), true, true);
328 }
329 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000330 // Needed to implement property "super.method" notation.
Daniel Dunbar4837ae72008-08-14 22:04:54 +0000331 if (SD == 0 && &II == SuperID) {
Steve Naroff6f786252008-06-02 23:03:37 +0000332 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000333 getCurMethodDecl()->getClassInterface()));
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000334 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroff6f786252008-06-02 23:03:37 +0000335 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000336 }
337
Chris Lattner4b009652007-07-25 00:24:17 +0000338 if (D == 0) {
339 // Otherwise, this could be an implicitly declared function reference (legal
340 // in C90, extension in C99).
341 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000342 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000343 D = ImplicitlyDefineFunction(Loc, II, S);
344 else {
345 // If this name wasn't predeclared and if this is not a function call,
346 // diagnose the problem.
347 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
348 }
349 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000350
Steve Naroff91b03f72007-08-28 03:03:08 +0000351 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneree4c3bf2008-02-29 16:48:43 +0000352 // check if referencing an identifier with __attribute__((deprecated)).
353 if (VD->getAttr<DeprecatedAttr>())
354 Diag(Loc, diag::warn_deprecated, VD->getName());
355
Steve Naroffcae537d2007-08-28 18:45:29 +0000356 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000357 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000358 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000359 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000360 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000361
362 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
363 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
364 if (MD->isStatic())
365 // "invalid use of member 'x' in static member function"
366 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
367 FD->getName());
368 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
369 // "invalid use of nonstatic data member 'x'"
370 return Diag(Loc, diag::err_invalid_non_static_member_use,
371 FD->getName());
372
373 if (FD->isInvalidDecl())
374 return true;
375
376 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
377 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
378 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
379 true, FD, Loc, FD->getType());
380 }
381
382 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
383 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000384
Chris Lattner4b009652007-07-25 00:24:17 +0000385 if (isa<TypedefDecl>(D))
386 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000387 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000388 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000389 if (isa<NamespaceDecl>(D))
390 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000391
392 assert(0 && "Invalid decl");
393 abort();
394}
395
Chris Lattner69909292008-08-10 01:53:14 +0000396Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000397 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000398 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000399
400 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000401 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000402 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
403 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
404 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000405 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000406
407 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000408 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000409 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000410
Chris Lattner7e637512008-01-12 08:14:25 +0000411 // Pre-defined identifiers are of type char[x], where x is the length of the
412 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000413 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000414 if (getCurFunctionDecl())
415 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000416 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000417 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000418
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000419 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000420 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000421 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000422 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000423}
424
Steve Naroff87d58b42007-09-16 03:34:24 +0000425Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000426 llvm::SmallString<16> CharBuffer;
427 CharBuffer.resize(Tok.getLength());
428 const char *ThisTokBegin = &CharBuffer[0];
429 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
430
431 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
432 Tok.getLocation(), PP);
433 if (Literal.hadError())
434 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000435
436 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
437
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000438 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
439 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000440}
441
Steve Naroff87d58b42007-09-16 03:34:24 +0000442Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000443 // fast path for a single digit (which is quite common). A single digit
444 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
445 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000446 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000447
Chris Lattner8cd0e932008-03-05 18:54:05 +0000448 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000449 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000450 Context.IntTy,
451 Tok.getLocation()));
452 }
453 llvm::SmallString<512> IntegerBuffer;
454 IntegerBuffer.resize(Tok.getLength());
455 const char *ThisTokBegin = &IntegerBuffer[0];
456
457 // Get the spelling of the token, which eliminates trigraphs, etc.
458 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
459 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
460 Tok.getLocation(), PP);
461 if (Literal.hadError)
462 return ExprResult(true);
463
Chris Lattner1de66eb2007-08-26 03:42:43 +0000464 Expr *Res;
465
466 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000467 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000468 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000469 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000470 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000471 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000472 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000473 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000474
475 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
476
Ted Kremenekddedbe22007-11-29 00:56:49 +0000477 // isExact will be set by GetFloatValue().
478 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000479 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000480 Ty, Tok.getLocation());
481
Chris Lattner1de66eb2007-08-26 03:42:43 +0000482 } else if (!Literal.isIntegerLiteral()) {
483 return ExprResult(true);
484 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000485 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000486
Neil Booth7421e9c2007-08-29 22:00:19 +0000487 // long long is a C99 feature.
488 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000489 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000490 Diag(Tok.getLocation(), diag::ext_longlong);
491
Chris Lattner4b009652007-07-25 00:24:17 +0000492 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000493 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000494
495 if (Literal.GetIntegerValue(ResultVal)) {
496 // If this value didn't fit into uintmax_t, warn and force to ull.
497 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000498 Ty = Context.UnsignedLongLongTy;
499 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000500 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000501 } else {
502 // If this value fits into a ULL, try to figure out what else it fits into
503 // according to the rules of C99 6.4.4.1p5.
504
505 // Octal, Hexadecimal, and integers with a U suffix are allowed to
506 // be an unsigned int.
507 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
508
509 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000510 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000511 if (!Literal.isLong && !Literal.isLongLong) {
512 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000513 unsigned IntSize = Context.Target.getIntWidth();
514
Chris Lattner4b009652007-07-25 00:24:17 +0000515 // Does it fit in a unsigned int?
516 if (ResultVal.isIntN(IntSize)) {
517 // Does it fit in a signed int?
518 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000519 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000520 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000521 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000522 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000523 }
Chris Lattner4b009652007-07-25 00:24:17 +0000524 }
525
526 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000527 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000528 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000529
530 // Does it fit in a unsigned long?
531 if (ResultVal.isIntN(LongSize)) {
532 // Does it fit in a signed long?
533 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000534 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000535 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000536 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000537 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000538 }
Chris Lattner4b009652007-07-25 00:24:17 +0000539 }
540
541 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000542 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000543 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000544
545 // Does it fit in a unsigned long long?
546 if (ResultVal.isIntN(LongLongSize)) {
547 // Does it fit in a signed long long?
548 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000549 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000550 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000551 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000552 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000553 }
554 }
555
556 // If we still couldn't decide a type, we probably have something that
557 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000558 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000559 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000560 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000561 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000562 }
Chris Lattnere4068872008-05-09 05:59:00 +0000563
564 if (ResultVal.getBitWidth() != Width)
565 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000566 }
567
Chris Lattner48d7f382008-04-02 04:24:33 +0000568 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000569 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000570
571 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
572 if (Literal.isImaginary)
573 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
574
575 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000576}
577
Steve Naroff87d58b42007-09-16 03:34:24 +0000578Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000579 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000580 Expr *E = (Expr *)Val;
581 assert((E != 0) && "ActOnParenExpr() missing expr");
582 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000583}
584
585/// The UsualUnaryConversions() function is *not* called by this routine.
586/// See C99 6.3.2.1p[2-4] for more details.
587QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerf814d882008-07-25 21:45:37 +0000588 SourceLocation OpLoc,
589 const SourceRange &ExprRange,
590 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000591 // C99 6.5.3.4p1:
592 if (isa<FunctionType>(exprType) && isSizeof)
593 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000594 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000595 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000596 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
597 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000598 else if (exprType->isIncompleteType()) {
599 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
600 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000601 exprType.getAsString(), ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000602 return QualType(); // error
603 }
604 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
605 return Context.getSizeType();
606}
607
608Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000609ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000610 SourceLocation LPLoc, TypeTy *Ty,
611 SourceLocation RPLoc) {
612 // If error parsing type, ignore.
613 if (Ty == 0) return true;
614
615 // Verify that this is a valid expression.
616 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
617
Chris Lattnerf814d882008-07-25 21:45:37 +0000618 QualType resultType =
619 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Chris Lattner4b009652007-07-25 00:24:17 +0000620
621 if (resultType.isNull())
622 return true;
623 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
624}
625
Chris Lattner5110ad52007-08-24 21:41:10 +0000626QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000627 DefaultFunctionArrayConversion(V);
628
Chris Lattnera16e42d2007-08-26 05:39:26 +0000629 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000630 if (const ComplexType *CT = V->getType()->getAsComplexType())
631 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000632
633 // Otherwise they pass through real integer and floating point types here.
634 if (V->getType()->isArithmeticType())
635 return V->getType();
636
637 // Reject anything else.
638 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
639 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000640}
641
642
Chris Lattner4b009652007-07-25 00:24:17 +0000643
Steve Naroff87d58b42007-09-16 03:34:24 +0000644Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000645 tok::TokenKind Kind,
646 ExprTy *Input) {
647 UnaryOperator::Opcode Opc;
648 switch (Kind) {
649 default: assert(0 && "Unknown unary op!");
650 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
651 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
652 }
653 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
654 if (result.isNull())
655 return true;
656 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
657}
658
659Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000660ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000661 ExprTy *Idx, SourceLocation RLoc) {
662 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
663
664 // Perform default conversions.
665 DefaultFunctionArrayConversion(LHSExp);
666 DefaultFunctionArrayConversion(RHSExp);
667
668 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
669
670 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000671 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000672 // in the subscript position. As a result, we need to derive the array base
673 // and index from the expression types.
674 Expr *BaseExpr, *IndexExpr;
675 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000676 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000677 BaseExpr = LHSExp;
678 IndexExpr = RHSExp;
679 // FIXME: need to deal with const...
680 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000681 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000682 // Handle the uncommon case of "123[Ptr]".
683 BaseExpr = RHSExp;
684 IndexExpr = LHSExp;
685 // FIXME: need to deal with const...
686 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000687 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
688 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000689 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000690
691 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000692 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
693 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000694 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000695 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000696 // FIXME: need to deal with const...
697 ResultType = VTy->getElementType();
698 } else {
699 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
700 RHSExp->getSourceRange());
701 }
702 // C99 6.5.2.1p1
703 if (!IndexExpr->getType()->isIntegerType())
704 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
705 IndexExpr->getSourceRange());
706
707 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
708 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000709 // void (*)(int)) and pointers to incomplete types. Functions are not
710 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000711 if (!ResultType->isObjectType())
712 return Diag(BaseExpr->getLocStart(),
713 diag::err_typecheck_subscript_not_object,
714 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
715
716 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
717}
718
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000719QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000720CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000721 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000722 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000723
724 // This flag determines whether or not the component is to be treated as a
725 // special name, or a regular GLSL-style component access.
726 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000727
728 // The vector accessor can't exceed the number of elements.
729 const char *compStr = CompName.getName();
730 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000731 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000732 baseType.getAsString(), SourceRange(CompLoc));
733 return QualType();
734 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000735
736 // Check that we've found one of the special components, or that the component
737 // names must come from the same set.
738 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
739 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
740 SpecialComponent = true;
741 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000742 do
743 compStr++;
744 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
745 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
746 do
747 compStr++;
748 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
749 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
750 do
751 compStr++;
752 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
753 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000754
Nate Begemanc8e51f82008-05-09 06:41:27 +0000755 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000756 // We didn't get to the end of the string. This means the component names
757 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000758 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000759 std::string(compStr,compStr+1), SourceRange(CompLoc));
760 return QualType();
761 }
762 // Each component accessor can't exceed the vector type.
763 compStr = CompName.getName();
764 while (*compStr) {
765 if (vecType->isAccessorWithinNumElements(*compStr))
766 compStr++;
767 else
768 break;
769 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000770 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000771 // We didn't get to the end of the string. This means a component accessor
772 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000773 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000774 baseType.getAsString(), SourceRange(CompLoc));
775 return QualType();
776 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000777
778 // If we have a special component name, verify that the current vector length
779 // is an even number, since all special component names return exactly half
780 // the elements.
781 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
782 return QualType();
783 }
784
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000785 // The component accessor looks fine - now we need to compute the actual type.
786 // The vector type is implied by the component accessor. For example,
787 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000788 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
789 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
790 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000791 if (CompSize == 1)
792 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000793
Nate Begemanaf6ed502008-04-18 23:10:10 +0000794 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000795 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000796 // diagostics look bad. We want extended vector types to appear built-in.
797 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
798 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
799 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000800 }
801 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000802}
803
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000804/// constructSetterName - Return the setter name for the given
805/// identifier, i.e. "set" + Name where the initial character of Name
806/// has been capitalized.
807// FIXME: Merge with same routine in Parser. But where should this
808// live?
809static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
810 const IdentifierInfo *Name) {
811 unsigned N = Name->getLength();
812 char *SelectorName = new char[3 + N];
813 memcpy(SelectorName, "set", 3);
814 memcpy(&SelectorName[3], Name->getName(), N);
815 SelectorName[3] = toupper(SelectorName[3]);
816
817 IdentifierInfo *Setter =
818 &Idents.get(SelectorName, &SelectorName[3 + N]);
819 delete[] SelectorName;
820 return Setter;
821}
822
Chris Lattner4b009652007-07-25 00:24:17 +0000823Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000824ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000825 tok::TokenKind OpKind, SourceLocation MemberLoc,
826 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000827 Expr *BaseExpr = static_cast<Expr *>(Base);
828 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000829
830 // Perform default conversions.
831 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000832
Steve Naroff2cb66382007-07-26 03:11:44 +0000833 QualType BaseType = BaseExpr->getType();
834 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000835
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000836 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
837 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000838 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000839 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000840 BaseType = PT->getPointeeType();
841 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000842 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
843 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000844 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000845
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000846 // Handle field access to simple records. This also handles access to fields
847 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000848 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000849 RecordDecl *RDecl = RTy->getDecl();
850 if (RTy->isIncompleteType())
851 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
852 BaseExpr->getSourceRange());
853 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000854 FieldDecl *MemberDecl = RDecl->getMember(&Member);
855 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000856 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
857 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000858
859 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000860 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000861 QualType MemberType = MemberDecl->getType();
862 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000863 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000864 MemberType = MemberType.getQualifiedType(combinedQualifiers);
865
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000866 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000867 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000868 }
869
Chris Lattnere9d71612008-07-21 04:59:05 +0000870 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
871 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000872 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
873 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000874 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000875 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000876 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000877 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000878 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000879 }
880
Chris Lattnere9d71612008-07-21 04:59:05 +0000881 // Handle Objective-C property access, which is "Obj.property" where Obj is a
882 // pointer to a (potentially qualified) interface type.
883 const PointerType *PTy;
884 const ObjCInterfaceType *IFTy;
885 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
886 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
887 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +0000888
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000889 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +0000890 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
891 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
892
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000893 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000894 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
895 E = IFTy->qual_end(); I != E; ++I)
896 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
897 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000898
899 // If that failed, look for an "implicit" property by seeing if the nullary
900 // selector is implemented.
901
902 // FIXME: The logic for looking up nullary and unary selectors should be
903 // shared with the code in ActOnInstanceMessage.
904
905 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
906 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
907
908 // If this reference is in an @implementation, check for 'private' methods.
909 if (!Getter)
910 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
911 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
912 if (ObjCImplementationDecl *ImpDecl =
913 ObjCImplementations[ClassDecl->getIdentifier()])
914 Getter = ImpDecl->getInstanceMethod(Sel);
915
916 if (Getter) {
917 // If we found a getter then this may be a valid dot-reference, we
918 // need to also look for the matching setter.
919 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
920 &Member);
921 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
922 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
923
924 if (!Setter) {
925 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
926 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
927 if (ObjCImplementationDecl *ImpDecl =
928 ObjCImplementations[ClassDecl->getIdentifier()])
929 Setter = ImpDecl->getInstanceMethod(SetterSel);
930 }
931
932 // FIXME: There are some issues here. First, we are not
933 // diagnosing accesses to read-only properties because we do not
934 // know if this is a getter or setter yet. Second, we are
935 // checking that the type of the setter matches the type we
936 // expect.
937 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
938 MemberLoc, BaseExpr);
939 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000940 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000941
942 // Handle 'field access' to vectors, such as 'V.xx'.
943 if (BaseType->isExtVectorType() && OpKind == tok::period) {
944 // Component access limited to variables (reject vec4.rg.g).
945 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
946 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +0000947 return Diag(MemberLoc, diag::err_ext_vector_component_access,
948 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000949 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
950 if (ret.isNull())
951 return true;
952 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
953 }
954
Chris Lattner7d5a8762008-07-21 05:35:34 +0000955 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
956 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000957}
958
Steve Naroff87d58b42007-09-16 03:34:24 +0000959/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000960/// This provides the location of the left/right parens and a list of comma
961/// locations.
962Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000963ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000964 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000965 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
966 Expr *Fn = static_cast<Expr *>(fn);
967 Expr **Args = reinterpret_cast<Expr**>(args);
968 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +0000969 FunctionDecl *FDecl = NULL;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000970
971 // Promote the function operand.
972 UsualUnaryConversions(Fn);
973
974 // If we're directly calling a function, get the declaration for
975 // that function.
976 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
977 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
978 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
979
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000980 // Make the call expr early, before semantic checks. This guarantees cleanup
981 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +0000982 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000983 Context.BoolTy, RParenLoc));
984
Chris Lattner4b009652007-07-25 00:24:17 +0000985 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
986 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000987 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000988 if (PT == 0)
Chris Lattner61000b12008-08-14 04:33:24 +0000989 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
990 Fn->getSourceRange());
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000991 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
992 if (FuncT == 0)
Chris Lattner61000b12008-08-14 04:33:24 +0000993 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
994 Fn->getSourceRange());
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000995
996 // We know the result type of the call, set it.
997 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000998
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000999 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001000 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1001 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001002 unsigned NumArgsInProto = Proto->getNumArgs();
1003 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001004
Chris Lattner3e254fb2008-04-08 04:40:51 +00001005 // If too few arguments are available (and we don't have default
1006 // arguments for the remaining parameters), don't make the call.
1007 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +00001008 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001009 // Use default arguments for missing arguments
1010 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +00001011 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001012 } else
1013 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
1014 Fn->getSourceRange());
1015 }
1016
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001017 // If too many are passed and not variadic, error on the extras and drop
1018 // them.
1019 if (NumArgs > NumArgsInProto) {
1020 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001021 Diag(Args[NumArgsInProto]->getLocStart(),
1022 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
1023 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001024 Args[NumArgs-1]->getLocEnd()));
1025 // This deletes the extra arguments.
1026 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001027 }
1028 NumArgsToCheck = NumArgsInProto;
1029 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001030
Chris Lattner4b009652007-07-25 00:24:17 +00001031 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001032 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001033 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001034
1035 Expr *Arg;
1036 if (i < NumArgs)
1037 Arg = Args[i];
1038 else
1039 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001040 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001041
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001042 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +00001043 AssignConvertType ConvTy =
1044 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001045 TheCall->setArg(i, Arg);
Eli Friedman583c31e2008-09-02 05:09:35 +00001046
Chris Lattner005ed752008-01-04 18:04:52 +00001047 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1048 ArgType, Arg, "passing"))
1049 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001050 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001051
1052 // If this is a variadic call, handle args passed through "...".
1053 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001054 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001055 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1056 Expr *Arg = Args[i];
1057 DefaultArgumentPromotion(Arg);
1058 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001059 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001060 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001061 } else {
1062 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1063
Steve Naroffdb65e052007-08-28 23:30:39 +00001064 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001065 for (unsigned i = 0; i != NumArgs; i++) {
1066 Expr *Arg = Args[i];
1067 DefaultArgumentPromotion(Arg);
1068 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001069 }
Chris Lattner4b009652007-07-25 00:24:17 +00001070 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001071
Chris Lattner2e64c072007-08-10 20:18:51 +00001072 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001073 if (FDecl)
1074 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001075
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001076 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001077}
1078
1079Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001080ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001081 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001082 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001083 QualType literalType = QualType::getFromOpaquePtr(Ty);
1084 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001085 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001086 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001087
Eli Friedman8c2173d2008-05-20 05:22:08 +00001088 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001089 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001090 return Diag(LParenLoc,
1091 diag::err_variable_object_no_init,
1092 SourceRange(LParenLoc,
1093 literalExpr->getSourceRange().getEnd()));
1094 } else if (literalType->isIncompleteType()) {
1095 return Diag(LParenLoc,
1096 diag::err_typecheck_decl_incomplete_type,
1097 literalType.getAsString(),
1098 SourceRange(LParenLoc,
1099 literalExpr->getSourceRange().getEnd()));
1100 }
1101
Steve Narofff0b23542008-01-10 22:15:12 +00001102 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +00001103 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001104
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001105 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001106 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001107 if (CheckForConstantInitializer(literalExpr, literalType))
1108 return true;
1109 }
Steve Naroffbe37fc02008-01-14 18:19:28 +00001110 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001111}
1112
1113Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001114ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001115 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001116 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001117
Steve Naroff0acc9c92007-09-15 18:49:24 +00001118 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001119 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001120
Chris Lattner48d7f382008-04-02 04:24:33 +00001121 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1122 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1123 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001124}
1125
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001126/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001127bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001128 UsualUnaryConversions(castExpr);
1129
1130 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1131 // type needs to be scalar.
1132 if (castType->isVoidType()) {
1133 // Cast to void allows any expr type.
1134 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1135 // GCC struct/union extension: allow cast to self.
1136 if (Context.getCanonicalType(castType) !=
1137 Context.getCanonicalType(castExpr->getType()) ||
1138 (!castType->isStructureType() && !castType->isUnionType())) {
1139 // Reject any other conversions to non-scalar types.
1140 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1141 castType.getAsString(), castExpr->getSourceRange());
1142 }
1143
1144 // accept this, but emit an ext-warn.
1145 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1146 castType.getAsString(), castExpr->getSourceRange());
1147 } else if (!castExpr->getType()->isScalarType() &&
1148 !castExpr->getType()->isVectorType()) {
1149 return Diag(castExpr->getLocStart(),
1150 diag::err_typecheck_expect_scalar_operand,
1151 castExpr->getType().getAsString(),castExpr->getSourceRange());
1152 } else if (castExpr->getType()->isVectorType()) {
1153 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1154 return true;
1155 } else if (castType->isVectorType()) {
1156 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1157 return true;
1158 }
1159 return false;
1160}
1161
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001162bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001163 assert(VectorTy->isVectorType() && "Not a vector type!");
1164
1165 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001166 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001167 return Diag(R.getBegin(),
1168 Ty->isVectorType() ?
1169 diag::err_invalid_conversion_between_vectors :
1170 diag::err_invalid_conversion_between_vector_and_integer,
1171 VectorTy.getAsString().c_str(),
1172 Ty.getAsString().c_str(), R);
1173 } else
1174 return Diag(R.getBegin(),
1175 diag::err_invalid_conversion_between_vector_and_scalar,
1176 VectorTy.getAsString().c_str(),
1177 Ty.getAsString().c_str(), R);
1178
1179 return false;
1180}
1181
Chris Lattner4b009652007-07-25 00:24:17 +00001182Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001183ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001184 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001185 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001186
1187 Expr *castExpr = static_cast<Expr*>(Op);
1188 QualType castType = QualType::getFromOpaquePtr(Ty);
1189
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001190 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1191 return true;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001192 return new ExplicitCastExpr(castType, castExpr, LParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001193}
1194
Chris Lattner98a425c2007-11-26 01:40:58 +00001195/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1196/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001197inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1198 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1199 UsualUnaryConversions(cond);
1200 UsualUnaryConversions(lex);
1201 UsualUnaryConversions(rex);
1202 QualType condT = cond->getType();
1203 QualType lexT = lex->getType();
1204 QualType rexT = rex->getType();
1205
1206 // first, check the condition.
1207 if (!condT->isScalarType()) { // C99 6.5.15p2
1208 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1209 condT.getAsString());
1210 return QualType();
1211 }
Chris Lattner992ae932008-01-06 22:42:25 +00001212
1213 // Now check the two expressions.
1214
1215 // If both operands have arithmetic type, do the usual arithmetic conversions
1216 // to find a common type: C99 6.5.15p3,5.
1217 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001218 UsualArithmeticConversions(lex, rex);
1219 return lex->getType();
1220 }
Chris Lattner992ae932008-01-06 22:42:25 +00001221
1222 // If both operands are the same structure or union type, the result is that
1223 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001224 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001225 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001226 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001227 // "If both the operands have structure or union type, the result has
1228 // that type." This implies that CV qualifiers are dropped.
1229 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001230 }
Chris Lattner992ae932008-01-06 22:42:25 +00001231
1232 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001233 // The following || allows only one side to be void (a GCC-ism).
1234 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001235 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001236 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1237 rex->getSourceRange());
1238 if (!rexT->isVoidType())
1239 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001240 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001241 ImpCastExprToType(lex, Context.VoidTy);
1242 ImpCastExprToType(rex, Context.VoidTy);
1243 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001244 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001245 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1246 // the type of the other operand."
1247 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001248 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001249 return lexT;
1250 }
1251 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001252 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001253 return rexT;
1254 }
Daniel Dunbarcc785c82008-09-03 17:53:25 +00001255 // Allow any Objective-C types to devolve to id type.
1256 // FIXME: This seems to match gcc behavior, although that is very
1257 // arguably incorrect. For example, (xxx ? (id<P>) : (id<P>)) has
1258 // type id, which seems broken.
1259 if (Context.isObjCObjectPointerType(lexT) &&
1260 Context.isObjCObjectPointerType(rexT)) {
1261 // FIXME: This is not the correct composite type. This only
1262 // happens to work because id can more or less be used anywhere,
1263 // however this may change the type of method sends.
1264 // FIXME: gcc adds some type-checking of the arguments and emits
1265 // (confusing) incompatible comparison warnings in some
1266 // cases. Investigate.
1267 QualType compositeType = Context.getObjCIdType();
1268 ImpCastExprToType(lex, compositeType);
1269 ImpCastExprToType(rex, compositeType);
1270 return compositeType;
1271 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001272 // Handle the case where both operands are pointers before we handle null
1273 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001274 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1275 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1276 // get the "pointed to" types
1277 QualType lhptee = LHSPT->getPointeeType();
1278 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001279
Chris Lattner71225142007-07-31 21:27:01 +00001280 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1281 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001282 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001283 // Figure out necessary qualifiers (C99 6.5.15p6)
1284 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001285 QualType destType = Context.getPointerType(destPointee);
1286 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1287 ImpCastExprToType(rex, destType); // promote to void*
1288 return destType;
1289 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001290 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001291 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001292 QualType destType = Context.getPointerType(destPointee);
1293 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1294 ImpCastExprToType(rex, destType); // promote to void*
1295 return destType;
1296 }
Chris Lattner4b009652007-07-25 00:24:17 +00001297
Steve Naroff85f0dc52007-10-15 20:41:53 +00001298 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1299 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001300 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001301 lexT.getAsString(), rexT.getAsString(),
1302 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001303 // In this situation, assume a conservative type; in general
1304 // we assume void* type. No especially good reason, but this
1305 // is what gcc does, and we do have to pick to get a
1306 // consistent AST. However, if either type is an Objective-C
1307 // object type then use id.
1308 QualType incompatTy;
1309 if (Context.isObjCObjectPointerType(lexT) ||
1310 Context.isObjCObjectPointerType(rexT)) {
1311 incompatTy = Context.getObjCIdType();
1312 } else {
1313 incompatTy = Context.getPointerType(Context.VoidTy);
1314 }
1315 ImpCastExprToType(lex, incompatTy);
1316 ImpCastExprToType(rex, incompatTy);
1317 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001318 }
1319 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001320 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1321 // differently qualified versions of compatible types, the result type is
1322 // a pointer to an appropriately qualified version of the *composite*
1323 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001324 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001325 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001326 QualType compositeType = lexT;
1327 ImpCastExprToType(lex, compositeType);
1328 ImpCastExprToType(rex, compositeType);
1329 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001330 }
Chris Lattner4b009652007-07-25 00:24:17 +00001331 }
Chris Lattner992ae932008-01-06 22:42:25 +00001332 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001333 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1334 lexT.getAsString(), rexT.getAsString(),
1335 lex->getSourceRange(), rex->getSourceRange());
1336 return QualType();
1337}
1338
Steve Naroff87d58b42007-09-16 03:34:24 +00001339/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001340/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001341Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001342 SourceLocation ColonLoc,
1343 ExprTy *Cond, ExprTy *LHS,
1344 ExprTy *RHS) {
1345 Expr *CondExpr = (Expr *) Cond;
1346 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001347
1348 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1349 // was the condition.
1350 bool isLHSNull = LHSExpr == 0;
1351 if (isLHSNull)
1352 LHSExpr = CondExpr;
1353
Chris Lattner4b009652007-07-25 00:24:17 +00001354 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1355 RHSExpr, QuestionLoc);
1356 if (result.isNull())
1357 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001358 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1359 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001360}
1361
Chris Lattner4b009652007-07-25 00:24:17 +00001362
1363// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1364// being closely modeled after the C99 spec:-). The odd characteristic of this
1365// routine is it effectively iqnores the qualifiers on the top level pointee.
1366// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1367// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001368Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001369Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1370 QualType lhptee, rhptee;
1371
1372 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001373 lhptee = lhsType->getAsPointerType()->getPointeeType();
1374 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001375
1376 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001377 lhptee = Context.getCanonicalType(lhptee);
1378 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001379
Chris Lattner005ed752008-01-04 18:04:52 +00001380 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001381
1382 // C99 6.5.16.1p1: This following citation is common to constraints
1383 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1384 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001385 // FIXME: Handle ASQualType
1386 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1387 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001388 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001389
1390 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1391 // incomplete type and the other is a pointer to a qualified or unqualified
1392 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001393 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001394 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001395 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001396
1397 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001398 assert(rhptee->isFunctionType());
1399 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001400 }
1401
1402 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001403 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001404 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001405
1406 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001407 assert(lhptee->isFunctionType());
1408 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001409 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001410
1411 // Check for ObjC interfaces
1412 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1413 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1414 if (LHSIface && RHSIface &&
1415 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1416 return ConvTy;
1417
1418 // ID acts sort of like void* for ObjC interfaces
1419 if (LHSIface && Context.isObjCIdType(rhptee))
1420 return ConvTy;
1421 if (RHSIface && Context.isObjCIdType(lhptee))
1422 return ConvTy;
1423
Chris Lattner4b009652007-07-25 00:24:17 +00001424 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1425 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001426 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1427 rhptee.getUnqualifiedType()))
1428 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001429 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001430}
1431
1432/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1433/// has code to accommodate several GCC extensions when type checking
1434/// pointers. Here are some objectionable examples that GCC considers warnings:
1435///
1436/// int a, *pint;
1437/// short *pshort;
1438/// struct foo *pfoo;
1439///
1440/// pint = pshort; // warning: assignment from incompatible pointer type
1441/// a = pint; // warning: assignment makes integer from pointer without a cast
1442/// pint = a; // warning: assignment makes pointer from integer without a cast
1443/// pint = pfoo; // warning: assignment from incompatible pointer type
1444///
1445/// As a result, the code for dealing with pointers is more complex than the
1446/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001447///
Chris Lattner005ed752008-01-04 18:04:52 +00001448Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001449Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001450 // Get canonical types. We're not formatting these types, just comparing
1451 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001452 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1453 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001454
1455 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001456 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001457
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001458 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001459 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001460 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001461 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001462 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001463
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001464 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1465 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001466 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001467 // Relax integer conversions like we do for pointers below.
1468 if (rhsType->isIntegerType())
1469 return IntToPointer;
1470 if (lhsType->isIntegerType())
1471 return PointerToInt;
Chris Lattner1853da22008-01-04 23:18:45 +00001472 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001473 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001474
Nate Begemanc5f0f652008-07-14 18:02:46 +00001475 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001476 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001477 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1478 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001479 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001480
Nate Begemanc5f0f652008-07-14 18:02:46 +00001481 // If we are allowing lax vector conversions, and LHS and RHS are both
1482 // vectors, the total size only needs to be the same. This is a bitcast;
1483 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001484 if (getLangOptions().LaxVectorConversions &&
1485 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001486 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1487 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001488 }
1489 return Incompatible;
1490 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001491
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001492 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001493 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001494
Chris Lattner390564e2008-04-07 06:49:41 +00001495 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001496 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001497 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001498
Chris Lattner390564e2008-04-07 06:49:41 +00001499 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001500 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001501 return Incompatible;
1502 }
1503
Chris Lattner390564e2008-04-07 06:49:41 +00001504 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001505 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001506 if (lhsType == Context.BoolTy)
1507 return Compatible;
1508
1509 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001510 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001511
Chris Lattner390564e2008-04-07 06:49:41 +00001512 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001513 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001514 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001515 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001516
Chris Lattner1853da22008-01-04 23:18:45 +00001517 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001518 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001519 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001520 }
1521 return Incompatible;
1522}
1523
Chris Lattner005ed752008-01-04 18:04:52 +00001524Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001525Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001526 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1527 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001528 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001529 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001530 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001531 return Compatible;
1532 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001533 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001534 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001535 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001536 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001537 //
1538 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1539 // are better understood.
1540 if (!lhsType->isReferenceType())
1541 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001542
Chris Lattner005ed752008-01-04 18:04:52 +00001543 Sema::AssignConvertType result =
1544 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001545
1546 // C99 6.5.16.1p2: The value of the right operand is converted to the
1547 // type of the assignment expression.
1548 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001549 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001550 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001551}
1552
Chris Lattner005ed752008-01-04 18:04:52 +00001553Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001554Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1555 return CheckAssignmentConstraints(lhsType, rhsType);
1556}
1557
Chris Lattner2c8bff72007-12-12 05:47:28 +00001558QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001559 Diag(loc, diag::err_typecheck_invalid_operands,
1560 lex->getType().getAsString(), rex->getType().getAsString(),
1561 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001562 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001563}
1564
1565inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1566 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001567 // For conversion purposes, we ignore any qualifiers.
1568 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001569 QualType lhsType =
1570 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1571 QualType rhsType =
1572 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001573
Nate Begemanc5f0f652008-07-14 18:02:46 +00001574 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001575 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001576 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001577
Nate Begemanc5f0f652008-07-14 18:02:46 +00001578 // Handle the case of a vector & extvector type of the same size and element
1579 // type. It would be nice if we only had one vector type someday.
1580 if (getLangOptions().LaxVectorConversions)
1581 if (const VectorType *LV = lhsType->getAsVectorType())
1582 if (const VectorType *RV = rhsType->getAsVectorType())
1583 if (LV->getElementType() == RV->getElementType() &&
1584 LV->getNumElements() == RV->getNumElements())
1585 return lhsType->isExtVectorType() ? lhsType : rhsType;
1586
1587 // If the lhs is an extended vector and the rhs is a scalar of the same type
1588 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001589 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001590 QualType eltType = V->getElementType();
1591
1592 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1593 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1594 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001595 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001596 return lhsType;
1597 }
1598 }
1599
Nate Begemanc5f0f652008-07-14 18:02:46 +00001600 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001601 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001602 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001603 QualType eltType = V->getElementType();
1604
1605 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1606 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1607 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001608 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001609 return rhsType;
1610 }
1611 }
1612
Chris Lattner4b009652007-07-25 00:24:17 +00001613 // You cannot convert between vector values of different size.
1614 Diag(loc, diag::err_typecheck_vector_not_convertable,
1615 lex->getType().getAsString(), rex->getType().getAsString(),
1616 lex->getSourceRange(), rex->getSourceRange());
1617 return QualType();
1618}
1619
1620inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001621 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001622{
1623 QualType lhsType = lex->getType(), rhsType = rex->getType();
1624
1625 if (lhsType->isVectorType() || rhsType->isVectorType())
1626 return CheckVectorOperands(loc, lex, rex);
1627
Steve Naroff8f708362007-08-24 19:07:16 +00001628 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001629
Chris Lattner4b009652007-07-25 00:24:17 +00001630 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001631 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001632 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001633}
1634
1635inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001636 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001637{
1638 QualType lhsType = lex->getType(), rhsType = rex->getType();
1639
Steve Naroff8f708362007-08-24 19:07:16 +00001640 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001641
Chris Lattner4b009652007-07-25 00:24:17 +00001642 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001643 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001644 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001645}
1646
1647inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001648 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001649{
1650 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1651 return CheckVectorOperands(loc, lex, rex);
1652
Steve Naroff8f708362007-08-24 19:07:16 +00001653 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001654
Chris Lattner4b009652007-07-25 00:24:17 +00001655 // handle the common case first (both operands are arithmetic).
1656 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001657 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001658
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001659 // Put any potential pointer into PExp
1660 Expr* PExp = lex, *IExp = rex;
1661 if (IExp->getType()->isPointerType())
1662 std::swap(PExp, IExp);
1663
1664 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1665 if (IExp->getType()->isIntegerType()) {
1666 // Check for arithmetic on pointers to incomplete types
1667 if (!PTy->getPointeeType()->isObjectType()) {
1668 if (PTy->getPointeeType()->isVoidType()) {
1669 Diag(loc, diag::ext_gnu_void_ptr,
1670 lex->getSourceRange(), rex->getSourceRange());
1671 } else {
1672 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1673 lex->getType().getAsString(), lex->getSourceRange());
1674 return QualType();
1675 }
1676 }
1677 return PExp->getType();
1678 }
1679 }
1680
Chris Lattner2c8bff72007-12-12 05:47:28 +00001681 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001682}
1683
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001684// C99 6.5.6
1685QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1686 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001687 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1688 return CheckVectorOperands(loc, lex, rex);
1689
Steve Naroff8f708362007-08-24 19:07:16 +00001690 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001691
Chris Lattnerf6da2912007-12-09 21:53:25 +00001692 // Enforce type constraints: C99 6.5.6p3.
1693
1694 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001695 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001696 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001697
1698 // Either ptr - int or ptr - ptr.
1699 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001700 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001701
Chris Lattnerf6da2912007-12-09 21:53:25 +00001702 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001703 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001704 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001705 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001706 Diag(loc, diag::ext_gnu_void_ptr,
1707 lex->getSourceRange(), rex->getSourceRange());
1708 } else {
1709 Diag(loc, diag::err_typecheck_sub_ptr_object,
1710 lex->getType().getAsString(), lex->getSourceRange());
1711 return QualType();
1712 }
1713 }
1714
1715 // The result type of a pointer-int computation is the pointer type.
1716 if (rex->getType()->isIntegerType())
1717 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001718
Chris Lattnerf6da2912007-12-09 21:53:25 +00001719 // Handle pointer-pointer subtractions.
1720 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001721 QualType rpointee = RHSPTy->getPointeeType();
1722
Chris Lattnerf6da2912007-12-09 21:53:25 +00001723 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001724 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001725 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001726 if (rpointee->isVoidType()) {
1727 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001728 Diag(loc, diag::ext_gnu_void_ptr,
1729 lex->getSourceRange(), rex->getSourceRange());
1730 } else {
1731 Diag(loc, diag::err_typecheck_sub_ptr_object,
1732 rex->getType().getAsString(), rex->getSourceRange());
1733 return QualType();
1734 }
1735 }
1736
1737 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00001738 if (!Context.typesAreCompatible(
1739 Context.getCanonicalType(lpointee).getUnqualifiedType(),
1740 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001741 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1742 lex->getType().getAsString(), rex->getType().getAsString(),
1743 lex->getSourceRange(), rex->getSourceRange());
1744 return QualType();
1745 }
1746
1747 return Context.getPointerDiffType();
1748 }
1749 }
1750
Chris Lattner2c8bff72007-12-12 05:47:28 +00001751 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001752}
1753
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001754// C99 6.5.7
1755QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1756 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00001757 // C99 6.5.7p2: Each of the operands shall have integer type.
1758 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1759 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001760
Chris Lattner2c8bff72007-12-12 05:47:28 +00001761 // Shifts don't perform usual arithmetic conversions, they just do integer
1762 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001763 if (!isCompAssign)
1764 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001765 UsualUnaryConversions(rex);
1766
1767 // "The type of the result is that of the promoted left operand."
1768 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001769}
1770
Eli Friedman0d9549b2008-08-22 00:56:42 +00001771static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
1772 ASTContext& Context) {
1773 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
1774 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
1775 // ID acts sort of like void* for ObjC interfaces
1776 if (LHSIface && Context.isObjCIdType(RHS))
1777 return true;
1778 if (RHSIface && Context.isObjCIdType(LHS))
1779 return true;
1780 if (!LHSIface || !RHSIface)
1781 return false;
1782 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
1783 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
1784}
1785
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001786// C99 6.5.8
1787QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1788 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001789 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1790 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1791
Chris Lattner254f3bc2007-08-26 01:18:55 +00001792 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001793 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1794 UsualArithmeticConversions(lex, rex);
1795 else {
1796 UsualUnaryConversions(lex);
1797 UsualUnaryConversions(rex);
1798 }
Chris Lattner4b009652007-07-25 00:24:17 +00001799 QualType lType = lex->getType();
1800 QualType rType = rex->getType();
1801
Ted Kremenek486509e2007-10-29 17:13:39 +00001802 // For non-floating point types, check for self-comparisons of the form
1803 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1804 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001805 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001806 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1807 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001808 if (DRL->getDecl() == DRR->getDecl())
1809 Diag(loc, diag::warn_selfcomparison);
1810 }
1811
Chris Lattner254f3bc2007-08-26 01:18:55 +00001812 if (isRelational) {
1813 if (lType->isRealType() && rType->isRealType())
1814 return Context.IntTy;
1815 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001816 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001817 if (lType->isFloatingType()) {
1818 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001819 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001820 }
1821
Chris Lattner254f3bc2007-08-26 01:18:55 +00001822 if (lType->isArithmeticType() && rType->isArithmeticType())
1823 return Context.IntTy;
1824 }
Chris Lattner4b009652007-07-25 00:24:17 +00001825
Chris Lattner22be8422007-08-26 01:10:14 +00001826 bool LHSIsNull = lex->isNullPointerConstant(Context);
1827 bool RHSIsNull = rex->isNullPointerConstant(Context);
1828
Chris Lattner254f3bc2007-08-26 01:18:55 +00001829 // All of the following pointer related warnings are GCC extensions, except
1830 // when handling null pointer constants. One day, we can consider making them
1831 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001832 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001833 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001834 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00001835 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001836 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00001837
Steve Naroff3b435622007-11-13 14:57:38 +00001838 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001839 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1840 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00001841 RCanPointeeTy.getUnqualifiedType()) &&
1842 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001843 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1844 lType.getAsString(), rType.getAsString(),
1845 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001846 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001847 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001848 return Context.IntTy;
1849 }
Steve Naroff936c4362008-06-03 14:04:54 +00001850 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
1851 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
1852 ImpCastExprToType(rex, lType);
1853 return Context.IntTy;
1854 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001855 }
Steve Naroff936c4362008-06-03 14:04:54 +00001856 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
1857 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001858 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001859 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1860 lType.getAsString(), rType.getAsString(),
1861 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001862 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001863 return Context.IntTy;
1864 }
Steve Naroff936c4362008-06-03 14:04:54 +00001865 if (lType->isIntegerType() &&
1866 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00001867 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001868 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1869 lType.getAsString(), rType.getAsString(),
1870 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001871 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001872 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001873 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001874 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001875}
1876
Nate Begemanc5f0f652008-07-14 18:02:46 +00001877/// CheckVectorCompareOperands - vector comparisons are a clang extension that
1878/// operates on extended vector types. Instead of producing an IntTy result,
1879/// like a scalar comparison, a vector comparison produces a vector of integer
1880/// types.
1881QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
1882 SourceLocation loc,
1883 bool isRelational) {
1884 // Check to make sure we're operating on vectors of the same type and width,
1885 // Allowing one side to be a scalar of element type.
1886 QualType vType = CheckVectorOperands(loc, lex, rex);
1887 if (vType.isNull())
1888 return vType;
1889
1890 QualType lType = lex->getType();
1891 QualType rType = rex->getType();
1892
1893 // For non-floating point types, check for self-comparisons of the form
1894 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1895 // often indicate logic errors in the program.
1896 if (!lType->isFloatingType()) {
1897 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1898 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1899 if (DRL->getDecl() == DRR->getDecl())
1900 Diag(loc, diag::warn_selfcomparison);
1901 }
1902
1903 // Check for comparisons of floating point operands using != and ==.
1904 if (!isRelational && lType->isFloatingType()) {
1905 assert (rType->isFloatingType());
1906 CheckFloatComparison(loc,lex,rex);
1907 }
1908
1909 // Return the type for the comparison, which is the same as vector type for
1910 // integer vectors, or an integer type of identical size and number of
1911 // elements for floating point vectors.
1912 if (lType->isIntegerType())
1913 return lType;
1914
1915 const VectorType *VTy = lType->getAsVectorType();
1916
1917 // FIXME: need to deal with non-32b int / non-64b long long
1918 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
1919 if (TypeSize == 32) {
1920 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
1921 }
1922 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
1923 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
1924}
1925
Chris Lattner4b009652007-07-25 00:24:17 +00001926inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001927 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001928{
1929 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1930 return CheckVectorOperands(loc, lex, rex);
1931
Steve Naroff8f708362007-08-24 19:07:16 +00001932 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001933
1934 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001935 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001936 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001937}
1938
1939inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1940 Expr *&lex, Expr *&rex, SourceLocation loc)
1941{
1942 UsualUnaryConversions(lex);
1943 UsualUnaryConversions(rex);
1944
Eli Friedmanbea3f842008-05-13 20:16:47 +00001945 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00001946 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001947 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001948}
1949
1950inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001951 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001952{
1953 QualType lhsType = lex->getType();
1954 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner25168a52008-07-26 21:30:36 +00001955 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00001956
1957 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001958 case Expr::MLV_Valid:
1959 break;
1960 case Expr::MLV_ConstQualified:
1961 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1962 return QualType();
1963 case Expr::MLV_ArrayType:
1964 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1965 lhsType.getAsString(), lex->getSourceRange());
1966 return QualType();
1967 case Expr::MLV_NotObjectType:
1968 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1969 lhsType.getAsString(), lex->getSourceRange());
1970 return QualType();
1971 case Expr::MLV_InvalidExpression:
1972 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1973 lex->getSourceRange());
1974 return QualType();
1975 case Expr::MLV_IncompleteType:
1976 case Expr::MLV_IncompleteVoidType:
1977 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1978 lhsType.getAsString(), lex->getSourceRange());
1979 return QualType();
1980 case Expr::MLV_DuplicateVectorComponents:
1981 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1982 lex->getSourceRange());
1983 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001984 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001985
Chris Lattner005ed752008-01-04 18:04:52 +00001986 AssignConvertType ConvTy;
Chris Lattner34c85082008-08-21 18:04:13 +00001987 if (compoundType.isNull()) {
1988 // Simple assignment "x = y".
Chris Lattner005ed752008-01-04 18:04:52 +00001989 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner34c85082008-08-21 18:04:13 +00001990
1991 // If the RHS is a unary plus or minus, check to see if they = and + are
1992 // right next to each other. If so, the user may have typo'd "x =+ 4"
1993 // instead of "x += 4".
1994 Expr *RHSCheck = rex;
1995 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
1996 RHSCheck = ICE->getSubExpr();
1997 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
1998 if ((UO->getOpcode() == UnaryOperator::Plus ||
1999 UO->getOpcode() == UnaryOperator::Minus) &&
2000 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2001 // Only if the two operators are exactly adjacent.
2002 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2003 Diag(loc, diag::warn_not_compound_assign,
2004 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2005 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2006 }
2007 } else {
2008 // Compound assignment "x += y"
Chris Lattner005ed752008-01-04 18:04:52 +00002009 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner34c85082008-08-21 18:04:13 +00002010 }
Chris Lattner005ed752008-01-04 18:04:52 +00002011
2012 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2013 rex, "assigning"))
2014 return QualType();
2015
Chris Lattner4b009652007-07-25 00:24:17 +00002016 // C99 6.5.16p3: The type of an assignment expression is the type of the
2017 // left operand unless the left operand has qualified type, in which case
2018 // it is the unqualified version of the type of the left operand.
2019 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2020 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002021 // C++ 5.17p1: the type of the assignment expression is that of its left
2022 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00002023 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002024}
2025
2026inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2027 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00002028
2029 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2030 DefaultFunctionArrayConversion(rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002031 return rex->getType();
2032}
2033
2034/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2035/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2036QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2037 QualType resType = op->getType();
2038 assert(!resType.isNull() && "no type for increment/decrement expression");
2039
Steve Naroffd30e1932007-08-24 17:20:07 +00002040 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00002041 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002042 if (pt->getPointeeType()->isVoidType()) {
2043 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2044 } else if (!pt->getPointeeType()->isObjectType()) {
2045 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00002046 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2047 resType.getAsString(), op->getSourceRange());
2048 return QualType();
2049 }
Steve Naroffd30e1932007-08-24 17:20:07 +00002050 } else if (!resType->isRealType()) {
2051 if (resType->isComplexType())
2052 // C99 does not support ++/-- on complex types.
2053 Diag(OpLoc, diag::ext_integer_increment_complex,
2054 resType.getAsString(), op->getSourceRange());
2055 else {
2056 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2057 resType.getAsString(), op->getSourceRange());
2058 return QualType();
2059 }
Chris Lattner4b009652007-07-25 00:24:17 +00002060 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002061 // At this point, we know we have a real, complex or pointer type.
2062 // Now make sure the operand is a modifiable lvalue.
Chris Lattner25168a52008-07-26 21:30:36 +00002063 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002064 if (mlval != Expr::MLV_Valid) {
2065 // FIXME: emit a more precise diagnostic...
2066 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2067 op->getSourceRange());
2068 return QualType();
2069 }
2070 return resType;
2071}
2072
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002073/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002074/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002075/// where the declaration is needed for type checking. We only need to
2076/// handle cases when the expression references a function designator
2077/// or is an lvalue. Here are some examples:
2078/// - &(x) => x
2079/// - &*****f => f for f a function designator.
2080/// - &s.xx => s
2081/// - &s.zz[1].yy -> s, if zz is an array
2082/// - *(x + 1) -> x, if x is an array
2083/// - &"123"[2] -> 0
2084/// - & __real__ x -> x
Chris Lattner48d7f382008-04-02 04:24:33 +00002085static ValueDecl *getPrimaryDecl(Expr *E) {
2086 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002087 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002088 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002089 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002090 // Fields cannot be declared with a 'register' storage class.
2091 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002092 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002093 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002094 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002095 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002096 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002097
Chris Lattner48d7f382008-04-02 04:24:33 +00002098 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00002099 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002100 return 0;
2101 else
2102 return VD;
2103 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002104 case Stmt::UnaryOperatorClass: {
2105 UnaryOperator *UO = cast<UnaryOperator>(E);
2106
2107 switch(UO->getOpcode()) {
2108 case UnaryOperator::Deref: {
2109 // *(X + 1) refers to X if X is not a pointer.
2110 ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2111 if (!VD || VD->getType()->isPointerType())
2112 return 0;
2113 return VD;
2114 }
2115 case UnaryOperator::Real:
2116 case UnaryOperator::Imag:
2117 case UnaryOperator::Extension:
2118 return getPrimaryDecl(UO->getSubExpr());
2119 default:
2120 return 0;
2121 }
2122 }
2123 case Stmt::BinaryOperatorClass: {
2124 BinaryOperator *BO = cast<BinaryOperator>(E);
2125
2126 // Handle cases involving pointer arithmetic. The result of an
2127 // Assign or AddAssign is not an lvalue so they can be ignored.
2128
2129 // (x + n) or (n + x) => x
2130 if (BO->getOpcode() == BinaryOperator::Add) {
2131 if (BO->getLHS()->getType()->isPointerType()) {
2132 return getPrimaryDecl(BO->getLHS());
2133 } else if (BO->getRHS()->getType()->isPointerType()) {
2134 return getPrimaryDecl(BO->getRHS());
2135 }
2136 }
2137
2138 return 0;
2139 }
Chris Lattner4b009652007-07-25 00:24:17 +00002140 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002141 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002142 case Stmt::ImplicitCastExprClass:
2143 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002144 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002145 default:
2146 return 0;
2147 }
2148}
2149
2150/// CheckAddressOfOperand - The operand of & must be either a function
2151/// designator or an lvalue designating an object. If it is an lvalue, the
2152/// object cannot be declared with storage class register or be a bit field.
2153/// Note: The usual conversions are *not* applied to the operand of the &
2154/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2155QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002156 if (getLangOptions().C99) {
2157 // Implement C99-only parts of addressof rules.
2158 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2159 if (uOp->getOpcode() == UnaryOperator::Deref)
2160 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2161 // (assuming the deref expression is valid).
2162 return uOp->getSubExpr()->getType();
2163 }
2164 // Technically, there should be a check for array subscript
2165 // expressions here, but the result of one is always an lvalue anyway.
2166 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002167 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002168 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002169
2170 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002171 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2172 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002173 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2174 op->getSourceRange());
2175 return QualType();
2176 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002177 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2178 if (MemExpr->getMemberDecl()->isBitField()) {
2179 Diag(OpLoc, diag::err_typecheck_address_of,
2180 std::string("bit-field"), op->getSourceRange());
2181 return QualType();
2182 }
2183 // Check for Apple extension for accessing vector components.
2184 } else if (isa<ArraySubscriptExpr>(op) &&
2185 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2186 Diag(OpLoc, diag::err_typecheck_address_of,
2187 std::string("vector"), op->getSourceRange());
2188 return QualType();
2189 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002190 // We have an lvalue with a decl. Make sure the decl is not declared
2191 // with the register storage-class specifier.
2192 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2193 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002194 Diag(OpLoc, diag::err_typecheck_address_of,
2195 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002196 return QualType();
2197 }
2198 } else
2199 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002200 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002201
Chris Lattner4b009652007-07-25 00:24:17 +00002202 // If the operand has type "type", the result has type "pointer to type".
2203 return Context.getPointerType(op->getType());
2204}
2205
2206QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2207 UsualUnaryConversions(op);
2208 QualType qType = op->getType();
2209
Chris Lattner7931f4a2007-07-31 16:53:04 +00002210 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002211 // Note that per both C89 and C99, this is always legal, even
2212 // if ptype is an incomplete type or void.
2213 // It would be possible to warn about dereferencing a
2214 // void pointer, but it's completely well-defined,
2215 // and such a warning is unlikely to catch any mistakes.
2216 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002217 }
2218 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2219 qType.getAsString(), op->getSourceRange());
2220 return QualType();
2221}
2222
2223static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2224 tok::TokenKind Kind) {
2225 BinaryOperator::Opcode Opc;
2226 switch (Kind) {
2227 default: assert(0 && "Unknown binop!");
2228 case tok::star: Opc = BinaryOperator::Mul; break;
2229 case tok::slash: Opc = BinaryOperator::Div; break;
2230 case tok::percent: Opc = BinaryOperator::Rem; break;
2231 case tok::plus: Opc = BinaryOperator::Add; break;
2232 case tok::minus: Opc = BinaryOperator::Sub; break;
2233 case tok::lessless: Opc = BinaryOperator::Shl; break;
2234 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2235 case tok::lessequal: Opc = BinaryOperator::LE; break;
2236 case tok::less: Opc = BinaryOperator::LT; break;
2237 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2238 case tok::greater: Opc = BinaryOperator::GT; break;
2239 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2240 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2241 case tok::amp: Opc = BinaryOperator::And; break;
2242 case tok::caret: Opc = BinaryOperator::Xor; break;
2243 case tok::pipe: Opc = BinaryOperator::Or; break;
2244 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2245 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2246 case tok::equal: Opc = BinaryOperator::Assign; break;
2247 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2248 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2249 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2250 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2251 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2252 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2253 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2254 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2255 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2256 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2257 case tok::comma: Opc = BinaryOperator::Comma; break;
2258 }
2259 return Opc;
2260}
2261
2262static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2263 tok::TokenKind Kind) {
2264 UnaryOperator::Opcode Opc;
2265 switch (Kind) {
2266 default: assert(0 && "Unknown unary op!");
2267 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2268 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2269 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2270 case tok::star: Opc = UnaryOperator::Deref; break;
2271 case tok::plus: Opc = UnaryOperator::Plus; break;
2272 case tok::minus: Opc = UnaryOperator::Minus; break;
2273 case tok::tilde: Opc = UnaryOperator::Not; break;
2274 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2275 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2276 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2277 case tok::kw___real: Opc = UnaryOperator::Real; break;
2278 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2279 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2280 }
2281 return Opc;
2282}
2283
2284// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002285Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002286 ExprTy *LHS, ExprTy *RHS) {
2287 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2288 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2289
Steve Naroff87d58b42007-09-16 03:34:24 +00002290 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2291 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002292
2293 QualType ResultTy; // Result type of the binary operator.
2294 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2295
2296 switch (Opc) {
2297 default:
2298 assert(0 && "Unknown binary expr!");
2299 case BinaryOperator::Assign:
2300 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2301 break;
2302 case BinaryOperator::Mul:
2303 case BinaryOperator::Div:
2304 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2305 break;
2306 case BinaryOperator::Rem:
2307 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2308 break;
2309 case BinaryOperator::Add:
2310 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2311 break;
2312 case BinaryOperator::Sub:
2313 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2314 break;
2315 case BinaryOperator::Shl:
2316 case BinaryOperator::Shr:
2317 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2318 break;
2319 case BinaryOperator::LE:
2320 case BinaryOperator::LT:
2321 case BinaryOperator::GE:
2322 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002323 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002324 break;
2325 case BinaryOperator::EQ:
2326 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002327 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00002328 break;
2329 case BinaryOperator::And:
2330 case BinaryOperator::Xor:
2331 case BinaryOperator::Or:
2332 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2333 break;
2334 case BinaryOperator::LAnd:
2335 case BinaryOperator::LOr:
2336 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2337 break;
2338 case BinaryOperator::MulAssign:
2339 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002340 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002341 if (!CompTy.isNull())
2342 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2343 break;
2344 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002345 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002346 if (!CompTy.isNull())
2347 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2348 break;
2349 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002350 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002351 if (!CompTy.isNull())
2352 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2353 break;
2354 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002355 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002356 if (!CompTy.isNull())
2357 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2358 break;
2359 case BinaryOperator::ShlAssign:
2360 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002361 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002362 if (!CompTy.isNull())
2363 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2364 break;
2365 case BinaryOperator::AndAssign:
2366 case BinaryOperator::XorAssign:
2367 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002368 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002369 if (!CompTy.isNull())
2370 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2371 break;
2372 case BinaryOperator::Comma:
2373 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2374 break;
2375 }
2376 if (ResultTy.isNull())
2377 return true;
2378 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00002379 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002380 else
Chris Lattnerf420df12007-08-28 18:36:55 +00002381 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002382}
2383
2384// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002385Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002386 ExprTy *input) {
2387 Expr *Input = (Expr*)input;
2388 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2389 QualType resultType;
2390 switch (Opc) {
2391 default:
2392 assert(0 && "Unimplemented unary expr!");
2393 case UnaryOperator::PreInc:
2394 case UnaryOperator::PreDec:
2395 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2396 break;
2397 case UnaryOperator::AddrOf:
2398 resultType = CheckAddressOfOperand(Input, OpLoc);
2399 break;
2400 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002401 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002402 resultType = CheckIndirectionOperand(Input, OpLoc);
2403 break;
2404 case UnaryOperator::Plus:
2405 case UnaryOperator::Minus:
2406 UsualUnaryConversions(Input);
2407 resultType = Input->getType();
2408 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2409 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2410 resultType.getAsString());
2411 break;
2412 case UnaryOperator::Not: // bitwise complement
2413 UsualUnaryConversions(Input);
2414 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002415 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2416 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2417 // C99 does not support '~' for complex conjugation.
2418 Diag(OpLoc, diag::ext_integer_complement_complex,
2419 resultType.getAsString(), Input->getSourceRange());
2420 else if (!resultType->isIntegerType())
2421 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2422 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002423 break;
2424 case UnaryOperator::LNot: // logical negation
2425 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2426 DefaultFunctionArrayConversion(Input);
2427 resultType = Input->getType();
2428 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2429 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2430 resultType.getAsString());
2431 // LNot always has type int. C99 6.5.3.3p5.
2432 resultType = Context.IntTy;
2433 break;
2434 case UnaryOperator::SizeOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002435 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2436 Input->getSourceRange(), true);
Chris Lattner4b009652007-07-25 00:24:17 +00002437 break;
2438 case UnaryOperator::AlignOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002439 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2440 Input->getSourceRange(), false);
Chris Lattner4b009652007-07-25 00:24:17 +00002441 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002442 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002443 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002444 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002445 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002446 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002447 resultType = Input->getType();
2448 break;
2449 }
2450 if (resultType.isNull())
2451 return true;
2452 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2453}
2454
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002455/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2456Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002457 SourceLocation LabLoc,
2458 IdentifierInfo *LabelII) {
2459 // Look up the record for this label identifier.
2460 LabelStmt *&LabelDecl = LabelMap[LabelII];
2461
Daniel Dunbar879788d2008-08-04 16:51:22 +00002462 // If we haven't seen this label yet, create a forward reference. It
2463 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00002464 if (LabelDecl == 0)
2465 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2466
2467 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002468 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2469 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002470}
2471
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002472Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002473 SourceLocation RPLoc) { // "({..})"
2474 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2475 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2476 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2477
2478 // FIXME: there are a variety of strange constraints to enforce here, for
2479 // example, it is not possible to goto into a stmt expression apparently.
2480 // More semantic analysis is needed.
2481
2482 // FIXME: the last statement in the compount stmt has its value used. We
2483 // should not warn about it being unused.
2484
2485 // If there are sub stmts in the compound stmt, take the type of the last one
2486 // as the type of the stmtexpr.
2487 QualType Ty = Context.VoidTy;
2488
Chris Lattner200964f2008-07-26 19:51:01 +00002489 if (!Compound->body_empty()) {
2490 Stmt *LastStmt = Compound->body_back();
2491 // If LastStmt is a label, skip down through into the body.
2492 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2493 LastStmt = Label->getSubStmt();
2494
2495 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00002496 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00002497 }
Chris Lattner4b009652007-07-25 00:24:17 +00002498
2499 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2500}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002501
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002502Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002503 SourceLocation TypeLoc,
2504 TypeTy *argty,
2505 OffsetOfComponent *CompPtr,
2506 unsigned NumComponents,
2507 SourceLocation RPLoc) {
2508 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2509 assert(!ArgTy.isNull() && "Missing type argument!");
2510
2511 // We must have at least one component that refers to the type, and the first
2512 // one is known to be a field designator. Verify that the ArgTy represents
2513 // a struct/union/class.
2514 if (!ArgTy->isRecordType())
2515 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2516
2517 // Otherwise, create a compound literal expression as the base, and
2518 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002519 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002520
Chris Lattnerb37522e2007-08-31 21:49:13 +00002521 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2522 // GCC extension, diagnose them.
2523 if (NumComponents != 1)
2524 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2525 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2526
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002527 for (unsigned i = 0; i != NumComponents; ++i) {
2528 const OffsetOfComponent &OC = CompPtr[i];
2529 if (OC.isBrackets) {
2530 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00002531 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002532 if (!AT) {
2533 delete Res;
2534 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2535 Res->getType().getAsString());
2536 }
2537
Chris Lattner2af6a802007-08-30 17:59:59 +00002538 // FIXME: C++: Verify that operator[] isn't overloaded.
2539
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002540 // C99 6.5.2.1p1
2541 Expr *Idx = static_cast<Expr*>(OC.U.E);
2542 if (!Idx->getType()->isIntegerType())
2543 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2544 Idx->getSourceRange());
2545
2546 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2547 continue;
2548 }
2549
2550 const RecordType *RC = Res->getType()->getAsRecordType();
2551 if (!RC) {
2552 delete Res;
2553 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2554 Res->getType().getAsString());
2555 }
2556
2557 // Get the decl corresponding to this.
2558 RecordDecl *RD = RC->getDecl();
2559 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2560 if (!MemberDecl)
2561 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2562 OC.U.IdentInfo->getName(),
2563 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002564
2565 // FIXME: C++: Verify that MemberDecl isn't a static field.
2566 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002567 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2568 // matter here.
2569 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002570 }
2571
2572 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2573 BuiltinLoc);
2574}
2575
2576
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002577Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002578 TypeTy *arg1, TypeTy *arg2,
2579 SourceLocation RPLoc) {
2580 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2581 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2582
2583 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2584
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002585 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002586}
2587
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002588Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002589 ExprTy *expr1, ExprTy *expr2,
2590 SourceLocation RPLoc) {
2591 Expr *CondExpr = static_cast<Expr*>(cond);
2592 Expr *LHSExpr = static_cast<Expr*>(expr1);
2593 Expr *RHSExpr = static_cast<Expr*>(expr2);
2594
2595 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2596
2597 // The conditional expression is required to be a constant expression.
2598 llvm::APSInt condEval(32);
2599 SourceLocation ExpLoc;
2600 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2601 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2602 CondExpr->getSourceRange());
2603
2604 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2605 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2606 RHSExpr->getType();
2607 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2608}
2609
Nate Begemanbd881ef2008-01-30 20:50:20 +00002610/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002611/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002612/// The number of arguments has already been validated to match the number of
2613/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002614static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2615 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002616 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00002617 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002618 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2619 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00002620
2621 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002622 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00002623 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002624 return true;
2625}
2626
2627Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2628 SourceLocation *CommaLocs,
2629 SourceLocation BuiltinLoc,
2630 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002631 // __builtin_overload requires at least 2 arguments
2632 if (NumArgs < 2)
2633 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2634 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002635
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002636 // The first argument is required to be a constant expression. It tells us
2637 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002638 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002639 Expr *NParamsExpr = Args[0];
2640 llvm::APSInt constEval(32);
2641 SourceLocation ExpLoc;
2642 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2643 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2644 NParamsExpr->getSourceRange());
2645
2646 // Verify that the number of parameters is > 0
2647 unsigned NumParams = constEval.getZExtValue();
2648 if (NumParams == 0)
2649 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2650 NParamsExpr->getSourceRange());
2651 // Verify that we have at least 1 + NumParams arguments to the builtin.
2652 if ((NumParams + 1) > NumArgs)
2653 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2654 SourceRange(BuiltinLoc, RParenLoc));
2655
2656 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002657 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002658 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002659 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2660 // UsualUnaryConversions will convert the function DeclRefExpr into a
2661 // pointer to function.
2662 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002663 const FunctionTypeProto *FnType = 0;
2664 if (const PointerType *PT = Fn->getType()->getAsPointerType())
2665 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002666
2667 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2668 // parameters, and the number of parameters must match the value passed to
2669 // the builtin.
2670 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002671 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2672 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002673
2674 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002675 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002676 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002677 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002678 if (OE)
2679 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2680 OE->getFn()->getSourceRange());
2681 // Remember our match, and continue processing the remaining arguments
2682 // to catch any errors.
2683 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2684 BuiltinLoc, RParenLoc);
2685 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002686 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002687 // Return the newly created OverloadExpr node, if we succeded in matching
2688 // exactly one of the candidate functions.
2689 if (OE)
2690 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002691
2692 // If we didn't find a matching function Expr in the __builtin_overload list
2693 // the return an error.
2694 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002695 for (unsigned i = 0; i != NumParams; ++i) {
2696 if (i != 0) typeNames += ", ";
2697 typeNames += Args[i+1]->getType().getAsString();
2698 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002699
2700 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2701 SourceRange(BuiltinLoc, RParenLoc));
2702}
2703
Anders Carlsson36760332007-10-15 20:28:48 +00002704Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2705 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002706 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002707 Expr *E = static_cast<Expr*>(expr);
2708 QualType T = QualType::getFromOpaquePtr(type);
2709
2710 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00002711
2712 // Get the va_list type
2713 QualType VaListType = Context.getBuiltinVaListType();
2714 // Deal with implicit array decay; for example, on x86-64,
2715 // va_list is an array, but it's supposed to decay to
2716 // a pointer for va_arg.
2717 if (VaListType->isArrayType())
2718 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00002719 // Make sure the input expression also decays appropriately.
2720 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00002721
2722 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002723 return Diag(E->getLocStart(),
2724 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2725 E->getType().getAsString(),
2726 E->getSourceRange());
2727
2728 // FIXME: Warn if a non-POD type is passed in.
2729
2730 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2731}
2732
Chris Lattner005ed752008-01-04 18:04:52 +00002733bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2734 SourceLocation Loc,
2735 QualType DstType, QualType SrcType,
2736 Expr *SrcExpr, const char *Flavor) {
2737 // Decode the result (notice that AST's are still created for extensions).
2738 bool isInvalid = false;
2739 unsigned DiagKind;
2740 switch (ConvTy) {
2741 default: assert(0 && "Unknown conversion type");
2742 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002743 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002744 DiagKind = diag::ext_typecheck_convert_pointer_int;
2745 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002746 case IntToPointer:
2747 DiagKind = diag::ext_typecheck_convert_int_pointer;
2748 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002749 case IncompatiblePointer:
2750 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2751 break;
2752 case FunctionVoidPointer:
2753 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2754 break;
2755 case CompatiblePointerDiscardsQualifiers:
2756 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2757 break;
2758 case Incompatible:
2759 DiagKind = diag::err_typecheck_convert_incompatible;
2760 isInvalid = true;
2761 break;
2762 }
2763
2764 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2765 SrcExpr->getSourceRange());
2766 return isInvalid;
2767}