blob: 571f9cc03089d6fca33345bd8fc833281d907cf4 [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"
Ted Kremenek30c66752007-11-25 00:58:00 +000015#include "SemaUtil.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000017#include "clang/AST/DeclCXX.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/AST/Expr.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000020#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000021#include "clang/AST/ExprObjC.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000022#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Lex/Preprocessor.h"
24#include "clang/Lex/LiteralSupport.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000025#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "clang/Basic/TargetInfo.h"
Chris Lattner83bd5eb2007-12-28 05:29:59 +000028#include "llvm/ADT/OwningPtr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000030#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000031using namespace clang;
32
Chris Lattner299b8842008-07-25 21:10:04 +000033//===----------------------------------------------------------------------===//
34// Standard Promotions and Conversions
35//===----------------------------------------------------------------------===//
36
Chris Lattner299b8842008-07-25 21:10:04 +000037/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
38void Sema::DefaultFunctionArrayConversion(Expr *&E) {
39 QualType Ty = E->getType();
40 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
41
42 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
43 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
44 Ty = E->getType();
45 }
46 if (Ty->isFunctionType())
47 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000048 else if (Ty->isArrayType()) {
49 // In C90 mode, arrays only promote to pointers if the array expression is
50 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
51 // type 'array of type' is converted to an expression that has type 'pointer
52 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
53 // that has type 'array of type' ...". The relevant change is "an lvalue"
54 // (C90) to "an expression" (C99).
Chris Lattner25168a52008-07-26 21:30:36 +000055 if (getLangOptions().C99 || E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000056 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
57 }
Chris Lattner299b8842008-07-25 21:10:04 +000058}
59
60/// UsualUnaryConversions - Performs various conversions that are common to most
61/// operators (C99 6.3). The conversions of array and function types are
62/// sometimes surpressed. For example, the array->pointer conversion doesn't
63/// apply if the array is an argument to the sizeof or address (&) operators.
64/// In these instances, this routine should *not* be called.
65Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
66 QualType Ty = Expr->getType();
67 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
68
69 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
70 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
71 Ty = Expr->getType();
72 }
73 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
74 ImpCastExprToType(Expr, Context.IntTy);
75 else
76 DefaultFunctionArrayConversion(Expr);
77
78 return Expr;
79}
80
Chris Lattner9305c3d2008-07-25 22:25:12 +000081/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
82/// do not have a prototype. Arguments that have type float are promoted to
83/// double. All other argument types are converted by UsualUnaryConversions().
84void Sema::DefaultArgumentPromotion(Expr *&Expr) {
85 QualType Ty = Expr->getType();
86 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
87
88 // If this is a 'float' (CVR qualified or typedef) promote to double.
89 if (const BuiltinType *BT = Ty->getAsBuiltinType())
90 if (BT->getKind() == BuiltinType::Float)
91 return ImpCastExprToType(Expr, Context.DoubleTy);
92
93 UsualUnaryConversions(Expr);
94}
95
Chris Lattner299b8842008-07-25 21:10:04 +000096/// UsualArithmeticConversions - Performs various conversions that are common to
97/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
98/// routine returns the first non-arithmetic type found. The client is
99/// responsible for emitting appropriate error diagnostics.
100/// FIXME: verify the conversion rules for "complex int" are consistent with
101/// GCC.
102QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
103 bool isCompAssign) {
104 if (!isCompAssign) {
105 UsualUnaryConversions(lhsExpr);
106 UsualUnaryConversions(rhsExpr);
107 }
108 // For conversion purposes, we ignore any qualifiers.
109 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000110 QualType lhs =
111 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
112 QualType rhs =
113 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattner299b8842008-07-25 21:10:04 +0000114
115 // If both types are identical, no conversion is needed.
116 if (lhs == rhs)
117 return lhs;
118
119 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
120 // The caller can deal with this (e.g. pointer + int).
121 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
122 return lhs;
123
124 // At this point, we have two different arithmetic types.
125
126 // Handle complex types first (C99 6.3.1.8p1).
127 if (lhs->isComplexType() || rhs->isComplexType()) {
128 // if we have an integer operand, the result is the complex type.
129 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
130 // convert the rhs to the lhs complex type.
131 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
132 return lhs;
133 }
134 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
135 // convert the lhs to the rhs complex type.
136 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
137 return rhs;
138 }
139 // This handles complex/complex, complex/float, or float/complex.
140 // When both operands are complex, the shorter operand is converted to the
141 // type of the longer, and that is the type of the result. This corresponds
142 // to what is done when combining two real floating-point operands.
143 // The fun begins when size promotion occur across type domains.
144 // From H&S 6.3.4: When one operand is complex and the other is a real
145 // floating-point type, the less precise type is converted, within it's
146 // real or complex domain, to the precision of the other type. For example,
147 // when combining a "long double" with a "double _Complex", the
148 // "double _Complex" is promoted to "long double _Complex".
149 int result = Context.getFloatingTypeOrder(lhs, rhs);
150
151 if (result > 0) { // The left side is bigger, convert rhs.
152 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
153 if (!isCompAssign)
154 ImpCastExprToType(rhsExpr, rhs);
155 } else if (result < 0) { // The right side is bigger, convert lhs.
156 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
157 if (!isCompAssign)
158 ImpCastExprToType(lhsExpr, lhs);
159 }
160 // At this point, lhs and rhs have the same rank/size. Now, make sure the
161 // domains match. This is a requirement for our implementation, C99
162 // does not require this promotion.
163 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
164 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
165 if (!isCompAssign)
166 ImpCastExprToType(lhsExpr, rhs);
167 return rhs;
168 } else { // handle "_Complex double, double".
169 if (!isCompAssign)
170 ImpCastExprToType(rhsExpr, lhs);
171 return lhs;
172 }
173 }
174 return lhs; // The domain/size match exactly.
175 }
176 // Now handle "real" floating types (i.e. float, double, long double).
177 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
178 // if we have an integer operand, the result is the real floating type.
179 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
180 // convert rhs to the lhs floating point type.
181 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
182 return lhs;
183 }
184 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
185 // convert lhs to the rhs floating point type.
186 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
187 return rhs;
188 }
189 // We have two real floating types, float/complex combos were handled above.
190 // Convert the smaller operand to the bigger result.
191 int result = Context.getFloatingTypeOrder(lhs, rhs);
192
193 if (result > 0) { // convert the rhs
194 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
195 return lhs;
196 }
197 if (result < 0) { // convert the lhs
198 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
199 return rhs;
200 }
201 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
202 }
203 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
204 // Handle GCC complex int extension.
205 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
206 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
207
208 if (lhsComplexInt && rhsComplexInt) {
209 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
210 rhsComplexInt->getElementType()) >= 0) {
211 // convert the rhs
212 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
213 return lhs;
214 }
215 if (!isCompAssign)
216 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
217 return rhs;
218 } else if (lhsComplexInt && rhs->isIntegerType()) {
219 // convert the rhs to the lhs complex type.
220 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
221 return lhs;
222 } else if (rhsComplexInt && lhs->isIntegerType()) {
223 // convert the lhs to the rhs complex type.
224 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
225 return rhs;
226 }
227 }
228 // Finally, we have two differing integer types.
229 // The rules for this case are in C99 6.3.1.8
230 int compare = Context.getIntegerTypeOrder(lhs, rhs);
231 bool lhsSigned = lhs->isSignedIntegerType(),
232 rhsSigned = rhs->isSignedIntegerType();
233 QualType destType;
234 if (lhsSigned == rhsSigned) {
235 // Same signedness; use the higher-ranked type
236 destType = compare >= 0 ? lhs : rhs;
237 } else if (compare != (lhsSigned ? 1 : -1)) {
238 // The unsigned type has greater than or equal rank to the
239 // signed type, so use the unsigned type
240 destType = lhsSigned ? rhs : lhs;
241 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
242 // The two types are different widths; if we are here, that
243 // means the signed type is larger than the unsigned type, so
244 // use the signed type.
245 destType = lhsSigned ? lhs : rhs;
246 } else {
247 // The signed type is higher-ranked than the unsigned type,
248 // but isn't actually any bigger (like unsigned int and long
249 // on most 32-bit systems). Use the unsigned type corresponding
250 // to the signed type.
251 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
252 }
253 if (!isCompAssign) {
254 ImpCastExprToType(lhsExpr, destType);
255 ImpCastExprToType(rhsExpr, destType);
256 }
257 return destType;
258}
259
260//===----------------------------------------------------------------------===//
261// Semantic Analysis for various Expression Types
262//===----------------------------------------------------------------------===//
263
264
Steve Naroff87d58b42007-09-16 03:34:24 +0000265/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000266/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
267/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
268/// multiple tokens. However, the common case is that StringToks points to one
269/// string.
270///
271Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000272Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000273 assert(NumStringToks && "Must have at least one string!");
274
275 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
276 if (Literal.hadError)
277 return ExprResult(true);
278
279 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
280 for (unsigned i = 0; i != NumStringToks; ++i)
281 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000282
283 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000284 if (Literal.Pascal && Literal.GetStringLength() > 256)
285 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
286 SourceRange(StringToks[0].getLocation(),
287 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000288
Chris Lattnera6dcce32008-02-11 00:02:17 +0000289 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000290 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000291 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
292
293 // Get an array type for the string, according to C99 6.4.5. This includes
294 // the nul terminator character as well as the string length for pascal
295 // strings.
296 StrTy = Context.getConstantArrayType(StrTy,
297 llvm::APInt(32, Literal.GetStringLength()+1),
298 ArrayType::Normal, 0);
299
Chris Lattner4b009652007-07-25 00:24:17 +0000300 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
301 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000302 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000303 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000304 StringToks[NumStringToks-1].getLocation());
305}
306
307
Steve Naroff0acc9c92007-09-15 18:49:24 +0000308/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000309/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000310/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000311Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000312 IdentifierInfo &II,
313 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000314 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +0000315 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000316
317 // If this reference is in an Objective-C method, then ivar lookup happens as
318 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000319 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000320 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000321 // There are two cases to handle here. 1) scoped lookup could have failed,
322 // in which case we should look for an ivar. 2) scoped lookup could have
323 // found a decl, but that decl is outside the current method (i.e. a global
324 // variable). In these two cases, we do a lookup for an ivar with this
325 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000326 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000327 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattnered94f762008-07-21 04:44:44 +0000328 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000329 // FIXME: This should use a new expr for a direct reference, don't turn
330 // this into Self->ivar, just return a BareIVarExpr or something.
331 IdentifierInfo &II = Context.Idents.get("self");
332 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
333 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
334 static_cast<Expr*>(SelfExpr.Val), true, true);
335 }
336 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000337 // Needed to implement property "super.method" notation.
Steve Naroffe90d4cc2008-06-05 18:14:25 +0000338 if (SD == 0 && !strcmp(II.getName(), "super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000339 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000340 getCurMethodDecl()->getClassInterface()));
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000341 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroff6f786252008-06-02 23:03:37 +0000342 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000343 }
344
Chris Lattner4b009652007-07-25 00:24:17 +0000345 if (D == 0) {
346 // Otherwise, this could be an implicitly declared function reference (legal
347 // in C90, extension in C99).
348 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000349 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000350 D = ImplicitlyDefineFunction(Loc, II, S);
351 else {
352 // If this name wasn't predeclared and if this is not a function call,
353 // diagnose the problem.
354 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
355 }
356 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000357
Steve Naroff91b03f72007-08-28 03:03:08 +0000358 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneree4c3bf2008-02-29 16:48:43 +0000359 // check if referencing an identifier with __attribute__((deprecated)).
360 if (VD->getAttr<DeprecatedAttr>())
361 Diag(Loc, diag::warn_deprecated, VD->getName());
362
Steve Naroffcae537d2007-08-28 18:45:29 +0000363 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000364 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000365 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000366 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000367 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000368
369 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
370 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
371 if (MD->isStatic())
372 // "invalid use of member 'x' in static member function"
373 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
374 FD->getName());
375 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
376 // "invalid use of nonstatic data member 'x'"
377 return Diag(Loc, diag::err_invalid_non_static_member_use,
378 FD->getName());
379
380 if (FD->isInvalidDecl())
381 return true;
382
383 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
384 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
385 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
386 true, FD, Loc, FD->getType());
387 }
388
389 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
390 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000391
Chris Lattner4b009652007-07-25 00:24:17 +0000392 if (isa<TypedefDecl>(D))
393 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000394 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000395 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000396 if (isa<NamespaceDecl>(D))
397 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000398
399 assert(0 && "Invalid decl");
400 abort();
401}
402
Chris Lattner69909292008-08-10 01:53:14 +0000403Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000404 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000405 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000406
407 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000408 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000409 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
410 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
411 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000412 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000413
414 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000415 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000416 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000417
Chris Lattner7e637512008-01-12 08:14:25 +0000418 // Pre-defined identifiers are of type char[x], where x is the length of the
419 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000420 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000421 if (getCurFunctionDecl())
422 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000423 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000424 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000425
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000426 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000427 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000428 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000429 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000430}
431
Steve Naroff87d58b42007-09-16 03:34:24 +0000432Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000433 llvm::SmallString<16> CharBuffer;
434 CharBuffer.resize(Tok.getLength());
435 const char *ThisTokBegin = &CharBuffer[0];
436 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
437
438 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
439 Tok.getLocation(), PP);
440 if (Literal.hadError())
441 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000442
443 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
444
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000445 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
446 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000447}
448
Steve Naroff87d58b42007-09-16 03:34:24 +0000449Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000450 // fast path for a single digit (which is quite common). A single digit
451 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
452 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000453 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000454
Chris Lattner8cd0e932008-03-05 18:54:05 +0000455 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000456 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000457 Context.IntTy,
458 Tok.getLocation()));
459 }
460 llvm::SmallString<512> IntegerBuffer;
461 IntegerBuffer.resize(Tok.getLength());
462 const char *ThisTokBegin = &IntegerBuffer[0];
463
464 // Get the spelling of the token, which eliminates trigraphs, etc.
465 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
466 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
467 Tok.getLocation(), PP);
468 if (Literal.hadError)
469 return ExprResult(true);
470
Chris Lattner1de66eb2007-08-26 03:42:43 +0000471 Expr *Res;
472
473 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000474 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000475 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000476 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000477 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000478 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000479 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000480 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000481
482 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
483
Ted Kremenekddedbe22007-11-29 00:56:49 +0000484 // isExact will be set by GetFloatValue().
485 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000486 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000487 Ty, Tok.getLocation());
488
Chris Lattner1de66eb2007-08-26 03:42:43 +0000489 } else if (!Literal.isIntegerLiteral()) {
490 return ExprResult(true);
491 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000492 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000493
Neil Booth7421e9c2007-08-29 22:00:19 +0000494 // long long is a C99 feature.
495 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000496 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000497 Diag(Tok.getLocation(), diag::ext_longlong);
498
Chris Lattner4b009652007-07-25 00:24:17 +0000499 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000500 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000501
502 if (Literal.GetIntegerValue(ResultVal)) {
503 // If this value didn't fit into uintmax_t, warn and force to ull.
504 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000505 Ty = Context.UnsignedLongLongTy;
506 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000507 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000508 } else {
509 // If this value fits into a ULL, try to figure out what else it fits into
510 // according to the rules of C99 6.4.4.1p5.
511
512 // Octal, Hexadecimal, and integers with a U suffix are allowed to
513 // be an unsigned int.
514 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
515
516 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000517 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000518 if (!Literal.isLong && !Literal.isLongLong) {
519 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000520 unsigned IntSize = Context.Target.getIntWidth();
521
Chris Lattner4b009652007-07-25 00:24:17 +0000522 // Does it fit in a unsigned int?
523 if (ResultVal.isIntN(IntSize)) {
524 // Does it fit in a signed int?
525 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000526 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000527 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000528 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000529 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000530 }
Chris Lattner4b009652007-07-25 00:24:17 +0000531 }
532
533 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000534 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000535 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000536
537 // Does it fit in a unsigned long?
538 if (ResultVal.isIntN(LongSize)) {
539 // Does it fit in a signed long?
540 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000541 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000542 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000543 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000544 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000545 }
Chris Lattner4b009652007-07-25 00:24:17 +0000546 }
547
548 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000549 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000550 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000551
552 // Does it fit in a unsigned long long?
553 if (ResultVal.isIntN(LongLongSize)) {
554 // Does it fit in a signed long long?
555 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000556 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000557 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000558 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000559 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000560 }
561 }
562
563 // If we still couldn't decide a type, we probably have something that
564 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000565 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000566 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000567 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000568 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000569 }
Chris Lattnere4068872008-05-09 05:59:00 +0000570
571 if (ResultVal.getBitWidth() != Width)
572 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000573 }
574
Chris Lattner48d7f382008-04-02 04:24:33 +0000575 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000576 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000577
578 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
579 if (Literal.isImaginary)
580 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
581
582 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000583}
584
Steve Naroff87d58b42007-09-16 03:34:24 +0000585Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000586 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000587 Expr *E = (Expr *)Val;
588 assert((E != 0) && "ActOnParenExpr() missing expr");
589 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000590}
591
592/// The UsualUnaryConversions() function is *not* called by this routine.
593/// See C99 6.3.2.1p[2-4] for more details.
594QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerf814d882008-07-25 21:45:37 +0000595 SourceLocation OpLoc,
596 const SourceRange &ExprRange,
597 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000598 // C99 6.5.3.4p1:
599 if (isa<FunctionType>(exprType) && isSizeof)
600 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000601 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000602 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000603 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
604 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000605 else if (exprType->isIncompleteType()) {
606 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
607 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000608 exprType.getAsString(), ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000609 return QualType(); // error
610 }
611 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
612 return Context.getSizeType();
613}
614
615Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000616ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000617 SourceLocation LPLoc, TypeTy *Ty,
618 SourceLocation RPLoc) {
619 // If error parsing type, ignore.
620 if (Ty == 0) return true;
621
622 // Verify that this is a valid expression.
623 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
624
Chris Lattnerf814d882008-07-25 21:45:37 +0000625 QualType resultType =
626 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Chris Lattner4b009652007-07-25 00:24:17 +0000627
628 if (resultType.isNull())
629 return true;
630 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
631}
632
Chris Lattner5110ad52007-08-24 21:41:10 +0000633QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000634 DefaultFunctionArrayConversion(V);
635
Chris Lattnera16e42d2007-08-26 05:39:26 +0000636 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000637 if (const ComplexType *CT = V->getType()->getAsComplexType())
638 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000639
640 // Otherwise they pass through real integer and floating point types here.
641 if (V->getType()->isArithmeticType())
642 return V->getType();
643
644 // Reject anything else.
645 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
646 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000647}
648
649
Chris Lattner4b009652007-07-25 00:24:17 +0000650
Steve Naroff87d58b42007-09-16 03:34:24 +0000651Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000652 tok::TokenKind Kind,
653 ExprTy *Input) {
654 UnaryOperator::Opcode Opc;
655 switch (Kind) {
656 default: assert(0 && "Unknown unary op!");
657 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
658 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
659 }
660 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
661 if (result.isNull())
662 return true;
663 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
664}
665
666Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000667ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000668 ExprTy *Idx, SourceLocation RLoc) {
669 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
670
671 // Perform default conversions.
672 DefaultFunctionArrayConversion(LHSExp);
673 DefaultFunctionArrayConversion(RHSExp);
674
675 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
676
677 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000678 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000679 // in the subscript position. As a result, we need to derive the array base
680 // and index from the expression types.
681 Expr *BaseExpr, *IndexExpr;
682 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000683 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000684 BaseExpr = LHSExp;
685 IndexExpr = RHSExp;
686 // FIXME: need to deal with const...
687 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000688 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000689 // Handle the uncommon case of "123[Ptr]".
690 BaseExpr = RHSExp;
691 IndexExpr = LHSExp;
692 // FIXME: need to deal with const...
693 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000694 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
695 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000696 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000697
698 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000699 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
700 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000701 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000702 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000703 // FIXME: need to deal with const...
704 ResultType = VTy->getElementType();
705 } else {
706 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
707 RHSExp->getSourceRange());
708 }
709 // C99 6.5.2.1p1
710 if (!IndexExpr->getType()->isIntegerType())
711 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
712 IndexExpr->getSourceRange());
713
714 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
715 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000716 // void (*)(int)) and pointers to incomplete types. Functions are not
717 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000718 if (!ResultType->isObjectType())
719 return Diag(BaseExpr->getLocStart(),
720 diag::err_typecheck_subscript_not_object,
721 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
722
723 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
724}
725
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000726QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000727CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000728 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000729 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000730
731 // This flag determines whether or not the component is to be treated as a
732 // special name, or a regular GLSL-style component access.
733 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000734
735 // The vector accessor can't exceed the number of elements.
736 const char *compStr = CompName.getName();
737 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000738 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000739 baseType.getAsString(), SourceRange(CompLoc));
740 return QualType();
741 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000742
743 // Check that we've found one of the special components, or that the component
744 // names must come from the same set.
745 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
746 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
747 SpecialComponent = true;
748 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000749 do
750 compStr++;
751 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
752 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
753 do
754 compStr++;
755 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
756 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
757 do
758 compStr++;
759 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
760 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000761
Nate Begemanc8e51f82008-05-09 06:41:27 +0000762 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000763 // We didn't get to the end of the string. This means the component names
764 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000765 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000766 std::string(compStr,compStr+1), SourceRange(CompLoc));
767 return QualType();
768 }
769 // Each component accessor can't exceed the vector type.
770 compStr = CompName.getName();
771 while (*compStr) {
772 if (vecType->isAccessorWithinNumElements(*compStr))
773 compStr++;
774 else
775 break;
776 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000777 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000778 // We didn't get to the end of the string. This means a component accessor
779 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000780 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000781 baseType.getAsString(), SourceRange(CompLoc));
782 return QualType();
783 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000784
785 // If we have a special component name, verify that the current vector length
786 // is an even number, since all special component names return exactly half
787 // the elements.
788 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
789 return QualType();
790 }
791
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000792 // The component accessor looks fine - now we need to compute the actual type.
793 // The vector type is implied by the component accessor. For example,
794 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000795 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
796 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
797 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000798 if (CompSize == 1)
799 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000800
Nate Begemanaf6ed502008-04-18 23:10:10 +0000801 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000802 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000803 // diagostics look bad. We want extended vector types to appear built-in.
804 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
805 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
806 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000807 }
808 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000809}
810
Chris Lattner4b009652007-07-25 00:24:17 +0000811Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000812ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000813 tok::TokenKind OpKind, SourceLocation MemberLoc,
814 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000815 Expr *BaseExpr = static_cast<Expr *>(Base);
816 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000817
818 // Perform default conversions.
819 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000820
Steve Naroff2cb66382007-07-26 03:11:44 +0000821 QualType BaseType = BaseExpr->getType();
822 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000823
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000824 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
825 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000826 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000827 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000828 BaseType = PT->getPointeeType();
829 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000830 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
831 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000832 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000833
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000834 // Handle field access to simple records. This also handles access to fields
835 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000836 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000837 RecordDecl *RDecl = RTy->getDecl();
838 if (RTy->isIncompleteType())
839 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
840 BaseExpr->getSourceRange());
841 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000842 FieldDecl *MemberDecl = RDecl->getMember(&Member);
843 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000844 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
845 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000846
847 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000848 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000849 QualType MemberType = MemberDecl->getType();
850 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000851 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000852 MemberType = MemberType.getQualifiedType(combinedQualifiers);
853
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000854 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000855 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000856 }
857
Chris Lattnere9d71612008-07-21 04:59:05 +0000858 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
859 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000860 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
861 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000862 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000863 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000864 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000865 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000866 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000867 }
868
Chris Lattnere9d71612008-07-21 04:59:05 +0000869 // Handle Objective-C property access, which is "Obj.property" where Obj is a
870 // pointer to a (potentially qualified) interface type.
871 const PointerType *PTy;
872 const ObjCInterfaceType *IFTy;
873 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
874 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
875 ObjCInterfaceDecl *IFace = IFTy->getDecl();
876
Chris Lattner55a24332008-07-21 06:44:27 +0000877 // FIXME: The logic for looking up nullary and unary selectors should be
878 // shared with the code in ActOnInstanceMessage.
879
Chris Lattnere9d71612008-07-21 04:59:05 +0000880 // Before we look for explicit property declarations, we check for
881 // nullary methods (which allow '.' notation).
882 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Chris Lattnere9d71612008-07-21 04:59:05 +0000883 if (ObjCMethodDecl *MD = IFace->lookupInstanceMethod(Sel))
884 return new ObjCPropertyRefExpr(MD, MD->getResultType(),
885 MemberLoc, BaseExpr);
886
Chris Lattner55a24332008-07-21 06:44:27 +0000887 // If this reference is in an @implementation, check for 'private' methods.
888 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
889 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
890 if (ObjCImplementationDecl *ImpDecl =
891 ObjCImplementations[ClassDecl->getIdentifier()])
892 if (ObjCMethodDecl *MD = ImpDecl->getInstanceMethod(Sel))
893 return new ObjCPropertyRefExpr(MD, MD->getResultType(),
894 MemberLoc, BaseExpr);
895 }
896
Chris Lattnere9d71612008-07-21 04:59:05 +0000897 // FIXME: Need to deal with setter methods that take 1 argument. E.g.:
898 // @interface NSBundle : NSObject {}
899 // - (NSString *)bundlePath;
900 // - (void)setBundlePath:(NSString *)x;
901 // @end
902 // void someMethod() { frameworkBundle.bundlePath = 0; }
903 //
904 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
905 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
906
907 // Lastly, check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000908 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
909 E = IFTy->qual_end(); I != E; ++I)
910 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
911 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000912 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000913
914 // Handle 'field access' to vectors, such as 'V.xx'.
915 if (BaseType->isExtVectorType() && OpKind == tok::period) {
916 // Component access limited to variables (reject vec4.rg.g).
917 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
918 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +0000919 return Diag(MemberLoc, diag::err_ext_vector_component_access,
920 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000921 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
922 if (ret.isNull())
923 return true;
924 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
925 }
926
Chris Lattner7d5a8762008-07-21 05:35:34 +0000927 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
928 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000929}
930
Steve Naroff87d58b42007-09-16 03:34:24 +0000931/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000932/// This provides the location of the left/right parens and a list of comma
933/// locations.
934Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000935ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000936 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000937 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
938 Expr *Fn = static_cast<Expr *>(fn);
939 Expr **Args = reinterpret_cast<Expr**>(args);
940 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +0000941 FunctionDecl *FDecl = NULL;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000942
943 // Promote the function operand.
944 UsualUnaryConversions(Fn);
945
946 // If we're directly calling a function, get the declaration for
947 // that function.
948 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
949 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
950 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
951
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000952 // Make the call expr early, before semantic checks. This guarantees cleanup
953 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +0000954 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000955 Context.BoolTy, RParenLoc));
956
Chris Lattner4b009652007-07-25 00:24:17 +0000957 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
958 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000959 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000960 if (PT == 0)
961 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
962 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000963 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
964 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000965 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
966 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000967
968 // We know the result type of the call, set it.
969 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000970
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000971 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000972 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
973 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000974 unsigned NumArgsInProto = Proto->getNumArgs();
975 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000976
Chris Lattner3e254fb2008-04-08 04:40:51 +0000977 // If too few arguments are available (and we don't have default
978 // arguments for the remaining parameters), don't make the call.
979 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +0000980 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000981 // Use default arguments for missing arguments
982 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +0000983 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000984 } else
985 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
986 Fn->getSourceRange());
987 }
988
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000989 // If too many are passed and not variadic, error on the extras and drop
990 // them.
991 if (NumArgs > NumArgsInProto) {
992 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000993 Diag(Args[NumArgsInProto]->getLocStart(),
994 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
995 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000996 Args[NumArgs-1]->getLocEnd()));
997 // This deletes the extra arguments.
998 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000999 }
1000 NumArgsToCheck = NumArgsInProto;
1001 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001002
Chris Lattner4b009652007-07-25 00:24:17 +00001003 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001004 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001005 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001006
1007 Expr *Arg;
1008 if (i < NumArgs)
1009 Arg = Args[i];
1010 else
1011 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001012 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001013
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001014 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +00001015 AssignConvertType ConvTy =
1016 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001017 TheCall->setArg(i, Arg);
1018
Chris Lattner005ed752008-01-04 18:04:52 +00001019 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1020 ArgType, Arg, "passing"))
1021 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001022 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001023
1024 // If this is a variadic call, handle args passed through "...".
1025 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001026 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001027 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1028 Expr *Arg = Args[i];
1029 DefaultArgumentPromotion(Arg);
1030 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001031 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001032 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001033 } else {
1034 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1035
Steve Naroffdb65e052007-08-28 23:30:39 +00001036 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001037 for (unsigned i = 0; i != NumArgs; i++) {
1038 Expr *Arg = Args[i];
1039 DefaultArgumentPromotion(Arg);
1040 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001041 }
Chris Lattner4b009652007-07-25 00:24:17 +00001042 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001043
Chris Lattner2e64c072007-08-10 20:18:51 +00001044 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001045 if (FDecl)
1046 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001047
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001048 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001049}
1050
1051Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001052ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001053 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001054 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001055 QualType literalType = QualType::getFromOpaquePtr(Ty);
1056 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001057 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001058 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001059
Eli Friedman8c2173d2008-05-20 05:22:08 +00001060 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001061 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001062 return Diag(LParenLoc,
1063 diag::err_variable_object_no_init,
1064 SourceRange(LParenLoc,
1065 literalExpr->getSourceRange().getEnd()));
1066 } else if (literalType->isIncompleteType()) {
1067 return Diag(LParenLoc,
1068 diag::err_typecheck_decl_incomplete_type,
1069 literalType.getAsString(),
1070 SourceRange(LParenLoc,
1071 literalExpr->getSourceRange().getEnd()));
1072 }
1073
Steve Narofff0b23542008-01-10 22:15:12 +00001074 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +00001075 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001076
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001077 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001078 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001079 if (CheckForConstantInitializer(literalExpr, literalType))
1080 return true;
1081 }
Steve Naroffbe37fc02008-01-14 18:19:28 +00001082 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001083}
1084
1085Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001086ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001087 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001088 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001089
Steve Naroff0acc9c92007-09-15 18:49:24 +00001090 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001091 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001092
Chris Lattner48d7f382008-04-02 04:24:33 +00001093 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1094 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1095 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001096}
1097
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001098bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001099 assert(VectorTy->isVectorType() && "Not a vector type!");
1100
1101 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001102 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001103 return Diag(R.getBegin(),
1104 Ty->isVectorType() ?
1105 diag::err_invalid_conversion_between_vectors :
1106 diag::err_invalid_conversion_between_vector_and_integer,
1107 VectorTy.getAsString().c_str(),
1108 Ty.getAsString().c_str(), R);
1109 } else
1110 return Diag(R.getBegin(),
1111 diag::err_invalid_conversion_between_vector_and_scalar,
1112 VectorTy.getAsString().c_str(),
1113 Ty.getAsString().c_str(), R);
1114
1115 return false;
1116}
1117
Chris Lattner4b009652007-07-25 00:24:17 +00001118Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001119ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001120 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001121 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001122
1123 Expr *castExpr = static_cast<Expr*>(Op);
1124 QualType castType = QualType::getFromOpaquePtr(Ty);
1125
Steve Naroff68adb482007-08-31 00:32:44 +00001126 UsualUnaryConversions(castExpr);
1127
Chris Lattner4b009652007-07-25 00:24:17 +00001128 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1129 // type needs to be scalar.
Chris Lattner08b3c472008-07-25 22:06:10 +00001130 if (castType->isVoidType()) {
1131 // Cast to void allows any expr type.
1132 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1133 // GCC struct/union extension: allow cast to self.
1134 if (Context.getCanonicalType(castType) !=
1135 Context.getCanonicalType(castExpr->getType()) ||
1136 (!castType->isStructureType() && !castType->isUnionType())) {
1137 // Reject any other conversions to non-scalar types.
1138 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
1139 castType.getAsString(), castExpr->getSourceRange());
Steve Naroff5ad85292008-06-03 12:56:35 +00001140 }
Chris Lattner08b3c472008-07-25 22:06:10 +00001141
1142 // accept this, but emit an ext-warn.
1143 Diag(LParenLoc, diag::ext_typecheck_cast_nonscalar,
1144 castType.getAsString(), castExpr->getSourceRange());
1145 } else if (!castExpr->getType()->isScalarType() &&
1146 !castExpr->getType()->isVectorType()) {
1147 return Diag(castExpr->getLocStart(),
1148 diag::err_typecheck_expect_scalar_operand,
1149 castExpr->getType().getAsString(),castExpr->getSourceRange());
1150 } else if (castExpr->getType()->isVectorType()) {
1151 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
1152 castExpr->getType(), castType))
1153 return true;
1154 } else if (castType->isVectorType()) {
1155 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
1156 castType, castExpr->getType()))
1157 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001158 }
1159 return new CastExpr(castType, castExpr, LParenLoc);
1160}
1161
Chris Lattner98a425c2007-11-26 01:40:58 +00001162/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1163/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001164inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1165 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1166 UsualUnaryConversions(cond);
1167 UsualUnaryConversions(lex);
1168 UsualUnaryConversions(rex);
1169 QualType condT = cond->getType();
1170 QualType lexT = lex->getType();
1171 QualType rexT = rex->getType();
1172
1173 // first, check the condition.
1174 if (!condT->isScalarType()) { // C99 6.5.15p2
1175 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1176 condT.getAsString());
1177 return QualType();
1178 }
Chris Lattner992ae932008-01-06 22:42:25 +00001179
1180 // Now check the two expressions.
1181
1182 // If both operands have arithmetic type, do the usual arithmetic conversions
1183 // to find a common type: C99 6.5.15p3,5.
1184 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001185 UsualArithmeticConversions(lex, rex);
1186 return lex->getType();
1187 }
Chris Lattner992ae932008-01-06 22:42:25 +00001188
1189 // If both operands are the same structure or union type, the result is that
1190 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001191 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001192 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001193 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001194 // "If both the operands have structure or union type, the result has
1195 // that type." This implies that CV qualifiers are dropped.
1196 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001197 }
Chris Lattner992ae932008-01-06 22:42:25 +00001198
1199 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001200 // The following || allows only one side to be void (a GCC-ism).
1201 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001202 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001203 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1204 rex->getSourceRange());
1205 if (!rexT->isVoidType())
1206 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001207 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001208 ImpCastExprToType(lex, Context.VoidTy);
1209 ImpCastExprToType(rex, Context.VoidTy);
1210 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001211 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001212 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1213 // the type of the other operand."
1214 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001215 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001216 return lexT;
1217 }
1218 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001219 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001220 return rexT;
1221 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001222 // Handle the case where both operands are pointers before we handle null
1223 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001224 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1225 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1226 // get the "pointed to" types
1227 QualType lhptee = LHSPT->getPointeeType();
1228 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001229
Chris Lattner71225142007-07-31 21:27:01 +00001230 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1231 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001232 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001233 // Figure out necessary qualifiers (C99 6.5.15p6)
1234 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001235 QualType destType = Context.getPointerType(destPointee);
1236 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1237 ImpCastExprToType(rex, destType); // promote to void*
1238 return destType;
1239 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001240 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001241 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001242 QualType destType = Context.getPointerType(destPointee);
1243 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1244 ImpCastExprToType(rex, destType); // promote to void*
1245 return destType;
1246 }
Chris Lattner4b009652007-07-25 00:24:17 +00001247
Steve Naroff85f0dc52007-10-15 20:41:53 +00001248 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1249 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001250 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001251 lexT.getAsString(), rexT.getAsString(),
1252 lex->getSourceRange(), rex->getSourceRange());
Eli Friedman33284862008-01-30 17:02:03 +00001253 // In this situation, we assume void* type. No especially good
1254 // reason, but this is what gcc does, and we do have to pick
1255 // to get a consistent AST.
1256 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
1257 ImpCastExprToType(lex, voidPtrTy);
1258 ImpCastExprToType(rex, voidPtrTy);
1259 return voidPtrTy;
Chris Lattner71225142007-07-31 21:27:01 +00001260 }
1261 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001262 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1263 // differently qualified versions of compatible types, the result type is
1264 // a pointer to an appropriately qualified version of the *composite*
1265 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001266 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001267 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001268 QualType compositeType = lexT;
1269 ImpCastExprToType(lex, compositeType);
1270 ImpCastExprToType(rex, compositeType);
1271 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001272 }
Chris Lattner4b009652007-07-25 00:24:17 +00001273 }
Steve Naroff605896f2008-05-31 22:33:45 +00001274 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1275 // evaluates to "struct objc_object *" (and is handled above when comparing
1276 // id with statically typed objects). FIXME: Do we need an ImpCastExprToType?
1277 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1278 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true))
1279 return Context.getObjCIdType();
1280 }
Chris Lattner992ae932008-01-06 22:42:25 +00001281 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001282 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1283 lexT.getAsString(), rexT.getAsString(),
1284 lex->getSourceRange(), rex->getSourceRange());
1285 return QualType();
1286}
1287
Steve Naroff87d58b42007-09-16 03:34:24 +00001288/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001289/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001290Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001291 SourceLocation ColonLoc,
1292 ExprTy *Cond, ExprTy *LHS,
1293 ExprTy *RHS) {
1294 Expr *CondExpr = (Expr *) Cond;
1295 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001296
1297 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1298 // was the condition.
1299 bool isLHSNull = LHSExpr == 0;
1300 if (isLHSNull)
1301 LHSExpr = CondExpr;
1302
Chris Lattner4b009652007-07-25 00:24:17 +00001303 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1304 RHSExpr, QuestionLoc);
1305 if (result.isNull())
1306 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001307 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1308 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001309}
1310
Chris Lattner4b009652007-07-25 00:24:17 +00001311
1312// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1313// being closely modeled after the C99 spec:-). The odd characteristic of this
1314// routine is it effectively iqnores the qualifiers on the top level pointee.
1315// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1316// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001317Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001318Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1319 QualType lhptee, rhptee;
1320
1321 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001322 lhptee = lhsType->getAsPointerType()->getPointeeType();
1323 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001324
1325 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001326 lhptee = Context.getCanonicalType(lhptee);
1327 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001328
Chris Lattner005ed752008-01-04 18:04:52 +00001329 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001330
1331 // C99 6.5.16.1p1: This following citation is common to constraints
1332 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1333 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001334 // FIXME: Handle ASQualType
1335 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1336 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001337 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001338
1339 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1340 // incomplete type and the other is a pointer to a qualified or unqualified
1341 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001342 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001343 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001344 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001345
1346 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001347 assert(rhptee->isFunctionType());
1348 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001349 }
1350
1351 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001352 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001353 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001354
1355 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001356 assert(lhptee->isFunctionType());
1357 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001358 }
1359
Chris Lattner4b009652007-07-25 00:24:17 +00001360 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1361 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001362 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1363 rhptee.getUnqualifiedType()))
1364 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001365 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001366}
1367
1368/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1369/// has code to accommodate several GCC extensions when type checking
1370/// pointers. Here are some objectionable examples that GCC considers warnings:
1371///
1372/// int a, *pint;
1373/// short *pshort;
1374/// struct foo *pfoo;
1375///
1376/// pint = pshort; // warning: assignment from incompatible pointer type
1377/// a = pint; // warning: assignment makes integer from pointer without a cast
1378/// pint = a; // warning: assignment makes pointer from integer without a cast
1379/// pint = pfoo; // warning: assignment from incompatible pointer type
1380///
1381/// As a result, the code for dealing with pointers is more complex than the
1382/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001383///
Chris Lattner005ed752008-01-04 18:04:52 +00001384Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001385Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001386 // Get canonical types. We're not formatting these types, just comparing
1387 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001388 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1389 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001390
1391 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001392 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001393
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001394 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001395 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001396 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001397 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001398 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001399
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001400 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1401 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001402 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001403 // Relax integer conversions like we do for pointers below.
1404 if (rhsType->isIntegerType())
1405 return IntToPointer;
1406 if (lhsType->isIntegerType())
1407 return PointerToInt;
Chris Lattner1853da22008-01-04 23:18:45 +00001408 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001409 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001410
Nate Begemanc5f0f652008-07-14 18:02:46 +00001411 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001412 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001413 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1414 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001415 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001416
Nate Begemanc5f0f652008-07-14 18:02:46 +00001417 // If we are allowing lax vector conversions, and LHS and RHS are both
1418 // vectors, the total size only needs to be the same. This is a bitcast;
1419 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001420 if (getLangOptions().LaxVectorConversions &&
1421 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001422 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1423 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001424 }
1425 return Incompatible;
1426 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001427
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001428 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001429 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001430
Chris Lattner390564e2008-04-07 06:49:41 +00001431 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001432 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001433 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001434
Chris Lattner390564e2008-04-07 06:49:41 +00001435 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001436 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001437 return Incompatible;
1438 }
1439
Chris Lattner390564e2008-04-07 06:49:41 +00001440 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001441 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001442 if (lhsType == Context.BoolTy)
1443 return Compatible;
1444
1445 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001446 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001447
Chris Lattner390564e2008-04-07 06:49:41 +00001448 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001449 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001450 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001451 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001452
Chris Lattner1853da22008-01-04 23:18:45 +00001453 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001454 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001455 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001456 }
1457 return Incompatible;
1458}
1459
Chris Lattner005ed752008-01-04 18:04:52 +00001460Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001461Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001462 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1463 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001464 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001465 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001466 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001467 return Compatible;
1468 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001469 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001470 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001471 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001472 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001473 //
1474 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1475 // are better understood.
1476 if (!lhsType->isReferenceType())
1477 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001478
Chris Lattner005ed752008-01-04 18:04:52 +00001479 Sema::AssignConvertType result =
1480 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001481
1482 // C99 6.5.16.1p2: The value of the right operand is converted to the
1483 // type of the assignment expression.
1484 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001485 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001486 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001487}
1488
Chris Lattner005ed752008-01-04 18:04:52 +00001489Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001490Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1491 return CheckAssignmentConstraints(lhsType, rhsType);
1492}
1493
Chris Lattner2c8bff72007-12-12 05:47:28 +00001494QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001495 Diag(loc, diag::err_typecheck_invalid_operands,
1496 lex->getType().getAsString(), rex->getType().getAsString(),
1497 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001498 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001499}
1500
1501inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1502 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001503 // For conversion purposes, we ignore any qualifiers.
1504 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001505 QualType lhsType =
1506 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1507 QualType rhsType =
1508 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001509
Nate Begemanc5f0f652008-07-14 18:02:46 +00001510 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001511 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001512 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001513
Nate Begemanc5f0f652008-07-14 18:02:46 +00001514 // Handle the case of a vector & extvector type of the same size and element
1515 // type. It would be nice if we only had one vector type someday.
1516 if (getLangOptions().LaxVectorConversions)
1517 if (const VectorType *LV = lhsType->getAsVectorType())
1518 if (const VectorType *RV = rhsType->getAsVectorType())
1519 if (LV->getElementType() == RV->getElementType() &&
1520 LV->getNumElements() == RV->getNumElements())
1521 return lhsType->isExtVectorType() ? lhsType : rhsType;
1522
1523 // If the lhs is an extended vector and the rhs is a scalar of the same type
1524 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001525 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001526 QualType eltType = V->getElementType();
1527
1528 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1529 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1530 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001531 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001532 return lhsType;
1533 }
1534 }
1535
Nate Begemanc5f0f652008-07-14 18:02:46 +00001536 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001537 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001538 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001539 QualType eltType = V->getElementType();
1540
1541 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1542 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1543 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001544 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001545 return rhsType;
1546 }
1547 }
1548
Chris Lattner4b009652007-07-25 00:24:17 +00001549 // You cannot convert between vector values of different size.
1550 Diag(loc, diag::err_typecheck_vector_not_convertable,
1551 lex->getType().getAsString(), rex->getType().getAsString(),
1552 lex->getSourceRange(), rex->getSourceRange());
1553 return QualType();
1554}
1555
1556inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001557 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001558{
1559 QualType lhsType = lex->getType(), rhsType = rex->getType();
1560
1561 if (lhsType->isVectorType() || rhsType->isVectorType())
1562 return CheckVectorOperands(loc, lex, rex);
1563
Steve Naroff8f708362007-08-24 19:07:16 +00001564 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001565
Chris Lattner4b009652007-07-25 00:24:17 +00001566 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001567 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001568 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001569}
1570
1571inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001572 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001573{
1574 QualType lhsType = lex->getType(), rhsType = rex->getType();
1575
Steve Naroff8f708362007-08-24 19:07:16 +00001576 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001577
Chris Lattner4b009652007-07-25 00:24:17 +00001578 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001579 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001580 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001581}
1582
1583inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001584 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001585{
1586 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1587 return CheckVectorOperands(loc, lex, rex);
1588
Steve Naroff8f708362007-08-24 19:07:16 +00001589 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001590
Chris Lattner4b009652007-07-25 00:24:17 +00001591 // handle the common case first (both operands are arithmetic).
1592 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001593 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001594
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001595 // Put any potential pointer into PExp
1596 Expr* PExp = lex, *IExp = rex;
1597 if (IExp->getType()->isPointerType())
1598 std::swap(PExp, IExp);
1599
1600 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1601 if (IExp->getType()->isIntegerType()) {
1602 // Check for arithmetic on pointers to incomplete types
1603 if (!PTy->getPointeeType()->isObjectType()) {
1604 if (PTy->getPointeeType()->isVoidType()) {
1605 Diag(loc, diag::ext_gnu_void_ptr,
1606 lex->getSourceRange(), rex->getSourceRange());
1607 } else {
1608 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1609 lex->getType().getAsString(), lex->getSourceRange());
1610 return QualType();
1611 }
1612 }
1613 return PExp->getType();
1614 }
1615 }
1616
Chris Lattner2c8bff72007-12-12 05:47:28 +00001617 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001618}
1619
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001620// C99 6.5.6
1621QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1622 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001623 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1624 return CheckVectorOperands(loc, lex, rex);
1625
Steve Naroff8f708362007-08-24 19:07:16 +00001626 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001627
Chris Lattnerf6da2912007-12-09 21:53:25 +00001628 // Enforce type constraints: C99 6.5.6p3.
1629
1630 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001631 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001632 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001633
1634 // Either ptr - int or ptr - ptr.
1635 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001636 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001637
Chris Lattnerf6da2912007-12-09 21:53:25 +00001638 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001639 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001640 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001641 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001642 Diag(loc, diag::ext_gnu_void_ptr,
1643 lex->getSourceRange(), rex->getSourceRange());
1644 } else {
1645 Diag(loc, diag::err_typecheck_sub_ptr_object,
1646 lex->getType().getAsString(), lex->getSourceRange());
1647 return QualType();
1648 }
1649 }
1650
1651 // The result type of a pointer-int computation is the pointer type.
1652 if (rex->getType()->isIntegerType())
1653 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001654
Chris Lattnerf6da2912007-12-09 21:53:25 +00001655 // Handle pointer-pointer subtractions.
1656 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001657 QualType rpointee = RHSPTy->getPointeeType();
1658
Chris Lattnerf6da2912007-12-09 21:53:25 +00001659 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001660 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001661 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001662 if (rpointee->isVoidType()) {
1663 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001664 Diag(loc, diag::ext_gnu_void_ptr,
1665 lex->getSourceRange(), rex->getSourceRange());
1666 } else {
1667 Diag(loc, diag::err_typecheck_sub_ptr_object,
1668 rex->getType().getAsString(), rex->getSourceRange());
1669 return QualType();
1670 }
1671 }
1672
1673 // Pointee types must be compatible.
Steve Naroff577f9722008-01-29 18:58:14 +00001674 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1675 rpointee.getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001676 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1677 lex->getType().getAsString(), rex->getType().getAsString(),
1678 lex->getSourceRange(), rex->getSourceRange());
1679 return QualType();
1680 }
1681
1682 return Context.getPointerDiffType();
1683 }
1684 }
1685
Chris Lattner2c8bff72007-12-12 05:47:28 +00001686 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001687}
1688
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001689// C99 6.5.7
1690QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1691 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00001692 // C99 6.5.7p2: Each of the operands shall have integer type.
1693 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1694 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001695
Chris Lattner2c8bff72007-12-12 05:47:28 +00001696 // Shifts don't perform usual arithmetic conversions, they just do integer
1697 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001698 if (!isCompAssign)
1699 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001700 UsualUnaryConversions(rex);
1701
1702 // "The type of the result is that of the promoted left operand."
1703 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001704}
1705
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001706// C99 6.5.8
1707QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1708 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001709 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1710 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1711
Chris Lattner254f3bc2007-08-26 01:18:55 +00001712 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001713 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1714 UsualArithmeticConversions(lex, rex);
1715 else {
1716 UsualUnaryConversions(lex);
1717 UsualUnaryConversions(rex);
1718 }
Chris Lattner4b009652007-07-25 00:24:17 +00001719 QualType lType = lex->getType();
1720 QualType rType = rex->getType();
1721
Ted Kremenek486509e2007-10-29 17:13:39 +00001722 // For non-floating point types, check for self-comparisons of the form
1723 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1724 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001725 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001726 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1727 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001728 if (DRL->getDecl() == DRR->getDecl())
1729 Diag(loc, diag::warn_selfcomparison);
1730 }
1731
Chris Lattner254f3bc2007-08-26 01:18:55 +00001732 if (isRelational) {
1733 if (lType->isRealType() && rType->isRealType())
1734 return Context.IntTy;
1735 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001736 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001737 if (lType->isFloatingType()) {
1738 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001739 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001740 }
1741
Chris Lattner254f3bc2007-08-26 01:18:55 +00001742 if (lType->isArithmeticType() && rType->isArithmeticType())
1743 return Context.IntTy;
1744 }
Chris Lattner4b009652007-07-25 00:24:17 +00001745
Chris Lattner22be8422007-08-26 01:10:14 +00001746 bool LHSIsNull = lex->isNullPointerConstant(Context);
1747 bool RHSIsNull = rex->isNullPointerConstant(Context);
1748
Chris Lattner254f3bc2007-08-26 01:18:55 +00001749 // All of the following pointer related warnings are GCC extensions, except
1750 // when handling null pointer constants. One day, we can consider making them
1751 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001752 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001753 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001754 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00001755 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001756 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00001757
Steve Naroff3b435622007-11-13 14:57:38 +00001758 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001759 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1760 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
1761 RCanPointeeTy.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001762 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1763 lType.getAsString(), rType.getAsString(),
1764 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001765 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001766 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001767 return Context.IntTy;
1768 }
Steve Naroff936c4362008-06-03 14:04:54 +00001769 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
1770 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
1771 ImpCastExprToType(rex, lType);
1772 return Context.IntTy;
1773 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001774 }
Steve Naroff936c4362008-06-03 14:04:54 +00001775 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
1776 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001777 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001778 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1779 lType.getAsString(), rType.getAsString(),
1780 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001781 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001782 return Context.IntTy;
1783 }
Steve Naroff936c4362008-06-03 14:04:54 +00001784 if (lType->isIntegerType() &&
1785 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00001786 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001787 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1788 lType.getAsString(), rType.getAsString(),
1789 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001790 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001791 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001792 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001793 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001794}
1795
Nate Begemanc5f0f652008-07-14 18:02:46 +00001796/// CheckVectorCompareOperands - vector comparisons are a clang extension that
1797/// operates on extended vector types. Instead of producing an IntTy result,
1798/// like a scalar comparison, a vector comparison produces a vector of integer
1799/// types.
1800QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
1801 SourceLocation loc,
1802 bool isRelational) {
1803 // Check to make sure we're operating on vectors of the same type and width,
1804 // Allowing one side to be a scalar of element type.
1805 QualType vType = CheckVectorOperands(loc, lex, rex);
1806 if (vType.isNull())
1807 return vType;
1808
1809 QualType lType = lex->getType();
1810 QualType rType = rex->getType();
1811
1812 // For non-floating point types, check for self-comparisons of the form
1813 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1814 // often indicate logic errors in the program.
1815 if (!lType->isFloatingType()) {
1816 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1817 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1818 if (DRL->getDecl() == DRR->getDecl())
1819 Diag(loc, diag::warn_selfcomparison);
1820 }
1821
1822 // Check for comparisons of floating point operands using != and ==.
1823 if (!isRelational && lType->isFloatingType()) {
1824 assert (rType->isFloatingType());
1825 CheckFloatComparison(loc,lex,rex);
1826 }
1827
1828 // Return the type for the comparison, which is the same as vector type for
1829 // integer vectors, or an integer type of identical size and number of
1830 // elements for floating point vectors.
1831 if (lType->isIntegerType())
1832 return lType;
1833
1834 const VectorType *VTy = lType->getAsVectorType();
1835
1836 // FIXME: need to deal with non-32b int / non-64b long long
1837 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
1838 if (TypeSize == 32) {
1839 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
1840 }
1841 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
1842 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
1843}
1844
Chris Lattner4b009652007-07-25 00:24:17 +00001845inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001846 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001847{
1848 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1849 return CheckVectorOperands(loc, lex, rex);
1850
Steve Naroff8f708362007-08-24 19:07:16 +00001851 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001852
1853 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001854 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001855 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001856}
1857
1858inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1859 Expr *&lex, Expr *&rex, SourceLocation loc)
1860{
1861 UsualUnaryConversions(lex);
1862 UsualUnaryConversions(rex);
1863
Eli Friedmanbea3f842008-05-13 20:16:47 +00001864 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00001865 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001866 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001867}
1868
1869inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001870 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001871{
1872 QualType lhsType = lex->getType();
1873 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner25168a52008-07-26 21:30:36 +00001874 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00001875
1876 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001877 case Expr::MLV_Valid:
1878 break;
1879 case Expr::MLV_ConstQualified:
1880 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1881 return QualType();
1882 case Expr::MLV_ArrayType:
1883 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1884 lhsType.getAsString(), lex->getSourceRange());
1885 return QualType();
1886 case Expr::MLV_NotObjectType:
1887 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1888 lhsType.getAsString(), lex->getSourceRange());
1889 return QualType();
1890 case Expr::MLV_InvalidExpression:
1891 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1892 lex->getSourceRange());
1893 return QualType();
1894 case Expr::MLV_IncompleteType:
1895 case Expr::MLV_IncompleteVoidType:
1896 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1897 lhsType.getAsString(), lex->getSourceRange());
1898 return QualType();
1899 case Expr::MLV_DuplicateVectorComponents:
1900 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1901 lex->getSourceRange());
1902 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001903 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001904
Chris Lattner005ed752008-01-04 18:04:52 +00001905 AssignConvertType ConvTy;
1906 if (compoundType.isNull())
1907 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1908 else
1909 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1910
1911 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1912 rex, "assigning"))
1913 return QualType();
1914
Chris Lattner4b009652007-07-25 00:24:17 +00001915 // C99 6.5.16p3: The type of an assignment expression is the type of the
1916 // left operand unless the left operand has qualified type, in which case
1917 // it is the unqualified version of the type of the left operand.
1918 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1919 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001920 // C++ 5.17p1: the type of the assignment expression is that of its left
1921 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001922 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001923}
1924
1925inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1926 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00001927
1928 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
1929 DefaultFunctionArrayConversion(rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001930 return rex->getType();
1931}
1932
1933/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1934/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1935QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1936 QualType resType = op->getType();
1937 assert(!resType.isNull() && "no type for increment/decrement expression");
1938
Steve Naroffd30e1932007-08-24 17:20:07 +00001939 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001940 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001941 if (pt->getPointeeType()->isVoidType()) {
1942 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
1943 } else if (!pt->getPointeeType()->isObjectType()) {
1944 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00001945 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1946 resType.getAsString(), op->getSourceRange());
1947 return QualType();
1948 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001949 } else if (!resType->isRealType()) {
1950 if (resType->isComplexType())
1951 // C99 does not support ++/-- on complex types.
1952 Diag(OpLoc, diag::ext_integer_increment_complex,
1953 resType.getAsString(), op->getSourceRange());
1954 else {
1955 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1956 resType.getAsString(), op->getSourceRange());
1957 return QualType();
1958 }
Chris Lattner4b009652007-07-25 00:24:17 +00001959 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001960 // At this point, we know we have a real, complex or pointer type.
1961 // Now make sure the operand is a modifiable lvalue.
Chris Lattner25168a52008-07-26 21:30:36 +00001962 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00001963 if (mlval != Expr::MLV_Valid) {
1964 // FIXME: emit a more precise diagnostic...
1965 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1966 op->getSourceRange());
1967 return QualType();
1968 }
1969 return resType;
1970}
1971
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001972/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00001973/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00001974/// where the declaration is needed for type checking. We only need to
1975/// handle cases when the expression references a function designator
1976/// or is an lvalue. Here are some examples:
1977/// - &(x) => x
1978/// - &*****f => f for f a function designator.
1979/// - &s.xx => s
1980/// - &s.zz[1].yy -> s, if zz is an array
1981/// - *(x + 1) -> x, if x is an array
1982/// - &"123"[2] -> 0
1983/// - & __real__ x -> x
Chris Lattner48d7f382008-04-02 04:24:33 +00001984static ValueDecl *getPrimaryDecl(Expr *E) {
1985 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001986 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001987 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001988 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001989 // Fields cannot be declared with a 'register' storage class.
1990 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00001991 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00001992 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00001993 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001994 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00001995 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001996
Chris Lattner48d7f382008-04-02 04:24:33 +00001997 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00001998 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001999 return 0;
2000 else
2001 return VD;
2002 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002003 case Stmt::UnaryOperatorClass: {
2004 UnaryOperator *UO = cast<UnaryOperator>(E);
2005
2006 switch(UO->getOpcode()) {
2007 case UnaryOperator::Deref: {
2008 // *(X + 1) refers to X if X is not a pointer.
2009 ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2010 if (!VD || VD->getType()->isPointerType())
2011 return 0;
2012 return VD;
2013 }
2014 case UnaryOperator::Real:
2015 case UnaryOperator::Imag:
2016 case UnaryOperator::Extension:
2017 return getPrimaryDecl(UO->getSubExpr());
2018 default:
2019 return 0;
2020 }
2021 }
2022 case Stmt::BinaryOperatorClass: {
2023 BinaryOperator *BO = cast<BinaryOperator>(E);
2024
2025 // Handle cases involving pointer arithmetic. The result of an
2026 // Assign or AddAssign is not an lvalue so they can be ignored.
2027
2028 // (x + n) or (n + x) => x
2029 if (BO->getOpcode() == BinaryOperator::Add) {
2030 if (BO->getLHS()->getType()->isPointerType()) {
2031 return getPrimaryDecl(BO->getLHS());
2032 } else if (BO->getRHS()->getType()->isPointerType()) {
2033 return getPrimaryDecl(BO->getRHS());
2034 }
2035 }
2036
2037 return 0;
2038 }
Chris Lattner4b009652007-07-25 00:24:17 +00002039 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002040 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002041 case Stmt::ImplicitCastExprClass:
2042 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002043 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002044 default:
2045 return 0;
2046 }
2047}
2048
2049/// CheckAddressOfOperand - The operand of & must be either a function
2050/// designator or an lvalue designating an object. If it is an lvalue, the
2051/// object cannot be declared with storage class register or be a bit field.
2052/// Note: The usual conversions are *not* applied to the operand of the &
2053/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2054QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002055 if (getLangOptions().C99) {
2056 // Implement C99-only parts of addressof rules.
2057 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2058 if (uOp->getOpcode() == UnaryOperator::Deref)
2059 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2060 // (assuming the deref expression is valid).
2061 return uOp->getSubExpr()->getType();
2062 }
2063 // Technically, there should be a check for array subscript
2064 // expressions here, but the result of one is always an lvalue anyway.
2065 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002066 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002067 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002068
2069 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002070 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2071 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002072 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2073 op->getSourceRange());
2074 return QualType();
2075 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002076 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2077 if (MemExpr->getMemberDecl()->isBitField()) {
2078 Diag(OpLoc, diag::err_typecheck_address_of,
2079 std::string("bit-field"), op->getSourceRange());
2080 return QualType();
2081 }
2082 // Check for Apple extension for accessing vector components.
2083 } else if (isa<ArraySubscriptExpr>(op) &&
2084 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2085 Diag(OpLoc, diag::err_typecheck_address_of,
2086 std::string("vector"), op->getSourceRange());
2087 return QualType();
2088 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002089 // We have an lvalue with a decl. Make sure the decl is not declared
2090 // with the register storage-class specifier.
2091 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2092 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002093 Diag(OpLoc, diag::err_typecheck_address_of,
2094 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002095 return QualType();
2096 }
2097 } else
2098 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002099 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002100
Chris Lattner4b009652007-07-25 00:24:17 +00002101 // If the operand has type "type", the result has type "pointer to type".
2102 return Context.getPointerType(op->getType());
2103}
2104
2105QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2106 UsualUnaryConversions(op);
2107 QualType qType = op->getType();
2108
Chris Lattner7931f4a2007-07-31 16:53:04 +00002109 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002110 // Note that per both C89 and C99, this is always legal, even
2111 // if ptype is an incomplete type or void.
2112 // It would be possible to warn about dereferencing a
2113 // void pointer, but it's completely well-defined,
2114 // and such a warning is unlikely to catch any mistakes.
2115 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002116 }
2117 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2118 qType.getAsString(), op->getSourceRange());
2119 return QualType();
2120}
2121
2122static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2123 tok::TokenKind Kind) {
2124 BinaryOperator::Opcode Opc;
2125 switch (Kind) {
2126 default: assert(0 && "Unknown binop!");
2127 case tok::star: Opc = BinaryOperator::Mul; break;
2128 case tok::slash: Opc = BinaryOperator::Div; break;
2129 case tok::percent: Opc = BinaryOperator::Rem; break;
2130 case tok::plus: Opc = BinaryOperator::Add; break;
2131 case tok::minus: Opc = BinaryOperator::Sub; break;
2132 case tok::lessless: Opc = BinaryOperator::Shl; break;
2133 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2134 case tok::lessequal: Opc = BinaryOperator::LE; break;
2135 case tok::less: Opc = BinaryOperator::LT; break;
2136 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2137 case tok::greater: Opc = BinaryOperator::GT; break;
2138 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2139 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2140 case tok::amp: Opc = BinaryOperator::And; break;
2141 case tok::caret: Opc = BinaryOperator::Xor; break;
2142 case tok::pipe: Opc = BinaryOperator::Or; break;
2143 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2144 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2145 case tok::equal: Opc = BinaryOperator::Assign; break;
2146 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2147 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2148 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2149 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2150 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2151 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2152 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2153 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2154 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2155 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2156 case tok::comma: Opc = BinaryOperator::Comma; break;
2157 }
2158 return Opc;
2159}
2160
2161static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2162 tok::TokenKind Kind) {
2163 UnaryOperator::Opcode Opc;
2164 switch (Kind) {
2165 default: assert(0 && "Unknown unary op!");
2166 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2167 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2168 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2169 case tok::star: Opc = UnaryOperator::Deref; break;
2170 case tok::plus: Opc = UnaryOperator::Plus; break;
2171 case tok::minus: Opc = UnaryOperator::Minus; break;
2172 case tok::tilde: Opc = UnaryOperator::Not; break;
2173 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2174 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2175 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2176 case tok::kw___real: Opc = UnaryOperator::Real; break;
2177 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2178 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2179 }
2180 return Opc;
2181}
2182
2183// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002184Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002185 ExprTy *LHS, ExprTy *RHS) {
2186 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2187 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2188
Steve Naroff87d58b42007-09-16 03:34:24 +00002189 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2190 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002191
2192 QualType ResultTy; // Result type of the binary operator.
2193 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2194
2195 switch (Opc) {
2196 default:
2197 assert(0 && "Unknown binary expr!");
2198 case BinaryOperator::Assign:
2199 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2200 break;
2201 case BinaryOperator::Mul:
2202 case BinaryOperator::Div:
2203 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2204 break;
2205 case BinaryOperator::Rem:
2206 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2207 break;
2208 case BinaryOperator::Add:
2209 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2210 break;
2211 case BinaryOperator::Sub:
2212 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2213 break;
2214 case BinaryOperator::Shl:
2215 case BinaryOperator::Shr:
2216 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2217 break;
2218 case BinaryOperator::LE:
2219 case BinaryOperator::LT:
2220 case BinaryOperator::GE:
2221 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002222 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002223 break;
2224 case BinaryOperator::EQ:
2225 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002226 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00002227 break;
2228 case BinaryOperator::And:
2229 case BinaryOperator::Xor:
2230 case BinaryOperator::Or:
2231 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2232 break;
2233 case BinaryOperator::LAnd:
2234 case BinaryOperator::LOr:
2235 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2236 break;
2237 case BinaryOperator::MulAssign:
2238 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002239 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002240 if (!CompTy.isNull())
2241 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2242 break;
2243 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002244 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002245 if (!CompTy.isNull())
2246 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2247 break;
2248 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002249 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002250 if (!CompTy.isNull())
2251 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2252 break;
2253 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002254 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002255 if (!CompTy.isNull())
2256 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2257 break;
2258 case BinaryOperator::ShlAssign:
2259 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002260 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002261 if (!CompTy.isNull())
2262 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2263 break;
2264 case BinaryOperator::AndAssign:
2265 case BinaryOperator::XorAssign:
2266 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002267 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002268 if (!CompTy.isNull())
2269 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2270 break;
2271 case BinaryOperator::Comma:
2272 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2273 break;
2274 }
2275 if (ResultTy.isNull())
2276 return true;
2277 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00002278 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002279 else
Chris Lattnerf420df12007-08-28 18:36:55 +00002280 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002281}
2282
2283// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002284Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002285 ExprTy *input) {
2286 Expr *Input = (Expr*)input;
2287 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2288 QualType resultType;
2289 switch (Opc) {
2290 default:
2291 assert(0 && "Unimplemented unary expr!");
2292 case UnaryOperator::PreInc:
2293 case UnaryOperator::PreDec:
2294 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2295 break;
2296 case UnaryOperator::AddrOf:
2297 resultType = CheckAddressOfOperand(Input, OpLoc);
2298 break;
2299 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002300 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002301 resultType = CheckIndirectionOperand(Input, OpLoc);
2302 break;
2303 case UnaryOperator::Plus:
2304 case UnaryOperator::Minus:
2305 UsualUnaryConversions(Input);
2306 resultType = Input->getType();
2307 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2308 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2309 resultType.getAsString());
2310 break;
2311 case UnaryOperator::Not: // bitwise complement
2312 UsualUnaryConversions(Input);
2313 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002314 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2315 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2316 // C99 does not support '~' for complex conjugation.
2317 Diag(OpLoc, diag::ext_integer_complement_complex,
2318 resultType.getAsString(), Input->getSourceRange());
2319 else if (!resultType->isIntegerType())
2320 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2321 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002322 break;
2323 case UnaryOperator::LNot: // logical negation
2324 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2325 DefaultFunctionArrayConversion(Input);
2326 resultType = Input->getType();
2327 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2328 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2329 resultType.getAsString());
2330 // LNot always has type int. C99 6.5.3.3p5.
2331 resultType = Context.IntTy;
2332 break;
2333 case UnaryOperator::SizeOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002334 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2335 Input->getSourceRange(), true);
Chris Lattner4b009652007-07-25 00:24:17 +00002336 break;
2337 case UnaryOperator::AlignOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002338 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2339 Input->getSourceRange(), false);
Chris Lattner4b009652007-07-25 00:24:17 +00002340 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002341 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002342 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002343 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002344 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002345 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002346 resultType = Input->getType();
2347 break;
2348 }
2349 if (resultType.isNull())
2350 return true;
2351 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2352}
2353
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002354/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2355Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002356 SourceLocation LabLoc,
2357 IdentifierInfo *LabelII) {
2358 // Look up the record for this label identifier.
2359 LabelStmt *&LabelDecl = LabelMap[LabelII];
2360
Daniel Dunbar879788d2008-08-04 16:51:22 +00002361 // If we haven't seen this label yet, create a forward reference. It
2362 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00002363 if (LabelDecl == 0)
2364 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2365
2366 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002367 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2368 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002369}
2370
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002371Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002372 SourceLocation RPLoc) { // "({..})"
2373 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2374 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2375 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2376
2377 // FIXME: there are a variety of strange constraints to enforce here, for
2378 // example, it is not possible to goto into a stmt expression apparently.
2379 // More semantic analysis is needed.
2380
2381 // FIXME: the last statement in the compount stmt has its value used. We
2382 // should not warn about it being unused.
2383
2384 // If there are sub stmts in the compound stmt, take the type of the last one
2385 // as the type of the stmtexpr.
2386 QualType Ty = Context.VoidTy;
2387
Chris Lattner200964f2008-07-26 19:51:01 +00002388 if (!Compound->body_empty()) {
2389 Stmt *LastStmt = Compound->body_back();
2390 // If LastStmt is a label, skip down through into the body.
2391 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2392 LastStmt = Label->getSubStmt();
2393
2394 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00002395 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00002396 }
Chris Lattner4b009652007-07-25 00:24:17 +00002397
2398 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2399}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002400
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002401Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002402 SourceLocation TypeLoc,
2403 TypeTy *argty,
2404 OffsetOfComponent *CompPtr,
2405 unsigned NumComponents,
2406 SourceLocation RPLoc) {
2407 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2408 assert(!ArgTy.isNull() && "Missing type argument!");
2409
2410 // We must have at least one component that refers to the type, and the first
2411 // one is known to be a field designator. Verify that the ArgTy represents
2412 // a struct/union/class.
2413 if (!ArgTy->isRecordType())
2414 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2415
2416 // Otherwise, create a compound literal expression as the base, and
2417 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002418 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002419
Chris Lattnerb37522e2007-08-31 21:49:13 +00002420 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2421 // GCC extension, diagnose them.
2422 if (NumComponents != 1)
2423 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2424 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2425
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002426 for (unsigned i = 0; i != NumComponents; ++i) {
2427 const OffsetOfComponent &OC = CompPtr[i];
2428 if (OC.isBrackets) {
2429 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00002430 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002431 if (!AT) {
2432 delete Res;
2433 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2434 Res->getType().getAsString());
2435 }
2436
Chris Lattner2af6a802007-08-30 17:59:59 +00002437 // FIXME: C++: Verify that operator[] isn't overloaded.
2438
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002439 // C99 6.5.2.1p1
2440 Expr *Idx = static_cast<Expr*>(OC.U.E);
2441 if (!Idx->getType()->isIntegerType())
2442 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2443 Idx->getSourceRange());
2444
2445 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2446 continue;
2447 }
2448
2449 const RecordType *RC = Res->getType()->getAsRecordType();
2450 if (!RC) {
2451 delete Res;
2452 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2453 Res->getType().getAsString());
2454 }
2455
2456 // Get the decl corresponding to this.
2457 RecordDecl *RD = RC->getDecl();
2458 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2459 if (!MemberDecl)
2460 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2461 OC.U.IdentInfo->getName(),
2462 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002463
2464 // FIXME: C++: Verify that MemberDecl isn't a static field.
2465 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002466 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2467 // matter here.
2468 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002469 }
2470
2471 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2472 BuiltinLoc);
2473}
2474
2475
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002476Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002477 TypeTy *arg1, TypeTy *arg2,
2478 SourceLocation RPLoc) {
2479 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2480 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2481
2482 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2483
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002484 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002485}
2486
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002487Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002488 ExprTy *expr1, ExprTy *expr2,
2489 SourceLocation RPLoc) {
2490 Expr *CondExpr = static_cast<Expr*>(cond);
2491 Expr *LHSExpr = static_cast<Expr*>(expr1);
2492 Expr *RHSExpr = static_cast<Expr*>(expr2);
2493
2494 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2495
2496 // The conditional expression is required to be a constant expression.
2497 llvm::APSInt condEval(32);
2498 SourceLocation ExpLoc;
2499 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2500 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2501 CondExpr->getSourceRange());
2502
2503 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2504 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2505 RHSExpr->getType();
2506 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2507}
2508
Nate Begemanbd881ef2008-01-30 20:50:20 +00002509/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002510/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002511/// The number of arguments has already been validated to match the number of
2512/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002513static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2514 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002515 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00002516 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002517 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2518 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00002519
2520 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002521 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00002522 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002523 return true;
2524}
2525
2526Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2527 SourceLocation *CommaLocs,
2528 SourceLocation BuiltinLoc,
2529 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002530 // __builtin_overload requires at least 2 arguments
2531 if (NumArgs < 2)
2532 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2533 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002534
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002535 // The first argument is required to be a constant expression. It tells us
2536 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002537 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002538 Expr *NParamsExpr = Args[0];
2539 llvm::APSInt constEval(32);
2540 SourceLocation ExpLoc;
2541 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2542 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2543 NParamsExpr->getSourceRange());
2544
2545 // Verify that the number of parameters is > 0
2546 unsigned NumParams = constEval.getZExtValue();
2547 if (NumParams == 0)
2548 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2549 NParamsExpr->getSourceRange());
2550 // Verify that we have at least 1 + NumParams arguments to the builtin.
2551 if ((NumParams + 1) > NumArgs)
2552 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2553 SourceRange(BuiltinLoc, RParenLoc));
2554
2555 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002556 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002557 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002558 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2559 // UsualUnaryConversions will convert the function DeclRefExpr into a
2560 // pointer to function.
2561 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002562 const FunctionTypeProto *FnType = 0;
2563 if (const PointerType *PT = Fn->getType()->getAsPointerType())
2564 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002565
2566 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2567 // parameters, and the number of parameters must match the value passed to
2568 // the builtin.
2569 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002570 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2571 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002572
2573 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002574 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002575 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002576 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002577 if (OE)
2578 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2579 OE->getFn()->getSourceRange());
2580 // Remember our match, and continue processing the remaining arguments
2581 // to catch any errors.
2582 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2583 BuiltinLoc, RParenLoc);
2584 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002585 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002586 // Return the newly created OverloadExpr node, if we succeded in matching
2587 // exactly one of the candidate functions.
2588 if (OE)
2589 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002590
2591 // If we didn't find a matching function Expr in the __builtin_overload list
2592 // the return an error.
2593 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002594 for (unsigned i = 0; i != NumParams; ++i) {
2595 if (i != 0) typeNames += ", ";
2596 typeNames += Args[i+1]->getType().getAsString();
2597 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002598
2599 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2600 SourceRange(BuiltinLoc, RParenLoc));
2601}
2602
Anders Carlsson36760332007-10-15 20:28:48 +00002603Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2604 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002605 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002606 Expr *E = static_cast<Expr*>(expr);
2607 QualType T = QualType::getFromOpaquePtr(type);
2608
2609 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00002610
2611 // Get the va_list type
2612 QualType VaListType = Context.getBuiltinVaListType();
2613 // Deal with implicit array decay; for example, on x86-64,
2614 // va_list is an array, but it's supposed to decay to
2615 // a pointer for va_arg.
2616 if (VaListType->isArrayType())
2617 VaListType = Context.getArrayDecayedType(VaListType);
2618
2619 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002620 return Diag(E->getLocStart(),
2621 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2622 E->getType().getAsString(),
2623 E->getSourceRange());
2624
2625 // FIXME: Warn if a non-POD type is passed in.
2626
2627 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2628}
2629
Chris Lattner005ed752008-01-04 18:04:52 +00002630bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2631 SourceLocation Loc,
2632 QualType DstType, QualType SrcType,
2633 Expr *SrcExpr, const char *Flavor) {
2634 // Decode the result (notice that AST's are still created for extensions).
2635 bool isInvalid = false;
2636 unsigned DiagKind;
2637 switch (ConvTy) {
2638 default: assert(0 && "Unknown conversion type");
2639 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002640 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002641 DiagKind = diag::ext_typecheck_convert_pointer_int;
2642 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002643 case IntToPointer:
2644 DiagKind = diag::ext_typecheck_convert_int_pointer;
2645 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002646 case IncompatiblePointer:
2647 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2648 break;
2649 case FunctionVoidPointer:
2650 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2651 break;
2652 case CompatiblePointerDiscardsQualifiers:
2653 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2654 break;
2655 case Incompatible:
2656 DiagKind = diag::err_typecheck_convert_incompatible;
2657 isInvalid = true;
2658 break;
2659 }
2660
2661 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2662 SrcExpr->getSourceRange());
2663 return isInvalid;
2664}