blob: 02169e6db84fc6fbff04a40484e18f6106297061 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026using namespace clang;
27
Chris Lattner299b8842008-07-25 21:10:04 +000028//===----------------------------------------------------------------------===//
29// Standard Promotions and Conversions
30//===----------------------------------------------------------------------===//
31
Chris Lattner299b8842008-07-25 21:10:04 +000032/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
33void Sema::DefaultFunctionArrayConversion(Expr *&E) {
34 QualType Ty = E->getType();
35 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
36
37 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
38 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
39 Ty = E->getType();
40 }
41 if (Ty->isFunctionType())
42 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000043 else if (Ty->isArrayType()) {
44 // In C90 mode, arrays only promote to pointers if the array expression is
45 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
46 // type 'array of type' is converted to an expression that has type 'pointer
47 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
48 // that has type 'array of type' ...". The relevant change is "an lvalue"
49 // (C90) to "an expression" (C99).
Chris Lattner25168a52008-07-26 21:30:36 +000050 if (getLangOptions().C99 || E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000051 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
52 }
Chris Lattner299b8842008-07-25 21:10:04 +000053}
54
55/// UsualUnaryConversions - Performs various conversions that are common to most
56/// operators (C99 6.3). The conversions of array and function types are
57/// sometimes surpressed. For example, the array->pointer conversion doesn't
58/// apply if the array is an argument to the sizeof or address (&) operators.
59/// In these instances, this routine should *not* be called.
60Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
61 QualType Ty = Expr->getType();
62 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
63
64 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
65 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
66 Ty = Expr->getType();
67 }
68 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
69 ImpCastExprToType(Expr, Context.IntTy);
70 else
71 DefaultFunctionArrayConversion(Expr);
72
73 return Expr;
74}
75
Chris Lattner9305c3d2008-07-25 22:25:12 +000076/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
77/// do not have a prototype. Arguments that have type float are promoted to
78/// double. All other argument types are converted by UsualUnaryConversions().
79void Sema::DefaultArgumentPromotion(Expr *&Expr) {
80 QualType Ty = Expr->getType();
81 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
82
83 // If this is a 'float' (CVR qualified or typedef) promote to double.
84 if (const BuiltinType *BT = Ty->getAsBuiltinType())
85 if (BT->getKind() == BuiltinType::Float)
86 return ImpCastExprToType(Expr, Context.DoubleTy);
87
88 UsualUnaryConversions(Expr);
89}
90
Chris Lattner299b8842008-07-25 21:10:04 +000091/// UsualArithmeticConversions - Performs various conversions that are common to
92/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
93/// routine returns the first non-arithmetic type found. The client is
94/// responsible for emitting appropriate error diagnostics.
95/// FIXME: verify the conversion rules for "complex int" are consistent with
96/// GCC.
97QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
98 bool isCompAssign) {
99 if (!isCompAssign) {
100 UsualUnaryConversions(lhsExpr);
101 UsualUnaryConversions(rhsExpr);
102 }
103 // For conversion purposes, we ignore any qualifiers.
104 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000105 QualType lhs =
106 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
107 QualType rhs =
108 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattner299b8842008-07-25 21:10:04 +0000109
110 // If both types are identical, no conversion is needed.
111 if (lhs == rhs)
112 return lhs;
113
114 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
115 // The caller can deal with this (e.g. pointer + int).
116 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
117 return lhs;
118
119 // At this point, we have two different arithmetic types.
120
121 // Handle complex types first (C99 6.3.1.8p1).
122 if (lhs->isComplexType() || rhs->isComplexType()) {
123 // if we have an integer operand, the result is the complex type.
124 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
125 // convert the rhs to the lhs complex type.
126 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
127 return lhs;
128 }
129 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
130 // convert the lhs to the rhs complex type.
131 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
132 return rhs;
133 }
134 // This handles complex/complex, complex/float, or float/complex.
135 // When both operands are complex, the shorter operand is converted to the
136 // type of the longer, and that is the type of the result. This corresponds
137 // to what is done when combining two real floating-point operands.
138 // The fun begins when size promotion occur across type domains.
139 // From H&S 6.3.4: When one operand is complex and the other is a real
140 // floating-point type, the less precise type is converted, within it's
141 // real or complex domain, to the precision of the other type. For example,
142 // when combining a "long double" with a "double _Complex", the
143 // "double _Complex" is promoted to "long double _Complex".
144 int result = Context.getFloatingTypeOrder(lhs, rhs);
145
146 if (result > 0) { // The left side is bigger, convert rhs.
147 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
148 if (!isCompAssign)
149 ImpCastExprToType(rhsExpr, rhs);
150 } else if (result < 0) { // The right side is bigger, convert lhs.
151 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
152 if (!isCompAssign)
153 ImpCastExprToType(lhsExpr, lhs);
154 }
155 // At this point, lhs and rhs have the same rank/size. Now, make sure the
156 // domains match. This is a requirement for our implementation, C99
157 // does not require this promotion.
158 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
159 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
160 if (!isCompAssign)
161 ImpCastExprToType(lhsExpr, rhs);
162 return rhs;
163 } else { // handle "_Complex double, double".
164 if (!isCompAssign)
165 ImpCastExprToType(rhsExpr, lhs);
166 return lhs;
167 }
168 }
169 return lhs; // The domain/size match exactly.
170 }
171 // Now handle "real" floating types (i.e. float, double, long double).
172 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
173 // if we have an integer operand, the result is the real floating type.
174 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
175 // convert rhs to the lhs floating point type.
176 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
177 return lhs;
178 }
179 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
180 // convert lhs to the rhs floating point type.
181 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
182 return rhs;
183 }
184 // We have two real floating types, float/complex combos were handled above.
185 // Convert the smaller operand to the bigger result.
186 int result = Context.getFloatingTypeOrder(lhs, rhs);
187
188 if (result > 0) { // convert the rhs
189 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
190 return lhs;
191 }
192 if (result < 0) { // convert the lhs
193 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
194 return rhs;
195 }
196 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
197 }
198 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
199 // Handle GCC complex int extension.
200 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
201 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
202
203 if (lhsComplexInt && rhsComplexInt) {
204 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
205 rhsComplexInt->getElementType()) >= 0) {
206 // convert the rhs
207 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
208 return lhs;
209 }
210 if (!isCompAssign)
211 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
212 return rhs;
213 } else if (lhsComplexInt && rhs->isIntegerType()) {
214 // convert the rhs to the lhs complex type.
215 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
216 return lhs;
217 } else if (rhsComplexInt && lhs->isIntegerType()) {
218 // convert the lhs to the rhs complex type.
219 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
220 return rhs;
221 }
222 }
223 // Finally, we have two differing integer types.
224 // The rules for this case are in C99 6.3.1.8
225 int compare = Context.getIntegerTypeOrder(lhs, rhs);
226 bool lhsSigned = lhs->isSignedIntegerType(),
227 rhsSigned = rhs->isSignedIntegerType();
228 QualType destType;
229 if (lhsSigned == rhsSigned) {
230 // Same signedness; use the higher-ranked type
231 destType = compare >= 0 ? lhs : rhs;
232 } else if (compare != (lhsSigned ? 1 : -1)) {
233 // The unsigned type has greater than or equal rank to the
234 // signed type, so use the unsigned type
235 destType = lhsSigned ? rhs : lhs;
236 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
237 // The two types are different widths; if we are here, that
238 // means the signed type is larger than the unsigned type, so
239 // use the signed type.
240 destType = lhsSigned ? lhs : rhs;
241 } else {
242 // The signed type is higher-ranked than the unsigned type,
243 // but isn't actually any bigger (like unsigned int and long
244 // on most 32-bit systems). Use the unsigned type corresponding
245 // to the signed type.
246 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
247 }
248 if (!isCompAssign) {
249 ImpCastExprToType(lhsExpr, destType);
250 ImpCastExprToType(rhsExpr, destType);
251 }
252 return destType;
253}
254
255//===----------------------------------------------------------------------===//
256// Semantic Analysis for various Expression Types
257//===----------------------------------------------------------------------===//
258
259
Steve Naroff87d58b42007-09-16 03:34:24 +0000260/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000261/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
262/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
263/// multiple tokens. However, the common case is that StringToks points to one
264/// string.
265///
266Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000267Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000268 assert(NumStringToks && "Must have at least one string!");
269
270 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
271 if (Literal.hadError)
272 return ExprResult(true);
273
274 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
275 for (unsigned i = 0; i != NumStringToks; ++i)
276 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000277
278 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000279 if (Literal.Pascal && Literal.GetStringLength() > 256)
280 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
281 SourceRange(StringToks[0].getLocation(),
282 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000283
Chris Lattnera6dcce32008-02-11 00:02:17 +0000284 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000285 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000286 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
287
288 // Get an array type for the string, according to C99 6.4.5. This includes
289 // the nul terminator character as well as the string length for pascal
290 // strings.
291 StrTy = Context.getConstantArrayType(StrTy,
292 llvm::APInt(32, Literal.GetStringLength()+1),
293 ArrayType::Normal, 0);
294
Chris Lattner4b009652007-07-25 00:24:17 +0000295 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
296 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000297 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000298 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000299 StringToks[NumStringToks-1].getLocation());
300}
301
302
Steve Naroff0acc9c92007-09-15 18:49:24 +0000303/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000304/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000305/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000306Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000307 IdentifierInfo &II,
308 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000309 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +0000310 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000311
312 // If this reference is in an Objective-C method, then ivar lookup happens as
313 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000314 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000315 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000316 // There are two cases to handle here. 1) scoped lookup could have failed,
317 // in which case we should look for an ivar. 2) scoped lookup could have
318 // found a decl, but that decl is outside the current method (i.e. a global
319 // variable). In these two cases, we do a lookup for an ivar with this
320 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000321 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000322 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattnered94f762008-07-21 04:44:44 +0000323 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000324 // FIXME: This should use a new expr for a direct reference, don't turn
325 // this into Self->ivar, just return a BareIVarExpr or something.
326 IdentifierInfo &II = Context.Idents.get("self");
327 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
328 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
329 static_cast<Expr*>(SelfExpr.Val), true, true);
330 }
331 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000332 // Needed to implement property "super.method" notation.
Daniel Dunbar4837ae72008-08-14 22:04:54 +0000333 if (SD == 0 && &II == SuperID) {
Steve Naroff6f786252008-06-02 23:03:37 +0000334 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000335 getCurMethodDecl()->getClassInterface()));
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000336 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroff6f786252008-06-02 23:03:37 +0000337 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000338 }
339
Chris Lattner4b009652007-07-25 00:24:17 +0000340 if (D == 0) {
341 // Otherwise, this could be an implicitly declared function reference (legal
342 // in C90, extension in C99).
343 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000344 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000345 D = ImplicitlyDefineFunction(Loc, II, S);
346 else {
347 // If this name wasn't predeclared and if this is not a function call,
348 // diagnose the problem.
349 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
350 }
351 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000352
Steve Naroff91b03f72007-08-28 03:03:08 +0000353 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneree4c3bf2008-02-29 16:48:43 +0000354 // check if referencing an identifier with __attribute__((deprecated)).
355 if (VD->getAttr<DeprecatedAttr>())
356 Diag(Loc, diag::warn_deprecated, VD->getName());
357
Steve Naroffcae537d2007-08-28 18:45:29 +0000358 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000359 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000360 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000361 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000362 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000363
364 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
365 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
366 if (MD->isStatic())
367 // "invalid use of member 'x' in static member function"
368 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
369 FD->getName());
370 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
371 // "invalid use of nonstatic data member 'x'"
372 return Diag(Loc, diag::err_invalid_non_static_member_use,
373 FD->getName());
374
375 if (FD->isInvalidDecl())
376 return true;
377
378 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
379 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
380 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
381 true, FD, Loc, FD->getType());
382 }
383
384 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
385 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000386
Chris Lattner4b009652007-07-25 00:24:17 +0000387 if (isa<TypedefDecl>(D))
388 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000389 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000390 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000391 if (isa<NamespaceDecl>(D))
392 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000393
394 assert(0 && "Invalid decl");
395 abort();
396}
397
Chris Lattner69909292008-08-10 01:53:14 +0000398Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000399 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000400 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000401
402 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000403 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000404 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
405 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
406 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000407 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000408
409 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000410 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000411 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000412
Chris Lattner7e637512008-01-12 08:14:25 +0000413 // Pre-defined identifiers are of type char[x], where x is the length of the
414 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000415 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000416 if (getCurFunctionDecl())
417 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000418 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000419 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000420
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000421 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000422 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000423 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000424 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000425}
426
Steve Naroff87d58b42007-09-16 03:34:24 +0000427Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000428 llvm::SmallString<16> CharBuffer;
429 CharBuffer.resize(Tok.getLength());
430 const char *ThisTokBegin = &CharBuffer[0];
431 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
432
433 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
434 Tok.getLocation(), PP);
435 if (Literal.hadError())
436 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000437
438 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
439
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000440 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
441 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000442}
443
Steve Naroff87d58b42007-09-16 03:34:24 +0000444Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000445 // fast path for a single digit (which is quite common). A single digit
446 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
447 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000448 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000449
Chris Lattner8cd0e932008-03-05 18:54:05 +0000450 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000451 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000452 Context.IntTy,
453 Tok.getLocation()));
454 }
455 llvm::SmallString<512> IntegerBuffer;
456 IntegerBuffer.resize(Tok.getLength());
457 const char *ThisTokBegin = &IntegerBuffer[0];
458
459 // Get the spelling of the token, which eliminates trigraphs, etc.
460 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
461 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
462 Tok.getLocation(), PP);
463 if (Literal.hadError)
464 return ExprResult(true);
465
Chris Lattner1de66eb2007-08-26 03:42:43 +0000466 Expr *Res;
467
468 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000469 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000470 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000471 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000472 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000473 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000474 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000475 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000476
477 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
478
Ted Kremenekddedbe22007-11-29 00:56:49 +0000479 // isExact will be set by GetFloatValue().
480 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000481 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000482 Ty, Tok.getLocation());
483
Chris Lattner1de66eb2007-08-26 03:42:43 +0000484 } else if (!Literal.isIntegerLiteral()) {
485 return ExprResult(true);
486 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000487 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000488
Neil Booth7421e9c2007-08-29 22:00:19 +0000489 // long long is a C99 feature.
490 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000491 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000492 Diag(Tok.getLocation(), diag::ext_longlong);
493
Chris Lattner4b009652007-07-25 00:24:17 +0000494 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000495 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000496
497 if (Literal.GetIntegerValue(ResultVal)) {
498 // If this value didn't fit into uintmax_t, warn and force to ull.
499 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000500 Ty = Context.UnsignedLongLongTy;
501 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000502 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000503 } else {
504 // If this value fits into a ULL, try to figure out what else it fits into
505 // according to the rules of C99 6.4.4.1p5.
506
507 // Octal, Hexadecimal, and integers with a U suffix are allowed to
508 // be an unsigned int.
509 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
510
511 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000512 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000513 if (!Literal.isLong && !Literal.isLongLong) {
514 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000515 unsigned IntSize = Context.Target.getIntWidth();
516
Chris Lattner4b009652007-07-25 00:24:17 +0000517 // Does it fit in a unsigned int?
518 if (ResultVal.isIntN(IntSize)) {
519 // Does it fit in a signed int?
520 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000521 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000522 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000523 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000524 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000525 }
Chris Lattner4b009652007-07-25 00:24:17 +0000526 }
527
528 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000529 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000530 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000531
532 // Does it fit in a unsigned long?
533 if (ResultVal.isIntN(LongSize)) {
534 // Does it fit in a signed long?
535 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000536 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000537 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000538 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000539 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000540 }
Chris Lattner4b009652007-07-25 00:24:17 +0000541 }
542
543 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000544 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000545 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000546
547 // Does it fit in a unsigned long long?
548 if (ResultVal.isIntN(LongLongSize)) {
549 // Does it fit in a signed long long?
550 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000551 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000552 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000553 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000554 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000555 }
556 }
557
558 // If we still couldn't decide a type, we probably have something that
559 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000560 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000561 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000562 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000563 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000564 }
Chris Lattnere4068872008-05-09 05:59:00 +0000565
566 if (ResultVal.getBitWidth() != Width)
567 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000568 }
569
Chris Lattner48d7f382008-04-02 04:24:33 +0000570 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000571 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000572
573 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
574 if (Literal.isImaginary)
575 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
576
577 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000578}
579
Steve Naroff87d58b42007-09-16 03:34:24 +0000580Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000581 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000582 Expr *E = (Expr *)Val;
583 assert((E != 0) && "ActOnParenExpr() missing expr");
584 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000585}
586
587/// The UsualUnaryConversions() function is *not* called by this routine.
588/// See C99 6.3.2.1p[2-4] for more details.
589QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerf814d882008-07-25 21:45:37 +0000590 SourceLocation OpLoc,
591 const SourceRange &ExprRange,
592 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000593 // C99 6.5.3.4p1:
594 if (isa<FunctionType>(exprType) && isSizeof)
595 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000596 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000597 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000598 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
599 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000600 else if (exprType->isIncompleteType()) {
601 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
602 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000603 exprType.getAsString(), ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000604 return QualType(); // error
605 }
606 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
607 return Context.getSizeType();
608}
609
610Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000611ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000612 SourceLocation LPLoc, TypeTy *Ty,
613 SourceLocation RPLoc) {
614 // If error parsing type, ignore.
615 if (Ty == 0) return true;
616
617 // Verify that this is a valid expression.
618 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
619
Chris Lattnerf814d882008-07-25 21:45:37 +0000620 QualType resultType =
621 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Chris Lattner4b009652007-07-25 00:24:17 +0000622
623 if (resultType.isNull())
624 return true;
625 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
626}
627
Chris Lattner5110ad52007-08-24 21:41:10 +0000628QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000629 DefaultFunctionArrayConversion(V);
630
Chris Lattnera16e42d2007-08-26 05:39:26 +0000631 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000632 if (const ComplexType *CT = V->getType()->getAsComplexType())
633 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000634
635 // Otherwise they pass through real integer and floating point types here.
636 if (V->getType()->isArithmeticType())
637 return V->getType();
638
639 // Reject anything else.
640 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
641 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000642}
643
644
Chris Lattner4b009652007-07-25 00:24:17 +0000645
Steve Naroff87d58b42007-09-16 03:34:24 +0000646Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000647 tok::TokenKind Kind,
648 ExprTy *Input) {
649 UnaryOperator::Opcode Opc;
650 switch (Kind) {
651 default: assert(0 && "Unknown unary op!");
652 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
653 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
654 }
655 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
656 if (result.isNull())
657 return true;
658 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
659}
660
661Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000662ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000663 ExprTy *Idx, SourceLocation RLoc) {
664 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
665
666 // Perform default conversions.
667 DefaultFunctionArrayConversion(LHSExp);
668 DefaultFunctionArrayConversion(RHSExp);
669
670 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
671
672 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000673 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000674 // in the subscript position. As a result, we need to derive the array base
675 // and index from the expression types.
676 Expr *BaseExpr, *IndexExpr;
677 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000678 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000679 BaseExpr = LHSExp;
680 IndexExpr = RHSExp;
681 // FIXME: need to deal with const...
682 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000683 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000684 // Handle the uncommon case of "123[Ptr]".
685 BaseExpr = RHSExp;
686 IndexExpr = LHSExp;
687 // FIXME: need to deal with const...
688 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000689 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
690 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000691 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000692
693 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000694 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
695 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000696 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000697 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000698 // FIXME: need to deal with const...
699 ResultType = VTy->getElementType();
700 } else {
701 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
702 RHSExp->getSourceRange());
703 }
704 // C99 6.5.2.1p1
705 if (!IndexExpr->getType()->isIntegerType())
706 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
707 IndexExpr->getSourceRange());
708
709 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
710 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000711 // void (*)(int)) and pointers to incomplete types. Functions are not
712 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000713 if (!ResultType->isObjectType())
714 return Diag(BaseExpr->getLocStart(),
715 diag::err_typecheck_subscript_not_object,
716 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
717
718 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
719}
720
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000721QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000722CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000723 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000724 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000725
726 // This flag determines whether or not the component is to be treated as a
727 // special name, or a regular GLSL-style component access.
728 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000729
730 // The vector accessor can't exceed the number of elements.
731 const char *compStr = CompName.getName();
732 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000733 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000734 baseType.getAsString(), SourceRange(CompLoc));
735 return QualType();
736 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000737
738 // Check that we've found one of the special components, or that the component
739 // names must come from the same set.
740 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
741 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
742 SpecialComponent = true;
743 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000744 do
745 compStr++;
746 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
747 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
748 do
749 compStr++;
750 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
751 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
752 do
753 compStr++;
754 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
755 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000756
Nate Begemanc8e51f82008-05-09 06:41:27 +0000757 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000758 // We didn't get to the end of the string. This means the component names
759 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000760 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000761 std::string(compStr,compStr+1), SourceRange(CompLoc));
762 return QualType();
763 }
764 // Each component accessor can't exceed the vector type.
765 compStr = CompName.getName();
766 while (*compStr) {
767 if (vecType->isAccessorWithinNumElements(*compStr))
768 compStr++;
769 else
770 break;
771 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000772 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000773 // We didn't get to the end of the string. This means a component accessor
774 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000775 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000776 baseType.getAsString(), SourceRange(CompLoc));
777 return QualType();
778 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000779
780 // If we have a special component name, verify that the current vector length
781 // is an even number, since all special component names return exactly half
782 // the elements.
783 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
784 return QualType();
785 }
786
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000787 // The component accessor looks fine - now we need to compute the actual type.
788 // The vector type is implied by the component accessor. For example,
789 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000790 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
791 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
792 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000793 if (CompSize == 1)
794 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000795
Nate Begemanaf6ed502008-04-18 23:10:10 +0000796 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000797 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000798 // diagostics look bad. We want extended vector types to appear built-in.
799 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
800 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
801 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000802 }
803 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000804}
805
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000806/// constructSetterName - Return the setter name for the given
807/// identifier, i.e. "set" + Name where the initial character of Name
808/// has been capitalized.
809// FIXME: Merge with same routine in Parser. But where should this
810// live?
811static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
812 const IdentifierInfo *Name) {
813 unsigned N = Name->getLength();
814 char *SelectorName = new char[3 + N];
815 memcpy(SelectorName, "set", 3);
816 memcpy(&SelectorName[3], Name->getName(), N);
817 SelectorName[3] = toupper(SelectorName[3]);
818
819 IdentifierInfo *Setter =
820 &Idents.get(SelectorName, &SelectorName[3 + N]);
821 delete[] SelectorName;
822 return Setter;
823}
824
Chris Lattner4b009652007-07-25 00:24:17 +0000825Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000826ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000827 tok::TokenKind OpKind, SourceLocation MemberLoc,
828 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000829 Expr *BaseExpr = static_cast<Expr *>(Base);
830 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000831
832 // Perform default conversions.
833 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000834
Steve Naroff2cb66382007-07-26 03:11:44 +0000835 QualType BaseType = BaseExpr->getType();
836 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000837
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000838 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
839 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000840 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000841 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000842 BaseType = PT->getPointeeType();
843 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000844 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
845 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000846 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000847
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000848 // Handle field access to simple records. This also handles access to fields
849 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000850 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000851 RecordDecl *RDecl = RTy->getDecl();
852 if (RTy->isIncompleteType())
853 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
854 BaseExpr->getSourceRange());
855 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000856 FieldDecl *MemberDecl = RDecl->getMember(&Member);
857 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000858 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
859 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000860
861 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000862 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000863 QualType MemberType = MemberDecl->getType();
864 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000865 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000866 MemberType = MemberType.getQualifiedType(combinedQualifiers);
867
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000868 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000869 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000870 }
871
Chris Lattnere9d71612008-07-21 04:59:05 +0000872 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
873 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000874 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
875 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000876 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000877 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000878 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000879 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000880 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000881 }
882
Chris Lattnere9d71612008-07-21 04:59:05 +0000883 // Handle Objective-C property access, which is "Obj.property" where Obj is a
884 // pointer to a (potentially qualified) interface type.
885 const PointerType *PTy;
886 const ObjCInterfaceType *IFTy;
887 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
888 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
889 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +0000890
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000891 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +0000892 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
893 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
894
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000895 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000896 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
897 E = IFTy->qual_end(); I != E; ++I)
898 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
899 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000900
901 // If that failed, look for an "implicit" property by seeing if the nullary
902 // selector is implemented.
903
904 // FIXME: The logic for looking up nullary and unary selectors should be
905 // shared with the code in ActOnInstanceMessage.
906
907 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
908 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
909
910 // If this reference is in an @implementation, check for 'private' methods.
911 if (!Getter)
912 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
913 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
914 if (ObjCImplementationDecl *ImpDecl =
915 ObjCImplementations[ClassDecl->getIdentifier()])
916 Getter = ImpDecl->getInstanceMethod(Sel);
917
918 if (Getter) {
919 // If we found a getter then this may be a valid dot-reference, we
920 // need to also look for the matching setter.
921 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
922 &Member);
923 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
924 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
925
926 if (!Setter) {
927 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
928 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
929 if (ObjCImplementationDecl *ImpDecl =
930 ObjCImplementations[ClassDecl->getIdentifier()])
931 Setter = ImpDecl->getInstanceMethod(SetterSel);
932 }
933
934 // FIXME: There are some issues here. First, we are not
935 // diagnosing accesses to read-only properties because we do not
936 // know if this is a getter or setter yet. Second, we are
937 // checking that the type of the setter matches the type we
938 // expect.
939 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
940 MemberLoc, BaseExpr);
941 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000942 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000943
944 // Handle 'field access' to vectors, such as 'V.xx'.
945 if (BaseType->isExtVectorType() && OpKind == tok::period) {
946 // Component access limited to variables (reject vec4.rg.g).
947 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
948 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +0000949 return Diag(MemberLoc, diag::err_ext_vector_component_access,
950 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000951 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
952 if (ret.isNull())
953 return true;
954 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
955 }
956
Chris Lattner7d5a8762008-07-21 05:35:34 +0000957 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
958 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000959}
960
Steve Naroff87d58b42007-09-16 03:34:24 +0000961/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000962/// This provides the location of the left/right parens and a list of comma
963/// locations.
964Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000965ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000966 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000967 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
968 Expr *Fn = static_cast<Expr *>(fn);
969 Expr **Args = reinterpret_cast<Expr**>(args);
970 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +0000971 FunctionDecl *FDecl = NULL;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000972
973 // Promote the function operand.
974 UsualUnaryConversions(Fn);
975
976 // If we're directly calling a function, get the declaration for
977 // that function.
978 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
979 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
980 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
981
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000982 // Make the call expr early, before semantic checks. This guarantees cleanup
983 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +0000984 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000985 Context.BoolTy, RParenLoc));
986
Chris Lattner4b009652007-07-25 00:24:17 +0000987 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
988 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000989 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000990 if (PT == 0)
Chris Lattner61000b12008-08-14 04:33:24 +0000991 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
992 Fn->getSourceRange());
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000993 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
994 if (FuncT == 0)
Chris Lattner61000b12008-08-14 04:33:24 +0000995 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
996 Fn->getSourceRange());
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000997
998 // We know the result type of the call, set it.
999 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +00001000
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001001 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001002 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1003 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001004 unsigned NumArgsInProto = Proto->getNumArgs();
1005 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001006
Chris Lattner3e254fb2008-04-08 04:40:51 +00001007 // If too few arguments are available (and we don't have default
1008 // arguments for the remaining parameters), don't make the call.
1009 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +00001010 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001011 // Use default arguments for missing arguments
1012 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +00001013 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001014 } else
1015 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
1016 Fn->getSourceRange());
1017 }
1018
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001019 // If too many are passed and not variadic, error on the extras and drop
1020 // them.
1021 if (NumArgs > NumArgsInProto) {
1022 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001023 Diag(Args[NumArgsInProto]->getLocStart(),
1024 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
1025 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001026 Args[NumArgs-1]->getLocEnd()));
1027 // This deletes the extra arguments.
1028 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001029 }
1030 NumArgsToCheck = NumArgsInProto;
1031 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001032
Chris Lattner4b009652007-07-25 00:24:17 +00001033 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001034 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001035 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001036
1037 Expr *Arg;
1038 if (i < NumArgs)
1039 Arg = Args[i];
1040 else
1041 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001042 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001043
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001044 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +00001045 AssignConvertType ConvTy =
1046 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001047 TheCall->setArg(i, Arg);
Eli Friedman583c31e2008-09-02 05:09:35 +00001048
Chris Lattner005ed752008-01-04 18:04:52 +00001049 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1050 ArgType, Arg, "passing"))
1051 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001052 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001053
1054 // If this is a variadic call, handle args passed through "...".
1055 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001056 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001057 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1058 Expr *Arg = Args[i];
1059 DefaultArgumentPromotion(Arg);
1060 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001061 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001062 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001063 } else {
1064 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1065
Steve Naroffdb65e052007-08-28 23:30:39 +00001066 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001067 for (unsigned i = 0; i != NumArgs; i++) {
1068 Expr *Arg = Args[i];
1069 DefaultArgumentPromotion(Arg);
1070 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001071 }
Chris Lattner4b009652007-07-25 00:24:17 +00001072 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001073
Chris Lattner2e64c072007-08-10 20:18:51 +00001074 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001075 if (FDecl)
1076 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001077
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001078 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001079}
1080
1081Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001082ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001083 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001084 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001085 QualType literalType = QualType::getFromOpaquePtr(Ty);
1086 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001087 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001088 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001089
Eli Friedman8c2173d2008-05-20 05:22:08 +00001090 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001091 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001092 return Diag(LParenLoc,
1093 diag::err_variable_object_no_init,
1094 SourceRange(LParenLoc,
1095 literalExpr->getSourceRange().getEnd()));
1096 } else if (literalType->isIncompleteType()) {
1097 return Diag(LParenLoc,
1098 diag::err_typecheck_decl_incomplete_type,
1099 literalType.getAsString(),
1100 SourceRange(LParenLoc,
1101 literalExpr->getSourceRange().getEnd()));
1102 }
1103
Steve Narofff0b23542008-01-10 22:15:12 +00001104 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +00001105 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001106
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001107 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001108 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001109 if (CheckForConstantInitializer(literalExpr, literalType))
1110 return true;
1111 }
Steve Naroffbe37fc02008-01-14 18:19:28 +00001112 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001113}
1114
1115Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001116ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001117 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001118 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001119
Steve Naroff0acc9c92007-09-15 18:49:24 +00001120 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001121 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001122
Chris Lattner48d7f382008-04-02 04:24:33 +00001123 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1124 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1125 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001126}
1127
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001128/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001129bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001130 UsualUnaryConversions(castExpr);
1131
1132 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1133 // type needs to be scalar.
1134 if (castType->isVoidType()) {
1135 // Cast to void allows any expr type.
1136 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1137 // GCC struct/union extension: allow cast to self.
1138 if (Context.getCanonicalType(castType) !=
1139 Context.getCanonicalType(castExpr->getType()) ||
1140 (!castType->isStructureType() && !castType->isUnionType())) {
1141 // Reject any other conversions to non-scalar types.
1142 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1143 castType.getAsString(), castExpr->getSourceRange());
1144 }
1145
1146 // accept this, but emit an ext-warn.
1147 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1148 castType.getAsString(), castExpr->getSourceRange());
1149 } else if (!castExpr->getType()->isScalarType() &&
1150 !castExpr->getType()->isVectorType()) {
1151 return Diag(castExpr->getLocStart(),
1152 diag::err_typecheck_expect_scalar_operand,
1153 castExpr->getType().getAsString(),castExpr->getSourceRange());
1154 } else if (castExpr->getType()->isVectorType()) {
1155 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1156 return true;
1157 } else if (castType->isVectorType()) {
1158 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1159 return true;
1160 }
1161 return false;
1162}
1163
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001164bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001165 assert(VectorTy->isVectorType() && "Not a vector type!");
1166
1167 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001168 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001169 return Diag(R.getBegin(),
1170 Ty->isVectorType() ?
1171 diag::err_invalid_conversion_between_vectors :
1172 diag::err_invalid_conversion_between_vector_and_integer,
1173 VectorTy.getAsString().c_str(),
1174 Ty.getAsString().c_str(), R);
1175 } else
1176 return Diag(R.getBegin(),
1177 diag::err_invalid_conversion_between_vector_and_scalar,
1178 VectorTy.getAsString().c_str(),
1179 Ty.getAsString().c_str(), R);
1180
1181 return false;
1182}
1183
Chris Lattner4b009652007-07-25 00:24:17 +00001184Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001185ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001186 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001187 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001188
1189 Expr *castExpr = static_cast<Expr*>(Op);
1190 QualType castType = QualType::getFromOpaquePtr(Ty);
1191
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001192 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1193 return true;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001194 return new ExplicitCastExpr(castType, castExpr, LParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001195}
1196
Chris Lattner98a425c2007-11-26 01:40:58 +00001197/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1198/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001199inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1200 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1201 UsualUnaryConversions(cond);
1202 UsualUnaryConversions(lex);
1203 UsualUnaryConversions(rex);
1204 QualType condT = cond->getType();
1205 QualType lexT = lex->getType();
1206 QualType rexT = rex->getType();
1207
1208 // first, check the condition.
1209 if (!condT->isScalarType()) { // C99 6.5.15p2
1210 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1211 condT.getAsString());
1212 return QualType();
1213 }
Chris Lattner992ae932008-01-06 22:42:25 +00001214
1215 // Now check the two expressions.
1216
1217 // If both operands have arithmetic type, do the usual arithmetic conversions
1218 // to find a common type: C99 6.5.15p3,5.
1219 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001220 UsualArithmeticConversions(lex, rex);
1221 return lex->getType();
1222 }
Chris Lattner992ae932008-01-06 22:42:25 +00001223
1224 // If both operands are the same structure or union type, the result is that
1225 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001226 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001227 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001228 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001229 // "If both the operands have structure or union type, the result has
1230 // that type." This implies that CV qualifiers are dropped.
1231 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001232 }
Chris Lattner992ae932008-01-06 22:42:25 +00001233
1234 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001235 // The following || allows only one side to be void (a GCC-ism).
1236 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001237 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001238 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1239 rex->getSourceRange());
1240 if (!rexT->isVoidType())
1241 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001242 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001243 ImpCastExprToType(lex, Context.VoidTy);
1244 ImpCastExprToType(rex, Context.VoidTy);
1245 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001246 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001247 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1248 // the type of the other operand."
1249 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001250 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001251 return lexT;
1252 }
1253 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001254 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001255 return rexT;
1256 }
Daniel Dunbarcc785c82008-09-03 17:53:25 +00001257 // Allow any Objective-C types to devolve to id type.
1258 // FIXME: This seems to match gcc behavior, although that is very
1259 // arguably incorrect. For example, (xxx ? (id<P>) : (id<P>)) has
1260 // type id, which seems broken.
1261 if (Context.isObjCObjectPointerType(lexT) &&
1262 Context.isObjCObjectPointerType(rexT)) {
1263 // FIXME: This is not the correct composite type. This only
1264 // happens to work because id can more or less be used anywhere,
1265 // however this may change the type of method sends.
1266 // FIXME: gcc adds some type-checking of the arguments and emits
1267 // (confusing) incompatible comparison warnings in some
1268 // cases. Investigate.
1269 QualType compositeType = Context.getObjCIdType();
1270 ImpCastExprToType(lex, compositeType);
1271 ImpCastExprToType(rex, compositeType);
1272 return compositeType;
1273 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001274 // Handle the case where both operands are pointers before we handle null
1275 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001276 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1277 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1278 // get the "pointed to" types
1279 QualType lhptee = LHSPT->getPointeeType();
1280 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001281
Chris Lattner71225142007-07-31 21:27:01 +00001282 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1283 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001284 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001285 // Figure out necessary qualifiers (C99 6.5.15p6)
1286 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001287 QualType destType = Context.getPointerType(destPointee);
1288 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1289 ImpCastExprToType(rex, destType); // promote to void*
1290 return destType;
1291 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001292 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001293 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001294 QualType destType = Context.getPointerType(destPointee);
1295 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1296 ImpCastExprToType(rex, destType); // promote to void*
1297 return destType;
1298 }
Chris Lattner4b009652007-07-25 00:24:17 +00001299
Steve Naroff85f0dc52007-10-15 20:41:53 +00001300 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1301 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001302 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001303 lexT.getAsString(), rexT.getAsString(),
1304 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001305 // In this situation, assume a conservative type; in general
1306 // we assume void* type. No especially good reason, but this
1307 // is what gcc does, and we do have to pick to get a
1308 // consistent AST. However, if either type is an Objective-C
1309 // object type then use id.
1310 QualType incompatTy;
1311 if (Context.isObjCObjectPointerType(lexT) ||
1312 Context.isObjCObjectPointerType(rexT)) {
1313 incompatTy = Context.getObjCIdType();
1314 } else {
1315 incompatTy = Context.getPointerType(Context.VoidTy);
1316 }
1317 ImpCastExprToType(lex, incompatTy);
1318 ImpCastExprToType(rex, incompatTy);
1319 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001320 }
1321 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001322 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1323 // differently qualified versions of compatible types, the result type is
1324 // a pointer to an appropriately qualified version of the *composite*
1325 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001326 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001327 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001328 QualType compositeType = lexT;
1329 ImpCastExprToType(lex, compositeType);
1330 ImpCastExprToType(rex, compositeType);
1331 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001332 }
Chris Lattner4b009652007-07-25 00:24:17 +00001333 }
Chris Lattner992ae932008-01-06 22:42:25 +00001334 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001335 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1336 lexT.getAsString(), rexT.getAsString(),
1337 lex->getSourceRange(), rex->getSourceRange());
1338 return QualType();
1339}
1340
Steve Naroff87d58b42007-09-16 03:34:24 +00001341/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001342/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001343Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001344 SourceLocation ColonLoc,
1345 ExprTy *Cond, ExprTy *LHS,
1346 ExprTy *RHS) {
1347 Expr *CondExpr = (Expr *) Cond;
1348 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001349
1350 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1351 // was the condition.
1352 bool isLHSNull = LHSExpr == 0;
1353 if (isLHSNull)
1354 LHSExpr = CondExpr;
1355
Chris Lattner4b009652007-07-25 00:24:17 +00001356 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1357 RHSExpr, QuestionLoc);
1358 if (result.isNull())
1359 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001360 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1361 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001362}
1363
Chris Lattner4b009652007-07-25 00:24:17 +00001364
1365// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1366// being closely modeled after the C99 spec:-). The odd characteristic of this
1367// routine is it effectively iqnores the qualifiers on the top level pointee.
1368// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1369// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001370Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001371Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1372 QualType lhptee, rhptee;
1373
1374 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001375 lhptee = lhsType->getAsPointerType()->getPointeeType();
1376 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001377
1378 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001379 lhptee = Context.getCanonicalType(lhptee);
1380 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001381
Chris Lattner005ed752008-01-04 18:04:52 +00001382 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001383
1384 // C99 6.5.16.1p1: This following citation is common to constraints
1385 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1386 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001387 // FIXME: Handle ASQualType
1388 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1389 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001390 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001391
1392 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1393 // incomplete type and the other is a pointer to a qualified or unqualified
1394 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001395 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001396 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001397 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001398
1399 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001400 assert(rhptee->isFunctionType());
1401 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001402 }
1403
1404 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001405 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001406 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001407
1408 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001409 assert(lhptee->isFunctionType());
1410 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001411 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001412
1413 // Check for ObjC interfaces
1414 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1415 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1416 if (LHSIface && RHSIface &&
1417 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1418 return ConvTy;
1419
1420 // ID acts sort of like void* for ObjC interfaces
1421 if (LHSIface && Context.isObjCIdType(rhptee))
1422 return ConvTy;
1423 if (RHSIface && Context.isObjCIdType(lhptee))
1424 return ConvTy;
1425
Chris Lattner4b009652007-07-25 00:24:17 +00001426 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1427 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001428 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1429 rhptee.getUnqualifiedType()))
1430 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001431 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001432}
1433
Steve Naroff3454b6c2008-09-04 15:10:53 +00001434/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1435/// block pointer types are compatible or whether a block and normal pointer
1436/// are compatible. It is more restrict than comparing two function pointer
1437// types.
1438Sema::AssignConvertType
1439Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1440 QualType rhsType) {
1441 QualType lhptee, rhptee;
1442
1443 // get the "pointed to" type (ignoring qualifiers at the top level)
1444 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1445 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1446
1447 // make sure we operate on the canonical type
1448 lhptee = Context.getCanonicalType(lhptee);
1449 rhptee = Context.getCanonicalType(rhptee);
1450
1451 AssignConvertType ConvTy = Compatible;
1452
1453 // For blocks we enforce that qualifiers are identical.
1454 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1455 ConvTy = CompatiblePointerDiscardsQualifiers;
1456
1457 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1458 return IncompatibleBlockPointer;
1459 return ConvTy;
1460}
1461
Chris Lattner4b009652007-07-25 00:24:17 +00001462/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1463/// has code to accommodate several GCC extensions when type checking
1464/// pointers. Here are some objectionable examples that GCC considers warnings:
1465///
1466/// int a, *pint;
1467/// short *pshort;
1468/// struct foo *pfoo;
1469///
1470/// pint = pshort; // warning: assignment from incompatible pointer type
1471/// a = pint; // warning: assignment makes integer from pointer without a cast
1472/// pint = a; // warning: assignment makes pointer from integer without a cast
1473/// pint = pfoo; // warning: assignment from incompatible pointer type
1474///
1475/// As a result, the code for dealing with pointers is more complex than the
1476/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001477///
Chris Lattner005ed752008-01-04 18:04:52 +00001478Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001479Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001480 // Get canonical types. We're not formatting these types, just comparing
1481 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001482 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1483 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001484
1485 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001486 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001487
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001488 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001489 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001490 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001491 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001492 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001493
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001494 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1495 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001496 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001497 // Relax integer conversions like we do for pointers below.
1498 if (rhsType->isIntegerType())
1499 return IntToPointer;
1500 if (lhsType->isIntegerType())
1501 return PointerToInt;
Chris Lattner1853da22008-01-04 23:18:45 +00001502 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001503 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001504
Nate Begemanc5f0f652008-07-14 18:02:46 +00001505 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001506 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001507 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1508 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001509 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001510
Nate Begemanc5f0f652008-07-14 18:02:46 +00001511 // If we are allowing lax vector conversions, and LHS and RHS are both
1512 // vectors, the total size only needs to be the same. This is a bitcast;
1513 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001514 if (getLangOptions().LaxVectorConversions &&
1515 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001516 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1517 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001518 }
1519 return Incompatible;
1520 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001521
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001522 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001523 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001524
Chris Lattner390564e2008-04-07 06:49:41 +00001525 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001526 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001527 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001528
Chris Lattner390564e2008-04-07 06:49:41 +00001529 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001530 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001531
1532 if (const BlockPointerType *BPT = rhsType->getAsBlockPointerType())
1533 if (BPT->getPointeeType()->isVoidType())
1534 return BlockVoidPointer;
1535
1536 return Incompatible;
1537 }
1538
1539 if (isa<BlockPointerType>(lhsType)) {
1540 if (rhsType->isIntegerType())
1541 return IntToPointer;
1542
1543 if (rhsType->isBlockPointerType())
1544 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1545
1546 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1547 if (RHSPT->getPointeeType()->isVoidType())
1548 return BlockVoidPointer;
1549 }
Chris Lattner1853da22008-01-04 23:18:45 +00001550 return Incompatible;
1551 }
1552
Chris Lattner390564e2008-04-07 06:49:41 +00001553 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001554 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001555 if (lhsType == Context.BoolTy)
1556 return Compatible;
1557
1558 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001559 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001560
Chris Lattner390564e2008-04-07 06:49:41 +00001561 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001562 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001563
1564 if (isa<BlockPointerType>(lhsType) &&
1565 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1566 return BlockVoidPointer;
Chris Lattner1853da22008-01-04 23:18:45 +00001567 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001568 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001569
Chris Lattner1853da22008-01-04 23:18:45 +00001570 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001571 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001572 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001573 }
1574 return Incompatible;
1575}
1576
Chris Lattner005ed752008-01-04 18:04:52 +00001577Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001578Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001579 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1580 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00001581 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1582 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001583 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001584 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001585 return Compatible;
1586 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001587
1588 // We don't allow conversion of non-null-pointer constants to integers.
1589 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1590 return IntToBlockPointer;
1591
Chris Lattner5f505bf2007-10-16 02:55:40 +00001592 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001593 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001594 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001595 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001596 //
1597 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1598 // are better understood.
1599 if (!lhsType->isReferenceType())
1600 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001601
Chris Lattner005ed752008-01-04 18:04:52 +00001602 Sema::AssignConvertType result =
1603 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001604
1605 // C99 6.5.16.1p2: The value of the right operand is converted to the
1606 // type of the assignment expression.
1607 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001608 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001609 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001610}
1611
Chris Lattner005ed752008-01-04 18:04:52 +00001612Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001613Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1614 return CheckAssignmentConstraints(lhsType, rhsType);
1615}
1616
Chris Lattner2c8bff72007-12-12 05:47:28 +00001617QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001618 Diag(loc, diag::err_typecheck_invalid_operands,
1619 lex->getType().getAsString(), rex->getType().getAsString(),
1620 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001621 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001622}
1623
1624inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1625 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001626 // For conversion purposes, we ignore any qualifiers.
1627 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001628 QualType lhsType =
1629 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1630 QualType rhsType =
1631 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001632
Nate Begemanc5f0f652008-07-14 18:02:46 +00001633 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001634 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001635 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001636
Nate Begemanc5f0f652008-07-14 18:02:46 +00001637 // Handle the case of a vector & extvector type of the same size and element
1638 // type. It would be nice if we only had one vector type someday.
1639 if (getLangOptions().LaxVectorConversions)
1640 if (const VectorType *LV = lhsType->getAsVectorType())
1641 if (const VectorType *RV = rhsType->getAsVectorType())
1642 if (LV->getElementType() == RV->getElementType() &&
1643 LV->getNumElements() == RV->getNumElements())
1644 return lhsType->isExtVectorType() ? lhsType : rhsType;
1645
1646 // If the lhs is an extended vector and the rhs is a scalar of the same type
1647 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001648 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001649 QualType eltType = V->getElementType();
1650
1651 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1652 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1653 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001654 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001655 return lhsType;
1656 }
1657 }
1658
Nate Begemanc5f0f652008-07-14 18:02:46 +00001659 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001660 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001661 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001662 QualType eltType = V->getElementType();
1663
1664 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1665 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1666 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001667 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001668 return rhsType;
1669 }
1670 }
1671
Chris Lattner4b009652007-07-25 00:24:17 +00001672 // You cannot convert between vector values of different size.
1673 Diag(loc, diag::err_typecheck_vector_not_convertable,
1674 lex->getType().getAsString(), rex->getType().getAsString(),
1675 lex->getSourceRange(), rex->getSourceRange());
1676 return QualType();
1677}
1678
1679inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001680 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001681{
1682 QualType lhsType = lex->getType(), rhsType = rex->getType();
1683
1684 if (lhsType->isVectorType() || rhsType->isVectorType())
1685 return CheckVectorOperands(loc, lex, rex);
1686
Steve Naroff8f708362007-08-24 19:07:16 +00001687 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001688
Chris Lattner4b009652007-07-25 00:24:17 +00001689 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001690 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001691 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001692}
1693
1694inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001695 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001696{
1697 QualType lhsType = lex->getType(), rhsType = rex->getType();
1698
Steve Naroff8f708362007-08-24 19:07:16 +00001699 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001700
Chris Lattner4b009652007-07-25 00:24:17 +00001701 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001702 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001703 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001704}
1705
1706inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001707 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001708{
1709 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1710 return CheckVectorOperands(loc, lex, rex);
1711
Steve Naroff8f708362007-08-24 19:07:16 +00001712 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001713
Chris Lattner4b009652007-07-25 00:24:17 +00001714 // handle the common case first (both operands are arithmetic).
1715 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001716 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001717
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001718 // Put any potential pointer into PExp
1719 Expr* PExp = lex, *IExp = rex;
1720 if (IExp->getType()->isPointerType())
1721 std::swap(PExp, IExp);
1722
1723 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1724 if (IExp->getType()->isIntegerType()) {
1725 // Check for arithmetic on pointers to incomplete types
1726 if (!PTy->getPointeeType()->isObjectType()) {
1727 if (PTy->getPointeeType()->isVoidType()) {
1728 Diag(loc, diag::ext_gnu_void_ptr,
1729 lex->getSourceRange(), rex->getSourceRange());
1730 } else {
1731 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1732 lex->getType().getAsString(), lex->getSourceRange());
1733 return QualType();
1734 }
1735 }
1736 return PExp->getType();
1737 }
1738 }
1739
Chris Lattner2c8bff72007-12-12 05:47:28 +00001740 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001741}
1742
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001743// C99 6.5.6
1744QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1745 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001746 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1747 return CheckVectorOperands(loc, lex, rex);
1748
Steve Naroff8f708362007-08-24 19:07:16 +00001749 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001750
Chris Lattnerf6da2912007-12-09 21:53:25 +00001751 // Enforce type constraints: C99 6.5.6p3.
1752
1753 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001754 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001755 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001756
1757 // Either ptr - int or ptr - ptr.
1758 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001759 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001760
Chris Lattnerf6da2912007-12-09 21:53:25 +00001761 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001762 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001763 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001764 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001765 Diag(loc, diag::ext_gnu_void_ptr,
1766 lex->getSourceRange(), rex->getSourceRange());
1767 } else {
1768 Diag(loc, diag::err_typecheck_sub_ptr_object,
1769 lex->getType().getAsString(), lex->getSourceRange());
1770 return QualType();
1771 }
1772 }
1773
1774 // The result type of a pointer-int computation is the pointer type.
1775 if (rex->getType()->isIntegerType())
1776 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001777
Chris Lattnerf6da2912007-12-09 21:53:25 +00001778 // Handle pointer-pointer subtractions.
1779 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001780 QualType rpointee = RHSPTy->getPointeeType();
1781
Chris Lattnerf6da2912007-12-09 21:53:25 +00001782 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001783 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001784 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001785 if (rpointee->isVoidType()) {
1786 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001787 Diag(loc, diag::ext_gnu_void_ptr,
1788 lex->getSourceRange(), rex->getSourceRange());
1789 } else {
1790 Diag(loc, diag::err_typecheck_sub_ptr_object,
1791 rex->getType().getAsString(), rex->getSourceRange());
1792 return QualType();
1793 }
1794 }
1795
1796 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00001797 if (!Context.typesAreCompatible(
1798 Context.getCanonicalType(lpointee).getUnqualifiedType(),
1799 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001800 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1801 lex->getType().getAsString(), rex->getType().getAsString(),
1802 lex->getSourceRange(), rex->getSourceRange());
1803 return QualType();
1804 }
1805
1806 return Context.getPointerDiffType();
1807 }
1808 }
1809
Chris Lattner2c8bff72007-12-12 05:47:28 +00001810 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001811}
1812
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001813// C99 6.5.7
1814QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1815 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00001816 // C99 6.5.7p2: Each of the operands shall have integer type.
1817 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1818 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001819
Chris Lattner2c8bff72007-12-12 05:47:28 +00001820 // Shifts don't perform usual arithmetic conversions, they just do integer
1821 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001822 if (!isCompAssign)
1823 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001824 UsualUnaryConversions(rex);
1825
1826 // "The type of the result is that of the promoted left operand."
1827 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001828}
1829
Eli Friedman0d9549b2008-08-22 00:56:42 +00001830static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
1831 ASTContext& Context) {
1832 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
1833 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
1834 // ID acts sort of like void* for ObjC interfaces
1835 if (LHSIface && Context.isObjCIdType(RHS))
1836 return true;
1837 if (RHSIface && Context.isObjCIdType(LHS))
1838 return true;
1839 if (!LHSIface || !RHSIface)
1840 return false;
1841 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
1842 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
1843}
1844
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001845// C99 6.5.8
1846QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1847 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001848 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1849 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1850
Chris Lattner254f3bc2007-08-26 01:18:55 +00001851 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001852 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1853 UsualArithmeticConversions(lex, rex);
1854 else {
1855 UsualUnaryConversions(lex);
1856 UsualUnaryConversions(rex);
1857 }
Chris Lattner4b009652007-07-25 00:24:17 +00001858 QualType lType = lex->getType();
1859 QualType rType = rex->getType();
1860
Ted Kremenek486509e2007-10-29 17:13:39 +00001861 // For non-floating point types, check for self-comparisons of the form
1862 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1863 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001864 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001865 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1866 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001867 if (DRL->getDecl() == DRR->getDecl())
1868 Diag(loc, diag::warn_selfcomparison);
1869 }
1870
Chris Lattner254f3bc2007-08-26 01:18:55 +00001871 if (isRelational) {
1872 if (lType->isRealType() && rType->isRealType())
1873 return Context.IntTy;
1874 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001875 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001876 if (lType->isFloatingType()) {
1877 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001878 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001879 }
1880
Chris Lattner254f3bc2007-08-26 01:18:55 +00001881 if (lType->isArithmeticType() && rType->isArithmeticType())
1882 return Context.IntTy;
1883 }
Chris Lattner4b009652007-07-25 00:24:17 +00001884
Chris Lattner22be8422007-08-26 01:10:14 +00001885 bool LHSIsNull = lex->isNullPointerConstant(Context);
1886 bool RHSIsNull = rex->isNullPointerConstant(Context);
1887
Chris Lattner254f3bc2007-08-26 01:18:55 +00001888 // All of the following pointer related warnings are GCC extensions, except
1889 // when handling null pointer constants. One day, we can consider making them
1890 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001891 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001892 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001893 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00001894 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001895 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00001896
Steve Naroff3b435622007-11-13 14:57:38 +00001897 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001898 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1899 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00001900 RCanPointeeTy.getUnqualifiedType()) &&
1901 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001902 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1903 lType.getAsString(), rType.getAsString(),
1904 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001905 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001906 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001907 return Context.IntTy;
1908 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001909 // Handle block pointer types.
1910 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
1911 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
1912 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
1913
1914 if (!LHSIsNull && !RHSIsNull &&
1915 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
1916 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
1917 lType.getAsString(), rType.getAsString(),
1918 lex->getSourceRange(), rex->getSourceRange());
1919 }
1920 ImpCastExprToType(rex, lType); // promote the pointer to pointer
1921 return Context.IntTy;
1922 }
1923
Steve Naroff936c4362008-06-03 14:04:54 +00001924 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
1925 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
1926 ImpCastExprToType(rex, lType);
1927 return Context.IntTy;
1928 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001929 }
Steve Naroff936c4362008-06-03 14:04:54 +00001930 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
1931 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001932 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001933 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1934 lType.getAsString(), rType.getAsString(),
1935 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001936 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001937 return Context.IntTy;
1938 }
Steve Naroff936c4362008-06-03 14:04:54 +00001939 if (lType->isIntegerType() &&
1940 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00001941 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001942 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1943 lType.getAsString(), rType.getAsString(),
1944 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001945 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001946 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001947 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00001948 // Handle block pointers.
1949 if (lType->isBlockPointerType() && rType->isIntegerType()) {
1950 if (!RHSIsNull)
1951 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1952 lType.getAsString(), rType.getAsString(),
1953 lex->getSourceRange(), rex->getSourceRange());
1954 ImpCastExprToType(rex, lType); // promote the integer to pointer
1955 return Context.IntTy;
1956 }
1957 if (lType->isIntegerType() && rType->isBlockPointerType()) {
1958 if (!LHSIsNull)
1959 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1960 lType.getAsString(), rType.getAsString(),
1961 lex->getSourceRange(), rex->getSourceRange());
1962 ImpCastExprToType(lex, rType); // promote the integer to pointer
1963 return Context.IntTy;
1964 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001965 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001966}
1967
Nate Begemanc5f0f652008-07-14 18:02:46 +00001968/// CheckVectorCompareOperands - vector comparisons are a clang extension that
1969/// operates on extended vector types. Instead of producing an IntTy result,
1970/// like a scalar comparison, a vector comparison produces a vector of integer
1971/// types.
1972QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
1973 SourceLocation loc,
1974 bool isRelational) {
1975 // Check to make sure we're operating on vectors of the same type and width,
1976 // Allowing one side to be a scalar of element type.
1977 QualType vType = CheckVectorOperands(loc, lex, rex);
1978 if (vType.isNull())
1979 return vType;
1980
1981 QualType lType = lex->getType();
1982 QualType rType = rex->getType();
1983
1984 // For non-floating point types, check for self-comparisons of the form
1985 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1986 // often indicate logic errors in the program.
1987 if (!lType->isFloatingType()) {
1988 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1989 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1990 if (DRL->getDecl() == DRR->getDecl())
1991 Diag(loc, diag::warn_selfcomparison);
1992 }
1993
1994 // Check for comparisons of floating point operands using != and ==.
1995 if (!isRelational && lType->isFloatingType()) {
1996 assert (rType->isFloatingType());
1997 CheckFloatComparison(loc,lex,rex);
1998 }
1999
2000 // Return the type for the comparison, which is the same as vector type for
2001 // integer vectors, or an integer type of identical size and number of
2002 // elements for floating point vectors.
2003 if (lType->isIntegerType())
2004 return lType;
2005
2006 const VectorType *VTy = lType->getAsVectorType();
2007
2008 // FIXME: need to deal with non-32b int / non-64b long long
2009 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2010 if (TypeSize == 32) {
2011 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2012 }
2013 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2014 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2015}
2016
Chris Lattner4b009652007-07-25 00:24:17 +00002017inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00002018 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002019{
2020 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2021 return CheckVectorOperands(loc, lex, rex);
2022
Steve Naroff8f708362007-08-24 19:07:16 +00002023 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002024
2025 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002026 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002027 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002028}
2029
2030inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
2031 Expr *&lex, Expr *&rex, SourceLocation loc)
2032{
2033 UsualUnaryConversions(lex);
2034 UsualUnaryConversions(rex);
2035
Eli Friedmanbea3f842008-05-13 20:16:47 +00002036 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002037 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002038 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002039}
2040
2041inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00002042 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00002043{
2044 QualType lhsType = lex->getType();
2045 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner25168a52008-07-26 21:30:36 +00002046 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002047
2048 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00002049 case Expr::MLV_Valid:
2050 break;
2051 case Expr::MLV_ConstQualified:
2052 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2053 return QualType();
2054 case Expr::MLV_ArrayType:
2055 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2056 lhsType.getAsString(), lex->getSourceRange());
2057 return QualType();
2058 case Expr::MLV_NotObjectType:
2059 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2060 lhsType.getAsString(), lex->getSourceRange());
2061 return QualType();
2062 case Expr::MLV_InvalidExpression:
2063 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2064 lex->getSourceRange());
2065 return QualType();
2066 case Expr::MLV_IncompleteType:
2067 case Expr::MLV_IncompleteVoidType:
2068 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2069 lhsType.getAsString(), lex->getSourceRange());
2070 return QualType();
2071 case Expr::MLV_DuplicateVectorComponents:
2072 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2073 lex->getSourceRange());
2074 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002075 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002076
Chris Lattner005ed752008-01-04 18:04:52 +00002077 AssignConvertType ConvTy;
Chris Lattner34c85082008-08-21 18:04:13 +00002078 if (compoundType.isNull()) {
2079 // Simple assignment "x = y".
Chris Lattner005ed752008-01-04 18:04:52 +00002080 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner34c85082008-08-21 18:04:13 +00002081
2082 // If the RHS is a unary plus or minus, check to see if they = and + are
2083 // right next to each other. If so, the user may have typo'd "x =+ 4"
2084 // instead of "x += 4".
2085 Expr *RHSCheck = rex;
2086 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2087 RHSCheck = ICE->getSubExpr();
2088 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2089 if ((UO->getOpcode() == UnaryOperator::Plus ||
2090 UO->getOpcode() == UnaryOperator::Minus) &&
2091 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2092 // Only if the two operators are exactly adjacent.
2093 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2094 Diag(loc, diag::warn_not_compound_assign,
2095 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2096 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2097 }
2098 } else {
2099 // Compound assignment "x += y"
Chris Lattner005ed752008-01-04 18:04:52 +00002100 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner34c85082008-08-21 18:04:13 +00002101 }
Chris Lattner005ed752008-01-04 18:04:52 +00002102
2103 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2104 rex, "assigning"))
2105 return QualType();
2106
Chris Lattner4b009652007-07-25 00:24:17 +00002107 // C99 6.5.16p3: The type of an assignment expression is the type of the
2108 // left operand unless the left operand has qualified type, in which case
2109 // it is the unqualified version of the type of the left operand.
2110 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2111 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002112 // C++ 5.17p1: the type of the assignment expression is that of its left
2113 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00002114 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002115}
2116
2117inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2118 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00002119
2120 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2121 DefaultFunctionArrayConversion(rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002122 return rex->getType();
2123}
2124
2125/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2126/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2127QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2128 QualType resType = op->getType();
2129 assert(!resType.isNull() && "no type for increment/decrement expression");
2130
Steve Naroffd30e1932007-08-24 17:20:07 +00002131 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00002132 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002133 if (pt->getPointeeType()->isVoidType()) {
2134 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2135 } else if (!pt->getPointeeType()->isObjectType()) {
2136 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00002137 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2138 resType.getAsString(), op->getSourceRange());
2139 return QualType();
2140 }
Steve Naroffd30e1932007-08-24 17:20:07 +00002141 } else if (!resType->isRealType()) {
2142 if (resType->isComplexType())
2143 // C99 does not support ++/-- on complex types.
2144 Diag(OpLoc, diag::ext_integer_increment_complex,
2145 resType.getAsString(), op->getSourceRange());
2146 else {
2147 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2148 resType.getAsString(), op->getSourceRange());
2149 return QualType();
2150 }
Chris Lattner4b009652007-07-25 00:24:17 +00002151 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002152 // At this point, we know we have a real, complex or pointer type.
2153 // Now make sure the operand is a modifiable lvalue.
Chris Lattner25168a52008-07-26 21:30:36 +00002154 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002155 if (mlval != Expr::MLV_Valid) {
2156 // FIXME: emit a more precise diagnostic...
2157 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2158 op->getSourceRange());
2159 return QualType();
2160 }
2161 return resType;
2162}
2163
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002164/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002165/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002166/// where the declaration is needed for type checking. We only need to
2167/// handle cases when the expression references a function designator
2168/// or is an lvalue. Here are some examples:
2169/// - &(x) => x
2170/// - &*****f => f for f a function designator.
2171/// - &s.xx => s
2172/// - &s.zz[1].yy -> s, if zz is an array
2173/// - *(x + 1) -> x, if x is an array
2174/// - &"123"[2] -> 0
2175/// - & __real__ x -> x
Chris Lattner48d7f382008-04-02 04:24:33 +00002176static ValueDecl *getPrimaryDecl(Expr *E) {
2177 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002178 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002179 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002180 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002181 // Fields cannot be declared with a 'register' storage class.
2182 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002183 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002184 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002185 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002186 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002187 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002188
Chris Lattner48d7f382008-04-02 04:24:33 +00002189 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00002190 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002191 return 0;
2192 else
2193 return VD;
2194 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002195 case Stmt::UnaryOperatorClass: {
2196 UnaryOperator *UO = cast<UnaryOperator>(E);
2197
2198 switch(UO->getOpcode()) {
2199 case UnaryOperator::Deref: {
2200 // *(X + 1) refers to X if X is not a pointer.
2201 ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2202 if (!VD || VD->getType()->isPointerType())
2203 return 0;
2204 return VD;
2205 }
2206 case UnaryOperator::Real:
2207 case UnaryOperator::Imag:
2208 case UnaryOperator::Extension:
2209 return getPrimaryDecl(UO->getSubExpr());
2210 default:
2211 return 0;
2212 }
2213 }
2214 case Stmt::BinaryOperatorClass: {
2215 BinaryOperator *BO = cast<BinaryOperator>(E);
2216
2217 // Handle cases involving pointer arithmetic. The result of an
2218 // Assign or AddAssign is not an lvalue so they can be ignored.
2219
2220 // (x + n) or (n + x) => x
2221 if (BO->getOpcode() == BinaryOperator::Add) {
2222 if (BO->getLHS()->getType()->isPointerType()) {
2223 return getPrimaryDecl(BO->getLHS());
2224 } else if (BO->getRHS()->getType()->isPointerType()) {
2225 return getPrimaryDecl(BO->getRHS());
2226 }
2227 }
2228
2229 return 0;
2230 }
Chris Lattner4b009652007-07-25 00:24:17 +00002231 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002232 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002233 case Stmt::ImplicitCastExprClass:
2234 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002235 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002236 default:
2237 return 0;
2238 }
2239}
2240
2241/// CheckAddressOfOperand - The operand of & must be either a function
2242/// designator or an lvalue designating an object. If it is an lvalue, the
2243/// object cannot be declared with storage class register or be a bit field.
2244/// Note: The usual conversions are *not* applied to the operand of the &
2245/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2246QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002247 if (getLangOptions().C99) {
2248 // Implement C99-only parts of addressof rules.
2249 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2250 if (uOp->getOpcode() == UnaryOperator::Deref)
2251 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2252 // (assuming the deref expression is valid).
2253 return uOp->getSubExpr()->getType();
2254 }
2255 // Technically, there should be a check for array subscript
2256 // expressions here, but the result of one is always an lvalue anyway.
2257 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002258 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002259 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002260
2261 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002262 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2263 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002264 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2265 op->getSourceRange());
2266 return QualType();
2267 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002268 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2269 if (MemExpr->getMemberDecl()->isBitField()) {
2270 Diag(OpLoc, diag::err_typecheck_address_of,
2271 std::string("bit-field"), op->getSourceRange());
2272 return QualType();
2273 }
2274 // Check for Apple extension for accessing vector components.
2275 } else if (isa<ArraySubscriptExpr>(op) &&
2276 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2277 Diag(OpLoc, diag::err_typecheck_address_of,
2278 std::string("vector"), op->getSourceRange());
2279 return QualType();
2280 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002281 // We have an lvalue with a decl. Make sure the decl is not declared
2282 // with the register storage-class specifier.
2283 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2284 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002285 Diag(OpLoc, diag::err_typecheck_address_of,
2286 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002287 return QualType();
2288 }
2289 } else
2290 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002291 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002292
Chris Lattner4b009652007-07-25 00:24:17 +00002293 // If the operand has type "type", the result has type "pointer to type".
2294 return Context.getPointerType(op->getType());
2295}
2296
2297QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2298 UsualUnaryConversions(op);
2299 QualType qType = op->getType();
2300
Chris Lattner7931f4a2007-07-31 16:53:04 +00002301 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002302 // Note that per both C89 and C99, this is always legal, even
2303 // if ptype is an incomplete type or void.
2304 // It would be possible to warn about dereferencing a
2305 // void pointer, but it's completely well-defined,
2306 // and such a warning is unlikely to catch any mistakes.
2307 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002308 }
2309 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2310 qType.getAsString(), op->getSourceRange());
2311 return QualType();
2312}
2313
2314static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2315 tok::TokenKind Kind) {
2316 BinaryOperator::Opcode Opc;
2317 switch (Kind) {
2318 default: assert(0 && "Unknown binop!");
2319 case tok::star: Opc = BinaryOperator::Mul; break;
2320 case tok::slash: Opc = BinaryOperator::Div; break;
2321 case tok::percent: Opc = BinaryOperator::Rem; break;
2322 case tok::plus: Opc = BinaryOperator::Add; break;
2323 case tok::minus: Opc = BinaryOperator::Sub; break;
2324 case tok::lessless: Opc = BinaryOperator::Shl; break;
2325 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2326 case tok::lessequal: Opc = BinaryOperator::LE; break;
2327 case tok::less: Opc = BinaryOperator::LT; break;
2328 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2329 case tok::greater: Opc = BinaryOperator::GT; break;
2330 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2331 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2332 case tok::amp: Opc = BinaryOperator::And; break;
2333 case tok::caret: Opc = BinaryOperator::Xor; break;
2334 case tok::pipe: Opc = BinaryOperator::Or; break;
2335 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2336 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2337 case tok::equal: Opc = BinaryOperator::Assign; break;
2338 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2339 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2340 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2341 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2342 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2343 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2344 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2345 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2346 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2347 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2348 case tok::comma: Opc = BinaryOperator::Comma; break;
2349 }
2350 return Opc;
2351}
2352
2353static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2354 tok::TokenKind Kind) {
2355 UnaryOperator::Opcode Opc;
2356 switch (Kind) {
2357 default: assert(0 && "Unknown unary op!");
2358 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2359 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2360 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2361 case tok::star: Opc = UnaryOperator::Deref; break;
2362 case tok::plus: Opc = UnaryOperator::Plus; break;
2363 case tok::minus: Opc = UnaryOperator::Minus; break;
2364 case tok::tilde: Opc = UnaryOperator::Not; break;
2365 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2366 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2367 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2368 case tok::kw___real: Opc = UnaryOperator::Real; break;
2369 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2370 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2371 }
2372 return Opc;
2373}
2374
2375// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002376Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002377 ExprTy *LHS, ExprTy *RHS) {
2378 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2379 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2380
Steve Naroff87d58b42007-09-16 03:34:24 +00002381 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2382 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002383
2384 QualType ResultTy; // Result type of the binary operator.
2385 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2386
2387 switch (Opc) {
2388 default:
2389 assert(0 && "Unknown binary expr!");
2390 case BinaryOperator::Assign:
2391 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2392 break;
2393 case BinaryOperator::Mul:
2394 case BinaryOperator::Div:
2395 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2396 break;
2397 case BinaryOperator::Rem:
2398 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2399 break;
2400 case BinaryOperator::Add:
2401 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2402 break;
2403 case BinaryOperator::Sub:
2404 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2405 break;
2406 case BinaryOperator::Shl:
2407 case BinaryOperator::Shr:
2408 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2409 break;
2410 case BinaryOperator::LE:
2411 case BinaryOperator::LT:
2412 case BinaryOperator::GE:
2413 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002414 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002415 break;
2416 case BinaryOperator::EQ:
2417 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002418 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00002419 break;
2420 case BinaryOperator::And:
2421 case BinaryOperator::Xor:
2422 case BinaryOperator::Or:
2423 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2424 break;
2425 case BinaryOperator::LAnd:
2426 case BinaryOperator::LOr:
2427 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2428 break;
2429 case BinaryOperator::MulAssign:
2430 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002431 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002432 if (!CompTy.isNull())
2433 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2434 break;
2435 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002436 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002437 if (!CompTy.isNull())
2438 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2439 break;
2440 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002441 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002442 if (!CompTy.isNull())
2443 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2444 break;
2445 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002446 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002447 if (!CompTy.isNull())
2448 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2449 break;
2450 case BinaryOperator::ShlAssign:
2451 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002452 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002453 if (!CompTy.isNull())
2454 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2455 break;
2456 case BinaryOperator::AndAssign:
2457 case BinaryOperator::XorAssign:
2458 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002459 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002460 if (!CompTy.isNull())
2461 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2462 break;
2463 case BinaryOperator::Comma:
2464 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2465 break;
2466 }
2467 if (ResultTy.isNull())
2468 return true;
2469 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00002470 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002471 else
Chris Lattnerf420df12007-08-28 18:36:55 +00002472 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002473}
2474
2475// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002476Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002477 ExprTy *input) {
2478 Expr *Input = (Expr*)input;
2479 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2480 QualType resultType;
2481 switch (Opc) {
2482 default:
2483 assert(0 && "Unimplemented unary expr!");
2484 case UnaryOperator::PreInc:
2485 case UnaryOperator::PreDec:
2486 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2487 break;
2488 case UnaryOperator::AddrOf:
2489 resultType = CheckAddressOfOperand(Input, OpLoc);
2490 break;
2491 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002492 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002493 resultType = CheckIndirectionOperand(Input, OpLoc);
2494 break;
2495 case UnaryOperator::Plus:
2496 case UnaryOperator::Minus:
2497 UsualUnaryConversions(Input);
2498 resultType = Input->getType();
2499 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2500 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2501 resultType.getAsString());
2502 break;
2503 case UnaryOperator::Not: // bitwise complement
2504 UsualUnaryConversions(Input);
2505 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002506 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2507 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2508 // C99 does not support '~' for complex conjugation.
2509 Diag(OpLoc, diag::ext_integer_complement_complex,
2510 resultType.getAsString(), Input->getSourceRange());
2511 else if (!resultType->isIntegerType())
2512 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2513 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002514 break;
2515 case UnaryOperator::LNot: // logical negation
2516 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2517 DefaultFunctionArrayConversion(Input);
2518 resultType = Input->getType();
2519 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2520 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2521 resultType.getAsString());
2522 // LNot always has type int. C99 6.5.3.3p5.
2523 resultType = Context.IntTy;
2524 break;
2525 case UnaryOperator::SizeOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002526 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2527 Input->getSourceRange(), true);
Chris Lattner4b009652007-07-25 00:24:17 +00002528 break;
2529 case UnaryOperator::AlignOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002530 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2531 Input->getSourceRange(), false);
Chris Lattner4b009652007-07-25 00:24:17 +00002532 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002533 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002534 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002535 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002536 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002537 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002538 resultType = Input->getType();
2539 break;
2540 }
2541 if (resultType.isNull())
2542 return true;
2543 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2544}
2545
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002546/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2547Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002548 SourceLocation LabLoc,
2549 IdentifierInfo *LabelII) {
2550 // Look up the record for this label identifier.
2551 LabelStmt *&LabelDecl = LabelMap[LabelII];
2552
Daniel Dunbar879788d2008-08-04 16:51:22 +00002553 // If we haven't seen this label yet, create a forward reference. It
2554 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00002555 if (LabelDecl == 0)
2556 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2557
2558 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002559 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2560 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002561}
2562
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002563Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002564 SourceLocation RPLoc) { // "({..})"
2565 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2566 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2567 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2568
2569 // FIXME: there are a variety of strange constraints to enforce here, for
2570 // example, it is not possible to goto into a stmt expression apparently.
2571 // More semantic analysis is needed.
2572
2573 // FIXME: the last statement in the compount stmt has its value used. We
2574 // should not warn about it being unused.
2575
2576 // If there are sub stmts in the compound stmt, take the type of the last one
2577 // as the type of the stmtexpr.
2578 QualType Ty = Context.VoidTy;
2579
Chris Lattner200964f2008-07-26 19:51:01 +00002580 if (!Compound->body_empty()) {
2581 Stmt *LastStmt = Compound->body_back();
2582 // If LastStmt is a label, skip down through into the body.
2583 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2584 LastStmt = Label->getSubStmt();
2585
2586 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00002587 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00002588 }
Chris Lattner4b009652007-07-25 00:24:17 +00002589
2590 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2591}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002592
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002593Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002594 SourceLocation TypeLoc,
2595 TypeTy *argty,
2596 OffsetOfComponent *CompPtr,
2597 unsigned NumComponents,
2598 SourceLocation RPLoc) {
2599 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2600 assert(!ArgTy.isNull() && "Missing type argument!");
2601
2602 // We must have at least one component that refers to the type, and the first
2603 // one is known to be a field designator. Verify that the ArgTy represents
2604 // a struct/union/class.
2605 if (!ArgTy->isRecordType())
2606 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2607
2608 // Otherwise, create a compound literal expression as the base, and
2609 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002610 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002611
Chris Lattnerb37522e2007-08-31 21:49:13 +00002612 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2613 // GCC extension, diagnose them.
2614 if (NumComponents != 1)
2615 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2616 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2617
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002618 for (unsigned i = 0; i != NumComponents; ++i) {
2619 const OffsetOfComponent &OC = CompPtr[i];
2620 if (OC.isBrackets) {
2621 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00002622 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002623 if (!AT) {
2624 delete Res;
2625 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2626 Res->getType().getAsString());
2627 }
2628
Chris Lattner2af6a802007-08-30 17:59:59 +00002629 // FIXME: C++: Verify that operator[] isn't overloaded.
2630
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002631 // C99 6.5.2.1p1
2632 Expr *Idx = static_cast<Expr*>(OC.U.E);
2633 if (!Idx->getType()->isIntegerType())
2634 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2635 Idx->getSourceRange());
2636
2637 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2638 continue;
2639 }
2640
2641 const RecordType *RC = Res->getType()->getAsRecordType();
2642 if (!RC) {
2643 delete Res;
2644 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2645 Res->getType().getAsString());
2646 }
2647
2648 // Get the decl corresponding to this.
2649 RecordDecl *RD = RC->getDecl();
2650 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2651 if (!MemberDecl)
2652 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2653 OC.U.IdentInfo->getName(),
2654 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002655
2656 // FIXME: C++: Verify that MemberDecl isn't a static field.
2657 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002658 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2659 // matter here.
2660 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002661 }
2662
2663 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2664 BuiltinLoc);
2665}
2666
2667
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002668Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002669 TypeTy *arg1, TypeTy *arg2,
2670 SourceLocation RPLoc) {
2671 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2672 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2673
2674 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2675
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002676 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002677}
2678
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002679Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002680 ExprTy *expr1, ExprTy *expr2,
2681 SourceLocation RPLoc) {
2682 Expr *CondExpr = static_cast<Expr*>(cond);
2683 Expr *LHSExpr = static_cast<Expr*>(expr1);
2684 Expr *RHSExpr = static_cast<Expr*>(expr2);
2685
2686 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2687
2688 // The conditional expression is required to be a constant expression.
2689 llvm::APSInt condEval(32);
2690 SourceLocation ExpLoc;
2691 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2692 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2693 CondExpr->getSourceRange());
2694
2695 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2696 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2697 RHSExpr->getType();
2698 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2699}
2700
Steve Naroff52a81c02008-09-03 18:15:37 +00002701//===----------------------------------------------------------------------===//
2702// Clang Extensions.
2703//===----------------------------------------------------------------------===//
2704
2705/// ActOnBlockStart - This callback is invoked when a block literal is started.
2706void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope,
2707 Declarator &ParamInfo) {
2708 // Analyze block parameters.
2709 BlockSemaInfo *BSI = new BlockSemaInfo();
2710
2711 // Add BSI to CurBlock.
2712 BSI->PrevBlockInfo = CurBlock;
2713 CurBlock = BSI;
2714
2715 BSI->ReturnType = 0;
2716 BSI->TheScope = BlockScope;
2717
2718 // Analyze arguments to block.
2719 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2720 "Not a function declarator!");
2721 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2722
2723 BSI->hasPrototype = FTI.hasPrototype;
2724 BSI->isVariadic = true;
2725
2726 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2727 // no arguments, not a function that takes a single void argument.
2728 if (FTI.hasPrototype &&
2729 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2730 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2731 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2732 // empty arg list, don't push any params.
2733 BSI->isVariadic = false;
2734 } else if (FTI.hasPrototype) {
2735 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
2736 BSI->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2737 BSI->isVariadic = FTI.isVariadic;
2738 }
2739}
2740
2741/// ActOnBlockError - If there is an error parsing a block, this callback
2742/// is invoked to pop the information about the block from the action impl.
2743void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
2744 // Ensure that CurBlock is deleted.
2745 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
2746
2747 // Pop off CurBlock, handle nested blocks.
2748 CurBlock = CurBlock->PrevBlockInfo;
2749
2750 // FIXME: Delete the ParmVarDecl objects as well???
2751
2752}
2753
2754/// ActOnBlockStmtExpr - This is called when the body of a block statement
2755/// literal was successfully completed. ^(int x){...}
2756Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
2757 Scope *CurScope) {
2758 // Ensure that CurBlock is deleted.
2759 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2760 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
2761
2762 // Pop off CurBlock, handle nested blocks.
2763 CurBlock = CurBlock->PrevBlockInfo;
2764
2765 QualType RetTy = Context.VoidTy;
2766 if (BSI->ReturnType)
2767 RetTy = QualType(BSI->ReturnType, 0);
2768
2769 llvm::SmallVector<QualType, 8> ArgTypes;
2770 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
2771 ArgTypes.push_back(BSI->Params[i]->getType());
2772
2773 QualType BlockTy;
2774 if (!BSI->hasPrototype)
2775 BlockTy = Context.getFunctionTypeNoProto(RetTy);
2776 else
2777 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
2778 BSI->isVariadic);
2779
2780 BlockTy = Context.getBlockPointerType(BlockTy);
2781 return new BlockStmtExpr(CaretLoc, BlockTy,
2782 &BSI->Params[0], BSI->Params.size(), Body.take());
2783}
2784
2785/// ActOnBlockExprExpr - This is called when the body of a block
2786/// expression literal was successfully completed. ^(int x)[foo bar: x]
2787Sema::ExprResult Sema::ActOnBlockExprExpr(SourceLocation CaretLoc, ExprTy *body,
2788 Scope *CurScope) {
2789 // Ensure that CurBlock is deleted.
2790 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2791 llvm::OwningPtr<Expr> Body(static_cast<Expr*>(body));
2792
2793 // Pop off CurBlock, handle nested blocks.
2794 CurBlock = CurBlock->PrevBlockInfo;
2795
2796 if (BSI->ReturnType) {
2797 Diag(CaretLoc, diag::err_return_in_block_expression);
2798 return true;
2799 }
2800
2801 QualType RetTy = Body->getType();
2802
2803 llvm::SmallVector<QualType, 8> ArgTypes;
2804 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
2805 ArgTypes.push_back(BSI->Params[i]->getType());
2806
2807 QualType BlockTy;
2808 if (!BSI->hasPrototype)
2809 BlockTy = Context.getFunctionTypeNoProto(RetTy);
2810 else
2811 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
2812 BSI->isVariadic);
2813
2814 BlockTy = Context.getBlockPointerType(BlockTy);
2815 return new BlockExprExpr(CaretLoc, BlockTy,
2816 &BSI->Params[0], BSI->Params.size(), Body.take());
2817}
2818
Nate Begemanbd881ef2008-01-30 20:50:20 +00002819/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002820/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002821/// The number of arguments has already been validated to match the number of
2822/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002823static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2824 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002825 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00002826 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002827 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2828 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00002829
2830 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002831 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00002832 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002833 return true;
2834}
2835
2836Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2837 SourceLocation *CommaLocs,
2838 SourceLocation BuiltinLoc,
2839 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002840 // __builtin_overload requires at least 2 arguments
2841 if (NumArgs < 2)
2842 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2843 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002844
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002845 // The first argument is required to be a constant expression. It tells us
2846 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002847 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002848 Expr *NParamsExpr = Args[0];
2849 llvm::APSInt constEval(32);
2850 SourceLocation ExpLoc;
2851 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2852 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2853 NParamsExpr->getSourceRange());
2854
2855 // Verify that the number of parameters is > 0
2856 unsigned NumParams = constEval.getZExtValue();
2857 if (NumParams == 0)
2858 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2859 NParamsExpr->getSourceRange());
2860 // Verify that we have at least 1 + NumParams arguments to the builtin.
2861 if ((NumParams + 1) > NumArgs)
2862 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2863 SourceRange(BuiltinLoc, RParenLoc));
2864
2865 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002866 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002867 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002868 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2869 // UsualUnaryConversions will convert the function DeclRefExpr into a
2870 // pointer to function.
2871 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002872 const FunctionTypeProto *FnType = 0;
2873 if (const PointerType *PT = Fn->getType()->getAsPointerType())
2874 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002875
2876 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2877 // parameters, and the number of parameters must match the value passed to
2878 // the builtin.
2879 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002880 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2881 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002882
2883 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002884 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002885 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002886 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002887 if (OE)
2888 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2889 OE->getFn()->getSourceRange());
2890 // Remember our match, and continue processing the remaining arguments
2891 // to catch any errors.
2892 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2893 BuiltinLoc, RParenLoc);
2894 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002895 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002896 // Return the newly created OverloadExpr node, if we succeded in matching
2897 // exactly one of the candidate functions.
2898 if (OE)
2899 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002900
2901 // If we didn't find a matching function Expr in the __builtin_overload list
2902 // the return an error.
2903 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002904 for (unsigned i = 0; i != NumParams; ++i) {
2905 if (i != 0) typeNames += ", ";
2906 typeNames += Args[i+1]->getType().getAsString();
2907 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002908
2909 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2910 SourceRange(BuiltinLoc, RParenLoc));
2911}
2912
Anders Carlsson36760332007-10-15 20:28:48 +00002913Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2914 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002915 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002916 Expr *E = static_cast<Expr*>(expr);
2917 QualType T = QualType::getFromOpaquePtr(type);
2918
2919 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00002920
2921 // Get the va_list type
2922 QualType VaListType = Context.getBuiltinVaListType();
2923 // Deal with implicit array decay; for example, on x86-64,
2924 // va_list is an array, but it's supposed to decay to
2925 // a pointer for va_arg.
2926 if (VaListType->isArrayType())
2927 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00002928 // Make sure the input expression also decays appropriately.
2929 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00002930
2931 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002932 return Diag(E->getLocStart(),
2933 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2934 E->getType().getAsString(),
2935 E->getSourceRange());
2936
2937 // FIXME: Warn if a non-POD type is passed in.
2938
2939 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2940}
2941
Chris Lattner005ed752008-01-04 18:04:52 +00002942bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2943 SourceLocation Loc,
2944 QualType DstType, QualType SrcType,
2945 Expr *SrcExpr, const char *Flavor) {
2946 // Decode the result (notice that AST's are still created for extensions).
2947 bool isInvalid = false;
2948 unsigned DiagKind;
2949 switch (ConvTy) {
2950 default: assert(0 && "Unknown conversion type");
2951 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002952 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002953 DiagKind = diag::ext_typecheck_convert_pointer_int;
2954 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002955 case IntToPointer:
2956 DiagKind = diag::ext_typecheck_convert_int_pointer;
2957 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002958 case IncompatiblePointer:
2959 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2960 break;
2961 case FunctionVoidPointer:
2962 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2963 break;
2964 case CompatiblePointerDiscardsQualifiers:
2965 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2966 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002967 case IntToBlockPointer:
2968 DiagKind = diag::err_int_to_block_pointer;
2969 break;
2970 case IncompatibleBlockPointer:
2971 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
2972 break;
2973 case BlockVoidPointer:
2974 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
2975 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002976 case Incompatible:
2977 DiagKind = diag::err_typecheck_convert_incompatible;
2978 isInvalid = true;
2979 break;
2980 }
2981
2982 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2983 SrcExpr->getSourceRange());
2984 return isInvalid;
2985}