blob: 5619eca4f00714deae40854727c3966eaf722c57 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026using namespace clang;
27
Chris Lattner299b8842008-07-25 21:10:04 +000028//===----------------------------------------------------------------------===//
29// Standard Promotions and Conversions
30//===----------------------------------------------------------------------===//
31
Chris Lattner299b8842008-07-25 21:10:04 +000032/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
33void Sema::DefaultFunctionArrayConversion(Expr *&E) {
34 QualType Ty = E->getType();
35 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
36
37 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
38 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
39 Ty = E->getType();
40 }
41 if (Ty->isFunctionType())
42 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000043 else if (Ty->isArrayType()) {
44 // In C90 mode, arrays only promote to pointers if the array expression is
45 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
46 // type 'array of type' is converted to an expression that has type 'pointer
47 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
48 // that has type 'array of type' ...". The relevant change is "an lvalue"
49 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000050 //
51 // C++ 4.2p1:
52 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
53 // T" can be converted to an rvalue of type "pointer to T".
54 //
55 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
56 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000057 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
58 }
Chris Lattner299b8842008-07-25 21:10:04 +000059}
60
61/// UsualUnaryConversions - Performs various conversions that are common to most
62/// operators (C99 6.3). The conversions of array and function types are
63/// sometimes surpressed. For example, the array->pointer conversion doesn't
64/// apply if the array is an argument to the sizeof or address (&) operators.
65/// In these instances, this routine should *not* be called.
66Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
67 QualType Ty = Expr->getType();
68 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
69
70 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
71 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
72 Ty = Expr->getType();
73 }
74 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
75 ImpCastExprToType(Expr, Context.IntTy);
76 else
77 DefaultFunctionArrayConversion(Expr);
78
79 return Expr;
80}
81
Chris Lattner9305c3d2008-07-25 22:25:12 +000082/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
83/// do not have a prototype. Arguments that have type float are promoted to
84/// double. All other argument types are converted by UsualUnaryConversions().
85void Sema::DefaultArgumentPromotion(Expr *&Expr) {
86 QualType Ty = Expr->getType();
87 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
88
89 // If this is a 'float' (CVR qualified or typedef) promote to double.
90 if (const BuiltinType *BT = Ty->getAsBuiltinType())
91 if (BT->getKind() == BuiltinType::Float)
92 return ImpCastExprToType(Expr, Context.DoubleTy);
93
94 UsualUnaryConversions(Expr);
95}
96
Chris Lattner299b8842008-07-25 21:10:04 +000097/// UsualArithmeticConversions - Performs various conversions that are common to
98/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
99/// routine returns the first non-arithmetic type found. The client is
100/// responsible for emitting appropriate error diagnostics.
101/// FIXME: verify the conversion rules for "complex int" are consistent with
102/// GCC.
103QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
104 bool isCompAssign) {
105 if (!isCompAssign) {
106 UsualUnaryConversions(lhsExpr);
107 UsualUnaryConversions(rhsExpr);
108 }
109 // For conversion purposes, we ignore any qualifiers.
110 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000111 QualType lhs =
112 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
113 QualType rhs =
114 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattner299b8842008-07-25 21:10:04 +0000115
116 // If both types are identical, no conversion is needed.
117 if (lhs == rhs)
118 return lhs;
119
120 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
121 // The caller can deal with this (e.g. pointer + int).
122 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
123 return lhs;
124
125 // At this point, we have two different arithmetic types.
126
127 // Handle complex types first (C99 6.3.1.8p1).
128 if (lhs->isComplexType() || rhs->isComplexType()) {
129 // if we have an integer operand, the result is the complex type.
130 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
131 // convert the rhs to the lhs complex type.
132 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
133 return lhs;
134 }
135 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
136 // convert the lhs to the rhs complex type.
137 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
138 return rhs;
139 }
140 // This handles complex/complex, complex/float, or float/complex.
141 // When both operands are complex, the shorter operand is converted to the
142 // type of the longer, and that is the type of the result. This corresponds
143 // to what is done when combining two real floating-point operands.
144 // The fun begins when size promotion occur across type domains.
145 // From H&S 6.3.4: When one operand is complex and the other is a real
146 // floating-point type, the less precise type is converted, within it's
147 // real or complex domain, to the precision of the other type. For example,
148 // when combining a "long double" with a "double _Complex", the
149 // "double _Complex" is promoted to "long double _Complex".
150 int result = Context.getFloatingTypeOrder(lhs, rhs);
151
152 if (result > 0) { // The left side is bigger, convert rhs.
153 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
154 if (!isCompAssign)
155 ImpCastExprToType(rhsExpr, rhs);
156 } else if (result < 0) { // The right side is bigger, convert lhs.
157 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
158 if (!isCompAssign)
159 ImpCastExprToType(lhsExpr, lhs);
160 }
161 // At this point, lhs and rhs have the same rank/size. Now, make sure the
162 // domains match. This is a requirement for our implementation, C99
163 // does not require this promotion.
164 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
165 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
166 if (!isCompAssign)
167 ImpCastExprToType(lhsExpr, rhs);
168 return rhs;
169 } else { // handle "_Complex double, double".
170 if (!isCompAssign)
171 ImpCastExprToType(rhsExpr, lhs);
172 return lhs;
173 }
174 }
175 return lhs; // The domain/size match exactly.
176 }
177 // Now handle "real" floating types (i.e. float, double, long double).
178 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
179 // if we have an integer operand, the result is the real floating type.
180 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
181 // convert rhs to the lhs floating point type.
182 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
183 return lhs;
184 }
185 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
186 // convert lhs to the rhs floating point type.
187 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
188 return rhs;
189 }
190 // We have two real floating types, float/complex combos were handled above.
191 // Convert the smaller operand to the bigger result.
192 int result = Context.getFloatingTypeOrder(lhs, rhs);
193
194 if (result > 0) { // convert the rhs
195 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
196 return lhs;
197 }
198 if (result < 0) { // convert the lhs
199 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
200 return rhs;
201 }
202 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
203 }
204 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
205 // Handle GCC complex int extension.
206 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
207 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
208
209 if (lhsComplexInt && rhsComplexInt) {
210 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
211 rhsComplexInt->getElementType()) >= 0) {
212 // convert the rhs
213 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
214 return lhs;
215 }
216 if (!isCompAssign)
217 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
218 return rhs;
219 } else if (lhsComplexInt && rhs->isIntegerType()) {
220 // convert the rhs to the lhs complex type.
221 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
222 return lhs;
223 } else if (rhsComplexInt && lhs->isIntegerType()) {
224 // convert the lhs to the rhs complex type.
225 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
226 return rhs;
227 }
228 }
229 // Finally, we have two differing integer types.
230 // The rules for this case are in C99 6.3.1.8
231 int compare = Context.getIntegerTypeOrder(lhs, rhs);
232 bool lhsSigned = lhs->isSignedIntegerType(),
233 rhsSigned = rhs->isSignedIntegerType();
234 QualType destType;
235 if (lhsSigned == rhsSigned) {
236 // Same signedness; use the higher-ranked type
237 destType = compare >= 0 ? lhs : rhs;
238 } else if (compare != (lhsSigned ? 1 : -1)) {
239 // The unsigned type has greater than or equal rank to the
240 // signed type, so use the unsigned type
241 destType = lhsSigned ? rhs : lhs;
242 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
243 // The two types are different widths; if we are here, that
244 // means the signed type is larger than the unsigned type, so
245 // use the signed type.
246 destType = lhsSigned ? lhs : rhs;
247 } else {
248 // The signed type is higher-ranked than the unsigned type,
249 // but isn't actually any bigger (like unsigned int and long
250 // on most 32-bit systems). Use the unsigned type corresponding
251 // to the signed type.
252 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
253 }
254 if (!isCompAssign) {
255 ImpCastExprToType(lhsExpr, destType);
256 ImpCastExprToType(rhsExpr, destType);
257 }
258 return destType;
259}
260
261//===----------------------------------------------------------------------===//
262// Semantic Analysis for various Expression Types
263//===----------------------------------------------------------------------===//
264
265
Steve Naroff87d58b42007-09-16 03:34:24 +0000266/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000267/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
268/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
269/// multiple tokens. However, the common case is that StringToks points to one
270/// string.
271///
272Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000273Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000274 assert(NumStringToks && "Must have at least one string!");
275
276 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
277 if (Literal.hadError)
278 return ExprResult(true);
279
280 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
281 for (unsigned i = 0; i != NumStringToks; ++i)
282 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000283
284 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000285 if (Literal.Pascal && Literal.GetStringLength() > 256)
286 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
287 SourceRange(StringToks[0].getLocation(),
288 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000289
Chris Lattnera6dcce32008-02-11 00:02:17 +0000290 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000291 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000292 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000293
294 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
295 if (getLangOptions().CPlusPlus)
296 StrTy.addConst();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000297
298 // Get an array type for the string, according to C99 6.4.5. This includes
299 // the nul terminator character as well as the string length for pascal
300 // strings.
301 StrTy = Context.getConstantArrayType(StrTy,
302 llvm::APInt(32, Literal.GetStringLength()+1),
303 ArrayType::Normal, 0);
304
Chris Lattner4b009652007-07-25 00:24:17 +0000305 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
306 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000307 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000308 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000309 StringToks[NumStringToks-1].getLocation());
310}
311
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000312/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
313/// CurBlock to VD should cause it to be snapshotted (as we do for auto
314/// variables defined outside the block) or false if this is not needed (e.g.
315/// for values inside the block or for globals).
316///
317/// FIXME: This will create BlockDeclRefExprs for global variables,
318/// function references, etc which is suboptimal :) and breaks
319/// things like "integer constant expression" tests.
320static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
321 ValueDecl *VD) {
322 // If the value is defined inside the block, we couldn't snapshot it even if
323 // we wanted to.
324 if (CurBlock->TheDecl == VD->getDeclContext())
325 return false;
326
327 // If this is an enum constant or function, it is constant, don't snapshot.
328 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
329 return false;
330
331 // If this is a reference to an extern, static, or global variable, no need to
332 // snapshot it.
333 // FIXME: What about 'const' variables in C++?
334 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
335 return Var->hasLocalStorage();
336
337 return true;
338}
339
340
341
Steve Naroff0acc9c92007-09-15 18:49:24 +0000342/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000343/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000344/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000345Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000346 IdentifierInfo &II,
347 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000348 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +0000349 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000350
351 // If this reference is in an Objective-C method, then ivar lookup happens as
352 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000353 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000354 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000355 // There are two cases to handle here. 1) scoped lookup could have failed,
356 // in which case we should look for an ivar. 2) scoped lookup could have
357 // found a decl, but that decl is outside the current method (i.e. a global
358 // variable). In these two cases, we do a lookup for an ivar with this
359 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000360 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000361 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattnered94f762008-07-21 04:44:44 +0000362 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000363 // FIXME: This should use a new expr for a direct reference, don't turn
364 // this into Self->ivar, just return a BareIVarExpr or something.
365 IdentifierInfo &II = Context.Idents.get("self");
366 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
367 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
368 static_cast<Expr*>(SelfExpr.Val), true, true);
369 }
370 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000371 // Needed to implement property "super.method" notation.
Daniel Dunbar4837ae72008-08-14 22:04:54 +0000372 if (SD == 0 && &II == SuperID) {
Steve Naroff6f786252008-06-02 23:03:37 +0000373 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000374 getCurMethodDecl()->getClassInterface()));
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000375 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroff6f786252008-06-02 23:03:37 +0000376 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000377 }
Chris Lattner4b009652007-07-25 00:24:17 +0000378 if (D == 0) {
379 // Otherwise, this could be an implicitly declared function reference (legal
380 // in C90, extension in C99).
381 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000382 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000383 D = ImplicitlyDefineFunction(Loc, II, S);
384 else {
385 // If this name wasn't predeclared and if this is not a function call,
386 // diagnose the problem.
387 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
388 }
389 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000390
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000391 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
392 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
393 if (MD->isStatic())
394 // "invalid use of member 'x' in static member function"
395 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
396 FD->getName());
397 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
398 // "invalid use of nonstatic data member 'x'"
399 return Diag(Loc, diag::err_invalid_non_static_member_use,
400 FD->getName());
401
402 if (FD->isInvalidDecl())
403 return true;
404
405 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
406 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
407 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
408 true, FD, Loc, FD->getType());
409 }
410
411 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
412 }
Chris Lattner4b009652007-07-25 00:24:17 +0000413 if (isa<TypedefDecl>(D))
414 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000415 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000416 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000417 if (isa<NamespaceDecl>(D))
418 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000419
Steve Naroffd6163f32008-09-05 22:11:13 +0000420 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000421 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
422 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
423
Steve Naroffd6163f32008-09-05 22:11:13 +0000424 ValueDecl *VD = cast<ValueDecl>(D);
425
426 // check if referencing an identifier with __attribute__((deprecated)).
427 if (VD->getAttr<DeprecatedAttr>())
428 Diag(Loc, diag::warn_deprecated, VD->getName());
429
430 // Only create DeclRefExpr's for valid Decl's.
431 if (VD->isInvalidDecl())
432 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000433
434 // If the identifier reference is inside a block, and it refers to a value
435 // that is outside the block, create a BlockDeclRefExpr instead of a
436 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
437 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000438 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000439 // We do not do this for things like enum constants, global variables, etc,
440 // as they do not get snapshotted.
441 //
442 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000443 // The BlocksAttr indicates the variable is bound by-reference.
444 if (VD->getAttr<BlocksAttr>())
445 return new BlockDeclRefExpr(VD, VD->getType(), Loc, true);
446
447 // Variable will be bound by-copy, make it const within the closure.
448 VD->getType().addConst();
449 return new BlockDeclRefExpr(VD, VD->getType(), Loc, false);
450 }
451 // If this reference is not in a block or if the referenced variable is
452 // within the block, create a normal DeclRefExpr.
Douglas Gregor3fb675a2008-10-22 04:14:44 +0000453 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Chris Lattner4b009652007-07-25 00:24:17 +0000454}
455
Chris Lattner69909292008-08-10 01:53:14 +0000456Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000457 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000458 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000459
460 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000461 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000462 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
463 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
464 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000465 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000466
467 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000468 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000469 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000470
Chris Lattner7e637512008-01-12 08:14:25 +0000471 // Pre-defined identifiers are of type char[x], where x is the length of the
472 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000473 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000474 if (getCurFunctionDecl())
475 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000476 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000477 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000478
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000479 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000480 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000481 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000482 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000483}
484
Steve Naroff87d58b42007-09-16 03:34:24 +0000485Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000486 llvm::SmallString<16> CharBuffer;
487 CharBuffer.resize(Tok.getLength());
488 const char *ThisTokBegin = &CharBuffer[0];
489 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
490
491 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
492 Tok.getLocation(), PP);
493 if (Literal.hadError())
494 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000495
496 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
497
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000498 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
499 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000500}
501
Steve Naroff87d58b42007-09-16 03:34:24 +0000502Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000503 // fast path for a single digit (which is quite common). A single digit
504 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
505 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000506 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000507
Chris Lattner8cd0e932008-03-05 18:54:05 +0000508 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000509 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000510 Context.IntTy,
511 Tok.getLocation()));
512 }
513 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000514 // Add padding so that NumericLiteralParser can overread by one character.
515 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000516 const char *ThisTokBegin = &IntegerBuffer[0];
517
518 // Get the spelling of the token, which eliminates trigraphs, etc.
519 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000520
Chris Lattner4b009652007-07-25 00:24:17 +0000521 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
522 Tok.getLocation(), PP);
523 if (Literal.hadError)
524 return ExprResult(true);
525
Chris Lattner1de66eb2007-08-26 03:42:43 +0000526 Expr *Res;
527
528 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000529 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000530 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000531 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000532 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000533 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000534 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000535 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000536
537 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
538
Ted Kremenekddedbe22007-11-29 00:56:49 +0000539 // isExact will be set by GetFloatValue().
540 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000541 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000542 Ty, Tok.getLocation());
543
Chris Lattner1de66eb2007-08-26 03:42:43 +0000544 } else if (!Literal.isIntegerLiteral()) {
545 return ExprResult(true);
546 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000547 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000548
Neil Booth7421e9c2007-08-29 22:00:19 +0000549 // long long is a C99 feature.
550 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000551 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000552 Diag(Tok.getLocation(), diag::ext_longlong);
553
Chris Lattner4b009652007-07-25 00:24:17 +0000554 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000555 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000556
557 if (Literal.GetIntegerValue(ResultVal)) {
558 // If this value didn't fit into uintmax_t, warn and force to ull.
559 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000560 Ty = Context.UnsignedLongLongTy;
561 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000562 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000563 } else {
564 // If this value fits into a ULL, try to figure out what else it fits into
565 // according to the rules of C99 6.4.4.1p5.
566
567 // Octal, Hexadecimal, and integers with a U suffix are allowed to
568 // be an unsigned int.
569 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
570
571 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000572 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000573 if (!Literal.isLong && !Literal.isLongLong) {
574 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000575 unsigned IntSize = Context.Target.getIntWidth();
576
Chris Lattner4b009652007-07-25 00:24:17 +0000577 // Does it fit in a unsigned int?
578 if (ResultVal.isIntN(IntSize)) {
579 // Does it fit in a signed int?
580 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000581 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000582 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000583 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000584 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000585 }
Chris Lattner4b009652007-07-25 00:24:17 +0000586 }
587
588 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000589 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000590 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000591
592 // Does it fit in a unsigned long?
593 if (ResultVal.isIntN(LongSize)) {
594 // Does it fit in a signed long?
595 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000596 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000597 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000598 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000599 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000600 }
Chris Lattner4b009652007-07-25 00:24:17 +0000601 }
602
603 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000604 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000605 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000606
607 // Does it fit in a unsigned long long?
608 if (ResultVal.isIntN(LongLongSize)) {
609 // Does it fit in a signed long long?
610 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000611 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000612 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000613 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000614 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000615 }
616 }
617
618 // If we still couldn't decide a type, we probably have something that
619 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000620 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000621 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000622 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000623 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000624 }
Chris Lattnere4068872008-05-09 05:59:00 +0000625
626 if (ResultVal.getBitWidth() != Width)
627 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000628 }
629
Chris Lattner48d7f382008-04-02 04:24:33 +0000630 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000631 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000632
633 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
634 if (Literal.isImaginary)
635 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
636
637 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000638}
639
Steve Naroff87d58b42007-09-16 03:34:24 +0000640Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000641 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000642 Expr *E = (Expr *)Val;
643 assert((E != 0) && "ActOnParenExpr() missing expr");
644 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000645}
646
647/// The UsualUnaryConversions() function is *not* called by this routine.
648/// See C99 6.3.2.1p[2-4] for more details.
649QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerf814d882008-07-25 21:45:37 +0000650 SourceLocation OpLoc,
651 const SourceRange &ExprRange,
652 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000653 // C99 6.5.3.4p1:
654 if (isa<FunctionType>(exprType) && isSizeof)
655 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000656 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000657 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000658 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
659 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000660 else if (exprType->isIncompleteType()) {
661 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
662 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000663 exprType.getAsString(), ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000664 return QualType(); // error
665 }
666 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
667 return Context.getSizeType();
668}
669
670Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000671ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000672 SourceLocation LPLoc, TypeTy *Ty,
673 SourceLocation RPLoc) {
674 // If error parsing type, ignore.
675 if (Ty == 0) return true;
676
677 // Verify that this is a valid expression.
678 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
679
Chris Lattnerf814d882008-07-25 21:45:37 +0000680 QualType resultType =
681 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Chris Lattner4b009652007-07-25 00:24:17 +0000682
683 if (resultType.isNull())
684 return true;
685 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
686}
687
Chris Lattner5110ad52007-08-24 21:41:10 +0000688QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000689 DefaultFunctionArrayConversion(V);
690
Chris Lattnera16e42d2007-08-26 05:39:26 +0000691 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000692 if (const ComplexType *CT = V->getType()->getAsComplexType())
693 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000694
695 // Otherwise they pass through real integer and floating point types here.
696 if (V->getType()->isArithmeticType())
697 return V->getType();
698
699 // Reject anything else.
700 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
701 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000702}
703
704
Chris Lattner4b009652007-07-25 00:24:17 +0000705
Steve Naroff87d58b42007-09-16 03:34:24 +0000706Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000707 tok::TokenKind Kind,
708 ExprTy *Input) {
709 UnaryOperator::Opcode Opc;
710 switch (Kind) {
711 default: assert(0 && "Unknown unary op!");
712 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
713 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
714 }
715 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
716 if (result.isNull())
717 return true;
718 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
719}
720
721Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000722ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000723 ExprTy *Idx, SourceLocation RLoc) {
724 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
725
726 // Perform default conversions.
727 DefaultFunctionArrayConversion(LHSExp);
728 DefaultFunctionArrayConversion(RHSExp);
729
730 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
731
732 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000733 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000734 // in the subscript position. As a result, we need to derive the array base
735 // and index from the expression types.
736 Expr *BaseExpr, *IndexExpr;
737 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000738 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000739 BaseExpr = LHSExp;
740 IndexExpr = RHSExp;
741 // FIXME: need to deal with const...
742 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000743 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000744 // Handle the uncommon case of "123[Ptr]".
745 BaseExpr = RHSExp;
746 IndexExpr = LHSExp;
747 // FIXME: need to deal with const...
748 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000749 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
750 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000751 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000752
753 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000754 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
755 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000756 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000757 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000758 // FIXME: need to deal with const...
759 ResultType = VTy->getElementType();
760 } else {
761 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
762 RHSExp->getSourceRange());
763 }
764 // C99 6.5.2.1p1
765 if (!IndexExpr->getType()->isIntegerType())
766 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
767 IndexExpr->getSourceRange());
768
769 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
770 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000771 // void (*)(int)) and pointers to incomplete types. Functions are not
772 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000773 if (!ResultType->isObjectType())
774 return Diag(BaseExpr->getLocStart(),
775 diag::err_typecheck_subscript_not_object,
776 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
777
778 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
779}
780
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000781QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000782CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000783 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000784 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000785
786 // This flag determines whether or not the component is to be treated as a
787 // special name, or a regular GLSL-style component access.
788 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000789
790 // The vector accessor can't exceed the number of elements.
791 const char *compStr = CompName.getName();
792 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000793 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000794 baseType.getAsString(), SourceRange(CompLoc));
795 return QualType();
796 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000797
798 // Check that we've found one of the special components, or that the component
799 // names must come from the same set.
800 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
801 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
802 SpecialComponent = true;
803 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000804 do
805 compStr++;
806 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
807 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
808 do
809 compStr++;
810 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
811 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
812 do
813 compStr++;
814 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
815 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000816
Nate Begemanc8e51f82008-05-09 06:41:27 +0000817 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000818 // We didn't get to the end of the string. This means the component names
819 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000820 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000821 std::string(compStr,compStr+1), SourceRange(CompLoc));
822 return QualType();
823 }
824 // Each component accessor can't exceed the vector type.
825 compStr = CompName.getName();
826 while (*compStr) {
827 if (vecType->isAccessorWithinNumElements(*compStr))
828 compStr++;
829 else
830 break;
831 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000832 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000833 // We didn't get to the end of the string. This means a component accessor
834 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000835 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000836 baseType.getAsString(), SourceRange(CompLoc));
837 return QualType();
838 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000839
840 // If we have a special component name, verify that the current vector length
841 // is an even number, since all special component names return exactly half
842 // the elements.
843 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Daniel Dunbar45a91802008-09-30 17:22:47 +0000844 Diag(OpLoc, diag::err_ext_vector_component_requires_even,
845 baseType.getAsString(), SourceRange(CompLoc));
Nate Begemanc8e51f82008-05-09 06:41:27 +0000846 return QualType();
847 }
848
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000849 // The component accessor looks fine - now we need to compute the actual type.
850 // The vector type is implied by the component accessor. For example,
851 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000852 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
853 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
854 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000855 if (CompSize == 1)
856 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000857
Nate Begemanaf6ed502008-04-18 23:10:10 +0000858 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000859 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000860 // diagostics look bad. We want extended vector types to appear built-in.
861 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
862 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
863 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000864 }
865 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000866}
867
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000868/// constructSetterName - Return the setter name for the given
869/// identifier, i.e. "set" + Name where the initial character of Name
870/// has been capitalized.
871// FIXME: Merge with same routine in Parser. But where should this
872// live?
873static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
874 const IdentifierInfo *Name) {
875 unsigned N = Name->getLength();
876 char *SelectorName = new char[3 + N];
877 memcpy(SelectorName, "set", 3);
878 memcpy(&SelectorName[3], Name->getName(), N);
879 SelectorName[3] = toupper(SelectorName[3]);
880
881 IdentifierInfo *Setter =
882 &Idents.get(SelectorName, &SelectorName[3 + N]);
883 delete[] SelectorName;
884 return Setter;
885}
886
Chris Lattner4b009652007-07-25 00:24:17 +0000887Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000888ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000889 tok::TokenKind OpKind, SourceLocation MemberLoc,
890 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000891 Expr *BaseExpr = static_cast<Expr *>(Base);
892 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000893
894 // Perform default conversions.
895 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000896
Steve Naroff2cb66382007-07-26 03:11:44 +0000897 QualType BaseType = BaseExpr->getType();
898 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000899
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000900 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
901 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000902 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000903 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000904 BaseType = PT->getPointeeType();
905 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000906 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
907 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000908 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000909
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000910 // Handle field access to simple records. This also handles access to fields
911 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000912 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000913 RecordDecl *RDecl = RTy->getDecl();
914 if (RTy->isIncompleteType())
915 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
916 BaseExpr->getSourceRange());
917 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000918 FieldDecl *MemberDecl = RDecl->getMember(&Member);
919 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000920 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
921 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000922
923 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000924 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000925 QualType MemberType = MemberDecl->getType();
926 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000927 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000928 MemberType = MemberType.getQualifiedType(combinedQualifiers);
929
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000930 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000931 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000932 }
933
Chris Lattnere9d71612008-07-21 04:59:05 +0000934 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
935 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000936 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
937 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000938 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000939 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000940 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000941 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000942 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000943 }
944
Chris Lattnere9d71612008-07-21 04:59:05 +0000945 // Handle Objective-C property access, which is "Obj.property" where Obj is a
946 // pointer to a (potentially qualified) interface type.
947 const PointerType *PTy;
948 const ObjCInterfaceType *IFTy;
949 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
950 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
951 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +0000952
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000953 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +0000954 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
955 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
956
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000957 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000958 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
959 E = IFTy->qual_end(); I != E; ++I)
960 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
961 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000962
963 // If that failed, look for an "implicit" property by seeing if the nullary
964 // selector is implemented.
965
966 // FIXME: The logic for looking up nullary and unary selectors should be
967 // shared with the code in ActOnInstanceMessage.
968
969 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
970 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
971
972 // If this reference is in an @implementation, check for 'private' methods.
973 if (!Getter)
974 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
975 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
976 if (ObjCImplementationDecl *ImpDecl =
977 ObjCImplementations[ClassDecl->getIdentifier()])
978 Getter = ImpDecl->getInstanceMethod(Sel);
979
Steve Naroff04151f32008-10-22 19:16:27 +0000980 // Look through local category implementations associated with the class.
981 if (!Getter) {
982 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
983 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
984 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
985 }
986 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000987 if (Getter) {
988 // If we found a getter then this may be a valid dot-reference, we
989 // need to also look for the matching setter.
990 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
991 &Member);
992 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
993 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
994
995 if (!Setter) {
996 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
997 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
998 if (ObjCImplementationDecl *ImpDecl =
999 ObjCImplementations[ClassDecl->getIdentifier()])
1000 Setter = ImpDecl->getInstanceMethod(SetterSel);
1001 }
1002
1003 // FIXME: There are some issues here. First, we are not
1004 // diagnosing accesses to read-only properties because we do not
1005 // know if this is a getter or setter yet. Second, we are
1006 // checking that the type of the setter matches the type we
1007 // expect.
1008 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1009 MemberLoc, BaseExpr);
1010 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001011 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001012 // Handle properties on qualified "id" protocols.
1013 const ObjCQualifiedIdType *QIdTy;
1014 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1015 // Check protocols on qualified interfaces.
1016 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1017 E = QIdTy->qual_end(); I != E; ++I)
1018 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1019 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1020 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001021 // Handle 'field access' to vectors, such as 'V.xx'.
1022 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1023 // Component access limited to variables (reject vec4.rg.g).
1024 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1025 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +00001026 return Diag(MemberLoc, diag::err_ext_vector_component_access,
1027 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001028 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1029 if (ret.isNull())
1030 return true;
1031 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1032 }
1033
Chris Lattner7d5a8762008-07-21 05:35:34 +00001034 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1035 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001036}
1037
Steve Naroff87d58b42007-09-16 03:34:24 +00001038/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001039/// This provides the location of the left/right parens and a list of comma
1040/// locations.
1041Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001042ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001043 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001044 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1045 Expr *Fn = static_cast<Expr *>(fn);
1046 Expr **Args = reinterpret_cast<Expr**>(args);
1047 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001048 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001049 OverloadedFunctionDecl *Ovl = NULL;
1050
1051 // If we're directly calling a function or a set of overloaded
1052 // functions, get the appropriate declaration.
1053 {
1054 DeclRefExpr *DRExpr = NULL;
1055 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1056 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1057 else
1058 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1059
1060 if (DRExpr) {
1061 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1062 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1063 }
1064 }
1065
1066 // If we have a set of overloaded functions, perform overload
1067 // resolution to pick the function.
1068 if (Ovl) {
1069 OverloadCandidateSet CandidateSet;
1070 OverloadCandidateSet::iterator Best;
1071 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
1072 switch (BestViableFunction(CandidateSet, Best)) {
1073 case OR_Success:
1074 {
1075 // Success! Let the remainder of this function build a call to
1076 // the function selected by overload resolution.
1077 FDecl = Best->Function;
1078 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1079 Fn->getSourceRange().getBegin());
1080 delete Fn;
1081 Fn = NewFn;
1082 }
1083 break;
1084
1085 case OR_No_Viable_Function:
1086 if (CandidateSet.empty())
1087 Diag(Fn->getSourceRange().getBegin(),
1088 diag::err_ovl_no_viable_function_in_call, Ovl->getName(),
1089 Fn->getSourceRange());
1090 else {
1091 Diag(Fn->getSourceRange().getBegin(),
1092 diag::err_ovl_no_viable_function_in_call_with_cands,
1093 Ovl->getName(), Fn->getSourceRange());
1094 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1095 }
1096 return true;
1097
1098 case OR_Ambiguous:
1099 Diag(Fn->getSourceRange().getBegin(),
1100 diag::err_ovl_ambiguous_call, Ovl->getName(),
1101 Fn->getSourceRange());
1102 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1103 return true;
1104 }
1105 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001106
1107 // Promote the function operand.
1108 UsualUnaryConversions(Fn);
1109
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001110 // Make the call expr early, before semantic checks. This guarantees cleanup
1111 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001112 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001113 Context.BoolTy, RParenLoc));
Steve Naroffd6163f32008-09-05 22:11:13 +00001114 const FunctionType *FuncT;
1115 if (!Fn->getType()->isBlockPointerType()) {
1116 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1117 // have type pointer to function".
1118 const PointerType *PT = Fn->getType()->getAsPointerType();
1119 if (PT == 0)
1120 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1121 Fn->getSourceRange());
1122 FuncT = PT->getPointeeType()->getAsFunctionType();
1123 } else { // This is a block call.
1124 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1125 getAsFunctionType();
1126 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001127 if (FuncT == 0)
Chris Lattner61000b12008-08-14 04:33:24 +00001128 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1129 Fn->getSourceRange());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001130
1131 // We know the result type of the call, set it.
1132 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +00001133
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001134 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001135 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1136 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001137 unsigned NumArgsInProto = Proto->getNumArgs();
1138 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001139
Chris Lattner3e254fb2008-04-08 04:40:51 +00001140 // If too few arguments are available (and we don't have default
1141 // arguments for the remaining parameters), don't make the call.
1142 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +00001143 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001144 // Use default arguments for missing arguments
1145 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +00001146 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001147 } else
Steve Naroffd6163f32008-09-05 22:11:13 +00001148 return Diag(RParenLoc,
1149 !Fn->getType()->isBlockPointerType()
1150 ? diag::err_typecheck_call_too_few_args
1151 : diag::err_typecheck_block_too_few_args,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001152 Fn->getSourceRange());
1153 }
1154
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001155 // If too many are passed and not variadic, error on the extras and drop
1156 // them.
1157 if (NumArgs > NumArgsInProto) {
1158 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001159 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffd6163f32008-09-05 22:11:13 +00001160 !Fn->getType()->isBlockPointerType()
1161 ? diag::err_typecheck_call_too_many_args
1162 : diag::err_typecheck_block_too_many_args,
1163 Fn->getSourceRange(),
Chris Lattner4b009652007-07-25 00:24:17 +00001164 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001165 Args[NumArgs-1]->getLocEnd()));
1166 // This deletes the extra arguments.
1167 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001168 }
1169 NumArgsToCheck = NumArgsInProto;
1170 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001171
Chris Lattner4b009652007-07-25 00:24:17 +00001172 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001173 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001174 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001175
1176 Expr *Arg;
1177 if (i < NumArgs)
1178 Arg = Args[i];
1179 else
1180 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001181 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001182
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001183 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +00001184 AssignConvertType ConvTy =
1185 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001186 TheCall->setArg(i, Arg);
Eli Friedman583c31e2008-09-02 05:09:35 +00001187
Chris Lattner005ed752008-01-04 18:04:52 +00001188 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1189 ArgType, Arg, "passing"))
1190 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001191 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001192
1193 // If this is a variadic call, handle args passed through "...".
1194 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001195 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001196 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1197 Expr *Arg = Args[i];
1198 DefaultArgumentPromotion(Arg);
1199 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001200 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001201 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001202 } else {
1203 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1204
Steve Naroffdb65e052007-08-28 23:30:39 +00001205 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001206 for (unsigned i = 0; i != NumArgs; i++) {
1207 Expr *Arg = Args[i];
1208 DefaultArgumentPromotion(Arg);
1209 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001210 }
Chris Lattner4b009652007-07-25 00:24:17 +00001211 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001212
Chris Lattner2e64c072007-08-10 20:18:51 +00001213 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001214 if (FDecl)
1215 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001216
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001217 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001218}
1219
1220Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001221ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001222 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001223 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001224 QualType literalType = QualType::getFromOpaquePtr(Ty);
1225 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001226 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001227 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001228
Eli Friedman8c2173d2008-05-20 05:22:08 +00001229 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001230 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001231 return Diag(LParenLoc,
1232 diag::err_variable_object_no_init,
1233 SourceRange(LParenLoc,
1234 literalExpr->getSourceRange().getEnd()));
1235 } else if (literalType->isIncompleteType()) {
1236 return Diag(LParenLoc,
1237 diag::err_typecheck_decl_incomplete_type,
1238 literalType.getAsString(),
1239 SourceRange(LParenLoc,
1240 literalExpr->getSourceRange().getEnd()));
1241 }
1242
Steve Narofff0b23542008-01-10 22:15:12 +00001243 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +00001244 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001245
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001246 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001247 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001248 if (CheckForConstantInitializer(literalExpr, literalType))
1249 return true;
1250 }
Steve Naroffbe37fc02008-01-14 18:19:28 +00001251 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001252}
1253
1254Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001255ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001256 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001257 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001258
Steve Naroff0acc9c92007-09-15 18:49:24 +00001259 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001260 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001261
Chris Lattner48d7f382008-04-02 04:24:33 +00001262 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1263 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1264 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001265}
1266
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001267/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001268bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001269 UsualUnaryConversions(castExpr);
1270
1271 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1272 // type needs to be scalar.
1273 if (castType->isVoidType()) {
1274 // Cast to void allows any expr type.
1275 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1276 // GCC struct/union extension: allow cast to self.
1277 if (Context.getCanonicalType(castType) !=
1278 Context.getCanonicalType(castExpr->getType()) ||
1279 (!castType->isStructureType() && !castType->isUnionType())) {
1280 // Reject any other conversions to non-scalar types.
1281 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1282 castType.getAsString(), castExpr->getSourceRange());
1283 }
1284
1285 // accept this, but emit an ext-warn.
1286 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1287 castType.getAsString(), castExpr->getSourceRange());
1288 } else if (!castExpr->getType()->isScalarType() &&
1289 !castExpr->getType()->isVectorType()) {
1290 return Diag(castExpr->getLocStart(),
1291 diag::err_typecheck_expect_scalar_operand,
1292 castExpr->getType().getAsString(),castExpr->getSourceRange());
1293 } else if (castExpr->getType()->isVectorType()) {
1294 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1295 return true;
1296 } else if (castType->isVectorType()) {
1297 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1298 return true;
1299 }
1300 return false;
1301}
1302
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001303bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001304 assert(VectorTy->isVectorType() && "Not a vector type!");
1305
1306 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001307 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001308 return Diag(R.getBegin(),
1309 Ty->isVectorType() ?
1310 diag::err_invalid_conversion_between_vectors :
1311 diag::err_invalid_conversion_between_vector_and_integer,
1312 VectorTy.getAsString().c_str(),
1313 Ty.getAsString().c_str(), R);
1314 } else
1315 return Diag(R.getBegin(),
1316 diag::err_invalid_conversion_between_vector_and_scalar,
1317 VectorTy.getAsString().c_str(),
1318 Ty.getAsString().c_str(), R);
1319
1320 return false;
1321}
1322
Chris Lattner4b009652007-07-25 00:24:17 +00001323Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001324ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001325 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001326 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001327
1328 Expr *castExpr = static_cast<Expr*>(Op);
1329 QualType castType = QualType::getFromOpaquePtr(Ty);
1330
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001331 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1332 return true;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001333 return new ExplicitCastExpr(castType, castExpr, LParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001334}
1335
Chris Lattner98a425c2007-11-26 01:40:58 +00001336/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1337/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001338inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1339 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1340 UsualUnaryConversions(cond);
1341 UsualUnaryConversions(lex);
1342 UsualUnaryConversions(rex);
1343 QualType condT = cond->getType();
1344 QualType lexT = lex->getType();
1345 QualType rexT = rex->getType();
1346
1347 // first, check the condition.
1348 if (!condT->isScalarType()) { // C99 6.5.15p2
1349 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1350 condT.getAsString());
1351 return QualType();
1352 }
Chris Lattner992ae932008-01-06 22:42:25 +00001353
1354 // Now check the two expressions.
1355
1356 // If both operands have arithmetic type, do the usual arithmetic conversions
1357 // to find a common type: C99 6.5.15p3,5.
1358 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001359 UsualArithmeticConversions(lex, rex);
1360 return lex->getType();
1361 }
Chris Lattner992ae932008-01-06 22:42:25 +00001362
1363 // If both operands are the same structure or union type, the result is that
1364 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001365 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001366 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001367 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001368 // "If both the operands have structure or union type, the result has
1369 // that type." This implies that CV qualifiers are dropped.
1370 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001371 }
Chris Lattner992ae932008-01-06 22:42:25 +00001372
1373 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001374 // The following || allows only one side to be void (a GCC-ism).
1375 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001376 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001377 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1378 rex->getSourceRange());
1379 if (!rexT->isVoidType())
1380 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001381 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001382 ImpCastExprToType(lex, Context.VoidTy);
1383 ImpCastExprToType(rex, Context.VoidTy);
1384 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001385 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001386 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1387 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001388 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1389 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001390 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001391 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001392 return lexT;
1393 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001394 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1395 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001396 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001397 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001398 return rexT;
1399 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001400 // Handle the case where both operands are pointers before we handle null
1401 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001402 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1403 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1404 // get the "pointed to" types
1405 QualType lhptee = LHSPT->getPointeeType();
1406 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001407
Chris Lattner71225142007-07-31 21:27:01 +00001408 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1409 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001410 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001411 // Figure out necessary qualifiers (C99 6.5.15p6)
1412 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001413 QualType destType = Context.getPointerType(destPointee);
1414 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1415 ImpCastExprToType(rex, destType); // promote to void*
1416 return destType;
1417 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001418 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001419 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001420 QualType destType = Context.getPointerType(destPointee);
1421 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1422 ImpCastExprToType(rex, destType); // promote to void*
1423 return destType;
1424 }
Chris Lattner4b009652007-07-25 00:24:17 +00001425
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001426 QualType compositeType = lexT;
1427
1428 // If either type is an Objective-C object type then check
1429 // compatibility according to Objective-C.
1430 if (Context.isObjCObjectPointerType(lexT) ||
1431 Context.isObjCObjectPointerType(rexT)) {
1432 // If both operands are interfaces and either operand can be
1433 // assigned to the other, use that type as the composite
1434 // type. This allows
1435 // xxx ? (A*) a : (B*) b
1436 // where B is a subclass of A.
1437 //
1438 // Additionally, as for assignment, if either type is 'id'
1439 // allow silent coercion. Finally, if the types are
1440 // incompatible then make sure to use 'id' as the composite
1441 // type so the result is acceptable for sending messages to.
1442
1443 // FIXME: This code should not be localized to here. Also this
1444 // should use a compatible check instead of abusing the
1445 // canAssignObjCInterfaces code.
1446 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1447 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1448 if (LHSIface && RHSIface &&
1449 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1450 compositeType = lexT;
1451 } else if (LHSIface && RHSIface &&
1452 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1453 compositeType = rexT;
1454 } else if (Context.isObjCIdType(lhptee) ||
1455 Context.isObjCIdType(rhptee)) {
1456 // FIXME: This code looks wrong, because isObjCIdType checks
1457 // the struct but getObjCIdType returns the pointer to
1458 // struct. This is horrible and should be fixed.
1459 compositeType = Context.getObjCIdType();
1460 } else {
1461 QualType incompatTy = Context.getObjCIdType();
1462 ImpCastExprToType(lex, incompatTy);
1463 ImpCastExprToType(rex, incompatTy);
1464 return incompatTy;
1465 }
1466 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1467 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001468 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001469 lexT.getAsString(), rexT.getAsString(),
1470 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001471 // In this situation, we assume void* type. No especially good
1472 // reason, but this is what gcc does, and we do have to pick
1473 // to get a consistent AST.
1474 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001475 ImpCastExprToType(lex, incompatTy);
1476 ImpCastExprToType(rex, incompatTy);
1477 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001478 }
1479 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001480 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1481 // differently qualified versions of compatible types, the result type is
1482 // a pointer to an appropriately qualified version of the *composite*
1483 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001484 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001485 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001486 ImpCastExprToType(lex, compositeType);
1487 ImpCastExprToType(rex, compositeType);
1488 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001489 }
Chris Lattner4b009652007-07-25 00:24:17 +00001490 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001491 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1492 // evaluates to "struct objc_object *" (and is handled above when comparing
1493 // id with statically typed objects).
1494 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1495 // GCC allows qualified id and any Objective-C type to devolve to
1496 // id. Currently localizing to here until clear this should be
1497 // part of ObjCQualifiedIdTypesAreCompatible.
1498 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1499 (lexT->isObjCQualifiedIdType() &&
1500 Context.isObjCObjectPointerType(rexT)) ||
1501 (rexT->isObjCQualifiedIdType() &&
1502 Context.isObjCObjectPointerType(lexT))) {
1503 // FIXME: This is not the correct composite type. This only
1504 // happens to work because id can more or less be used anywhere,
1505 // however this may change the type of method sends.
1506 // FIXME: gcc adds some type-checking of the arguments and emits
1507 // (confusing) incompatible comparison warnings in some
1508 // cases. Investigate.
1509 QualType compositeType = Context.getObjCIdType();
1510 ImpCastExprToType(lex, compositeType);
1511 ImpCastExprToType(rex, compositeType);
1512 return compositeType;
1513 }
1514 }
1515
Steve Naroff3eac7692008-09-10 19:17:48 +00001516 // Selection between block pointer types is ok as long as they are the same.
1517 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1518 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1519 return lexT;
1520
Chris Lattner992ae932008-01-06 22:42:25 +00001521 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001522 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1523 lexT.getAsString(), rexT.getAsString(),
1524 lex->getSourceRange(), rex->getSourceRange());
1525 return QualType();
1526}
1527
Steve Naroff87d58b42007-09-16 03:34:24 +00001528/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001529/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001530Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001531 SourceLocation ColonLoc,
1532 ExprTy *Cond, ExprTy *LHS,
1533 ExprTy *RHS) {
1534 Expr *CondExpr = (Expr *) Cond;
1535 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001536
1537 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1538 // was the condition.
1539 bool isLHSNull = LHSExpr == 0;
1540 if (isLHSNull)
1541 LHSExpr = CondExpr;
1542
Chris Lattner4b009652007-07-25 00:24:17 +00001543 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1544 RHSExpr, QuestionLoc);
1545 if (result.isNull())
1546 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001547 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1548 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001549}
1550
Chris Lattner4b009652007-07-25 00:24:17 +00001551
1552// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1553// being closely modeled after the C99 spec:-). The odd characteristic of this
1554// routine is it effectively iqnores the qualifiers on the top level pointee.
1555// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1556// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001557Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001558Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1559 QualType lhptee, rhptee;
1560
1561 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001562 lhptee = lhsType->getAsPointerType()->getPointeeType();
1563 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001564
1565 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001566 lhptee = Context.getCanonicalType(lhptee);
1567 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001568
Chris Lattner005ed752008-01-04 18:04:52 +00001569 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001570
1571 // C99 6.5.16.1p1: This following citation is common to constraints
1572 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1573 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001574 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001575 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001576 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001577
1578 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1579 // incomplete type and the other is a pointer to a qualified or unqualified
1580 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001581 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001582 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001583 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001584
1585 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001586 assert(rhptee->isFunctionType());
1587 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001588 }
1589
1590 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001591 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001592 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001593
1594 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001595 assert(lhptee->isFunctionType());
1596 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001597 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001598
1599 // Check for ObjC interfaces
1600 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1601 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1602 if (LHSIface && RHSIface &&
1603 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1604 return ConvTy;
1605
1606 // ID acts sort of like void* for ObjC interfaces
1607 if (LHSIface && Context.isObjCIdType(rhptee))
1608 return ConvTy;
1609 if (RHSIface && Context.isObjCIdType(lhptee))
1610 return ConvTy;
1611
Chris Lattner4b009652007-07-25 00:24:17 +00001612 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1613 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001614 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1615 rhptee.getUnqualifiedType()))
1616 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001617 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001618}
1619
Steve Naroff3454b6c2008-09-04 15:10:53 +00001620/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1621/// block pointer types are compatible or whether a block and normal pointer
1622/// are compatible. It is more restrict than comparing two function pointer
1623// types.
1624Sema::AssignConvertType
1625Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1626 QualType rhsType) {
1627 QualType lhptee, rhptee;
1628
1629 // get the "pointed to" type (ignoring qualifiers at the top level)
1630 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1631 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1632
1633 // make sure we operate on the canonical type
1634 lhptee = Context.getCanonicalType(lhptee);
1635 rhptee = Context.getCanonicalType(rhptee);
1636
1637 AssignConvertType ConvTy = Compatible;
1638
1639 // For blocks we enforce that qualifiers are identical.
1640 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1641 ConvTy = CompatiblePointerDiscardsQualifiers;
1642
1643 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1644 return IncompatibleBlockPointer;
1645 return ConvTy;
1646}
1647
Chris Lattner4b009652007-07-25 00:24:17 +00001648/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1649/// has code to accommodate several GCC extensions when type checking
1650/// pointers. Here are some objectionable examples that GCC considers warnings:
1651///
1652/// int a, *pint;
1653/// short *pshort;
1654/// struct foo *pfoo;
1655///
1656/// pint = pshort; // warning: assignment from incompatible pointer type
1657/// a = pint; // warning: assignment makes integer from pointer without a cast
1658/// pint = a; // warning: assignment makes pointer from integer without a cast
1659/// pint = pfoo; // warning: assignment from incompatible pointer type
1660///
1661/// As a result, the code for dealing with pointers is more complex than the
1662/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001663///
Chris Lattner005ed752008-01-04 18:04:52 +00001664Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001665Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001666 // Get canonical types. We're not formatting these types, just comparing
1667 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001668 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1669 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001670
1671 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001672 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001673
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001674 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001675 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001676 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001677 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001678 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001679
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001680 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1681 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001682 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001683 // Relax integer conversions like we do for pointers below.
1684 if (rhsType->isIntegerType())
1685 return IntToPointer;
1686 if (lhsType->isIntegerType())
1687 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00001688 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001689 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001690
Nate Begemanc5f0f652008-07-14 18:02:46 +00001691 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001692 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001693 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1694 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001695 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001696
Nate Begemanc5f0f652008-07-14 18:02:46 +00001697 // If we are allowing lax vector conversions, and LHS and RHS are both
1698 // vectors, the total size only needs to be the same. This is a bitcast;
1699 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001700 if (getLangOptions().LaxVectorConversions &&
1701 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001702 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1703 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001704 }
1705 return Incompatible;
1706 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001707
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001708 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001709 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001710
Chris Lattner390564e2008-04-07 06:49:41 +00001711 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001712 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001713 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001714
Chris Lattner390564e2008-04-07 06:49:41 +00001715 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001716 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001717
Steve Naroffa982c712008-09-29 18:10:17 +00001718 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00001719 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff3454b6c2008-09-04 15:10:53 +00001720 return BlockVoidPointer;
Steve Naroffa982c712008-09-29 18:10:17 +00001721
1722 // Treat block pointers as objects.
1723 if (getLangOptions().ObjC1 &&
1724 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1725 return Compatible;
1726 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001727 return Incompatible;
1728 }
1729
1730 if (isa<BlockPointerType>(lhsType)) {
1731 if (rhsType->isIntegerType())
1732 return IntToPointer;
1733
Steve Naroffa982c712008-09-29 18:10:17 +00001734 // Treat block pointers as objects.
1735 if (getLangOptions().ObjC1 &&
1736 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1737 return Compatible;
1738
Steve Naroff3454b6c2008-09-04 15:10:53 +00001739 if (rhsType->isBlockPointerType())
1740 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1741
1742 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1743 if (RHSPT->getPointeeType()->isVoidType())
1744 return BlockVoidPointer;
1745 }
Chris Lattner1853da22008-01-04 23:18:45 +00001746 return Incompatible;
1747 }
1748
Chris Lattner390564e2008-04-07 06:49:41 +00001749 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001750 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001751 if (lhsType == Context.BoolTy)
1752 return Compatible;
1753
1754 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001755 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001756
Chris Lattner390564e2008-04-07 06:49:41 +00001757 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001758 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001759
1760 if (isa<BlockPointerType>(lhsType) &&
1761 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1762 return BlockVoidPointer;
Chris Lattner1853da22008-01-04 23:18:45 +00001763 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001764 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001765
Chris Lattner1853da22008-01-04 23:18:45 +00001766 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001767 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001768 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001769 }
1770 return Incompatible;
1771}
1772
Chris Lattner005ed752008-01-04 18:04:52 +00001773Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001774Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001775 if (getLangOptions().CPlusPlus) {
1776 if (!lhsType->isRecordType()) {
1777 // C++ 5.17p3: If the left operand is not of class type, the
1778 // expression is implicitly converted (C++ 4) to the
1779 // cv-unqualified type of the left operand.
1780 ImplicitConversionSequence ICS
1781 = TryCopyInitialization(rExpr, lhsType.getUnqualifiedType());
1782 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
1783 // No implicit conversion available; we cannot perform this
1784 // assignment.
1785 return Incompatible;
1786 } else {
1787 // Perform the appropriate cast to the right-handle side.
1788 ImpCastExprToType(rExpr, lhsType.getUnqualifiedType());
1789 return Compatible;
1790 }
1791 }
1792
1793 // FIXME: Currently, we fall through and treat C++ classes like C
1794 // structures.
1795 }
1796
Steve Naroffcdee22d2007-11-27 17:58:44 +00001797 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1798 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00001799 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1800 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001801 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001802 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001803 return Compatible;
1804 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001805
1806 // We don't allow conversion of non-null-pointer constants to integers.
1807 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1808 return IntToBlockPointer;
1809
Chris Lattner5f505bf2007-10-16 02:55:40 +00001810 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001811 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001812 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001813 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001814 //
1815 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1816 // are better understood.
1817 if (!lhsType->isReferenceType())
1818 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001819
Chris Lattner005ed752008-01-04 18:04:52 +00001820 Sema::AssignConvertType result =
1821 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001822
1823 // C99 6.5.16.1p2: The value of the right operand is converted to the
1824 // type of the assignment expression.
1825 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001826 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001827 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001828}
1829
Chris Lattner005ed752008-01-04 18:04:52 +00001830Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001831Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1832 return CheckAssignmentConstraints(lhsType, rhsType);
1833}
1834
Chris Lattner2c8bff72007-12-12 05:47:28 +00001835QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001836 Diag(loc, diag::err_typecheck_invalid_operands,
1837 lex->getType().getAsString(), rex->getType().getAsString(),
1838 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001839 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001840}
1841
1842inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1843 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001844 // For conversion purposes, we ignore any qualifiers.
1845 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001846 QualType lhsType =
1847 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1848 QualType rhsType =
1849 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001850
Nate Begemanc5f0f652008-07-14 18:02:46 +00001851 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001852 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001853 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001854
Nate Begemanc5f0f652008-07-14 18:02:46 +00001855 // Handle the case of a vector & extvector type of the same size and element
1856 // type. It would be nice if we only had one vector type someday.
1857 if (getLangOptions().LaxVectorConversions)
1858 if (const VectorType *LV = lhsType->getAsVectorType())
1859 if (const VectorType *RV = rhsType->getAsVectorType())
1860 if (LV->getElementType() == RV->getElementType() &&
1861 LV->getNumElements() == RV->getNumElements())
1862 return lhsType->isExtVectorType() ? lhsType : rhsType;
1863
1864 // If the lhs is an extended vector and the rhs is a scalar of the same type
1865 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001866 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001867 QualType eltType = V->getElementType();
1868
1869 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1870 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1871 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001872 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001873 return lhsType;
1874 }
1875 }
1876
Nate Begemanc5f0f652008-07-14 18:02:46 +00001877 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001878 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001879 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001880 QualType eltType = V->getElementType();
1881
1882 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1883 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1884 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001885 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001886 return rhsType;
1887 }
1888 }
1889
Chris Lattner4b009652007-07-25 00:24:17 +00001890 // You cannot convert between vector values of different size.
1891 Diag(loc, diag::err_typecheck_vector_not_convertable,
1892 lex->getType().getAsString(), rex->getType().getAsString(),
1893 lex->getSourceRange(), rex->getSourceRange());
1894 return QualType();
1895}
1896
1897inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001898 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001899{
1900 QualType lhsType = lex->getType(), rhsType = rex->getType();
1901
1902 if (lhsType->isVectorType() || rhsType->isVectorType())
1903 return CheckVectorOperands(loc, lex, rex);
1904
Steve Naroff8f708362007-08-24 19:07:16 +00001905 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001906
Chris Lattner4b009652007-07-25 00:24:17 +00001907 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001908 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001909 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001910}
1911
1912inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001913 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001914{
1915 QualType lhsType = lex->getType(), rhsType = rex->getType();
1916
Steve Naroff8f708362007-08-24 19:07:16 +00001917 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001918
Chris Lattner4b009652007-07-25 00:24:17 +00001919 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001920 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001921 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001922}
1923
1924inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001925 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001926{
1927 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1928 return CheckVectorOperands(loc, lex, rex);
1929
Steve Naroff8f708362007-08-24 19:07:16 +00001930 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001931
Chris Lattner4b009652007-07-25 00:24:17 +00001932 // handle the common case first (both operands are arithmetic).
1933 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001934 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001935
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001936 // Put any potential pointer into PExp
1937 Expr* PExp = lex, *IExp = rex;
1938 if (IExp->getType()->isPointerType())
1939 std::swap(PExp, IExp);
1940
1941 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1942 if (IExp->getType()->isIntegerType()) {
1943 // Check for arithmetic on pointers to incomplete types
1944 if (!PTy->getPointeeType()->isObjectType()) {
1945 if (PTy->getPointeeType()->isVoidType()) {
1946 Diag(loc, diag::ext_gnu_void_ptr,
1947 lex->getSourceRange(), rex->getSourceRange());
1948 } else {
1949 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1950 lex->getType().getAsString(), lex->getSourceRange());
1951 return QualType();
1952 }
1953 }
1954 return PExp->getType();
1955 }
1956 }
1957
Chris Lattner2c8bff72007-12-12 05:47:28 +00001958 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001959}
1960
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001961// C99 6.5.6
1962QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1963 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001964 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1965 return CheckVectorOperands(loc, lex, rex);
1966
Steve Naroff8f708362007-08-24 19:07:16 +00001967 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001968
Chris Lattnerf6da2912007-12-09 21:53:25 +00001969 // Enforce type constraints: C99 6.5.6p3.
1970
1971 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001972 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001973 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001974
1975 // Either ptr - int or ptr - ptr.
1976 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001977 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001978
Chris Lattnerf6da2912007-12-09 21:53:25 +00001979 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001980 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001981 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001982 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001983 Diag(loc, diag::ext_gnu_void_ptr,
1984 lex->getSourceRange(), rex->getSourceRange());
1985 } else {
1986 Diag(loc, diag::err_typecheck_sub_ptr_object,
1987 lex->getType().getAsString(), lex->getSourceRange());
1988 return QualType();
1989 }
1990 }
1991
1992 // The result type of a pointer-int computation is the pointer type.
1993 if (rex->getType()->isIntegerType())
1994 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001995
Chris Lattnerf6da2912007-12-09 21:53:25 +00001996 // Handle pointer-pointer subtractions.
1997 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001998 QualType rpointee = RHSPTy->getPointeeType();
1999
Chris Lattnerf6da2912007-12-09 21:53:25 +00002000 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002001 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002002 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002003 if (rpointee->isVoidType()) {
2004 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00002005 Diag(loc, diag::ext_gnu_void_ptr,
2006 lex->getSourceRange(), rex->getSourceRange());
2007 } else {
2008 Diag(loc, diag::err_typecheck_sub_ptr_object,
2009 rex->getType().getAsString(), rex->getSourceRange());
2010 return QualType();
2011 }
2012 }
2013
2014 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002015 if (!Context.typesAreCompatible(
2016 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2017 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002018 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
2019 lex->getType().getAsString(), rex->getType().getAsString(),
2020 lex->getSourceRange(), rex->getSourceRange());
2021 return QualType();
2022 }
2023
2024 return Context.getPointerDiffType();
2025 }
2026 }
2027
Chris Lattner2c8bff72007-12-12 05:47:28 +00002028 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002029}
2030
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002031// C99 6.5.7
2032QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2033 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002034 // C99 6.5.7p2: Each of the operands shall have integer type.
2035 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
2036 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002037
Chris Lattner2c8bff72007-12-12 05:47:28 +00002038 // Shifts don't perform usual arithmetic conversions, they just do integer
2039 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002040 if (!isCompAssign)
2041 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002042 UsualUnaryConversions(rex);
2043
2044 // "The type of the result is that of the promoted left operand."
2045 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002046}
2047
Eli Friedman0d9549b2008-08-22 00:56:42 +00002048static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2049 ASTContext& Context) {
2050 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2051 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2052 // ID acts sort of like void* for ObjC interfaces
2053 if (LHSIface && Context.isObjCIdType(RHS))
2054 return true;
2055 if (RHSIface && Context.isObjCIdType(LHS))
2056 return true;
2057 if (!LHSIface || !RHSIface)
2058 return false;
2059 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2060 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2061}
2062
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002063// C99 6.5.8
2064QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2065 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002066 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2067 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
2068
Chris Lattner254f3bc2007-08-26 01:18:55 +00002069 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002070 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2071 UsualArithmeticConversions(lex, rex);
2072 else {
2073 UsualUnaryConversions(lex);
2074 UsualUnaryConversions(rex);
2075 }
Chris Lattner4b009652007-07-25 00:24:17 +00002076 QualType lType = lex->getType();
2077 QualType rType = rex->getType();
2078
Ted Kremenek486509e2007-10-29 17:13:39 +00002079 // For non-floating point types, check for self-comparisons of the form
2080 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2081 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002082 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002083 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2084 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002085 if (DRL->getDecl() == DRR->getDecl())
2086 Diag(loc, diag::warn_selfcomparison);
2087 }
2088
Chris Lattner254f3bc2007-08-26 01:18:55 +00002089 if (isRelational) {
2090 if (lType->isRealType() && rType->isRealType())
2091 return Context.IntTy;
2092 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002093 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002094 if (lType->isFloatingType()) {
2095 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00002096 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002097 }
2098
Chris Lattner254f3bc2007-08-26 01:18:55 +00002099 if (lType->isArithmeticType() && rType->isArithmeticType())
2100 return Context.IntTy;
2101 }
Chris Lattner4b009652007-07-25 00:24:17 +00002102
Chris Lattner22be8422007-08-26 01:10:14 +00002103 bool LHSIsNull = lex->isNullPointerConstant(Context);
2104 bool RHSIsNull = rex->isNullPointerConstant(Context);
2105
Chris Lattner254f3bc2007-08-26 01:18:55 +00002106 // All of the following pointer related warnings are GCC extensions, except
2107 // when handling null pointer constants. One day, we can consider making them
2108 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002109 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002110 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002111 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002112 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002113 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002114
Steve Naroff3b435622007-11-13 14:57:38 +00002115 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002116 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2117 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002118 RCanPointeeTy.getUnqualifiedType()) &&
2119 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroff4462cb02007-08-16 21:48:38 +00002120 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2121 lType.getAsString(), rType.getAsString(),
2122 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002123 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002124 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002125 return Context.IntTy;
2126 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002127 // Handle block pointer types.
2128 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2129 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2130 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2131
2132 if (!LHSIsNull && !RHSIsNull &&
2133 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2134 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2135 lType.getAsString(), rType.getAsString(),
2136 lex->getSourceRange(), rex->getSourceRange());
2137 }
2138 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2139 return Context.IntTy;
2140 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002141 // Allow block pointers to be compared with null pointer constants.
2142 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2143 (lType->isPointerType() && rType->isBlockPointerType())) {
2144 if (!LHSIsNull && !RHSIsNull) {
2145 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2146 lType.getAsString(), rType.getAsString(),
2147 lex->getSourceRange(), rex->getSourceRange());
2148 }
2149 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2150 return Context.IntTy;
2151 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002152
Steve Naroff936c4362008-06-03 14:04:54 +00002153 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002154 if ((lType->isPointerType() || rType->isPointerType()) &&
2155 !Context.typesAreCompatible(lType, rType)) {
2156 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2157 lType.getAsString(), rType.getAsString(),
2158 lex->getSourceRange(), rex->getSourceRange());
2159 return QualType();
2160 }
Steve Naroff936c4362008-06-03 14:04:54 +00002161 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2162 ImpCastExprToType(rex, lType);
2163 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002164 } else {
2165 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
2166 Diag(loc, diag::warn_incompatible_qualified_id_operands,
2167 lex->getType().getAsString(), rex->getType().getAsString(),
2168 lex->getSourceRange(), rex->getSourceRange());
2169 return QualType();
2170 }
Steve Naroff936c4362008-06-03 14:04:54 +00002171 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002172 }
Steve Naroff936c4362008-06-03 14:04:54 +00002173 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2174 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002175 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002176 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2177 lType.getAsString(), rType.getAsString(),
2178 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002179 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002180 return Context.IntTy;
2181 }
Steve Naroff936c4362008-06-03 14:04:54 +00002182 if (lType->isIntegerType() &&
2183 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002184 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002185 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2186 lType.getAsString(), rType.getAsString(),
2187 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002188 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002189 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002190 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002191 // Handle block pointers.
2192 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2193 if (!RHSIsNull)
2194 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2195 lType.getAsString(), rType.getAsString(),
2196 lex->getSourceRange(), rex->getSourceRange());
2197 ImpCastExprToType(rex, lType); // promote the integer to pointer
2198 return Context.IntTy;
2199 }
2200 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2201 if (!LHSIsNull)
2202 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2203 lType.getAsString(), rType.getAsString(),
2204 lex->getSourceRange(), rex->getSourceRange());
2205 ImpCastExprToType(lex, rType); // promote the integer to pointer
2206 return Context.IntTy;
2207 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00002208 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002209}
2210
Nate Begemanc5f0f652008-07-14 18:02:46 +00002211/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2212/// operates on extended vector types. Instead of producing an IntTy result,
2213/// like a scalar comparison, a vector comparison produces a vector of integer
2214/// types.
2215QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2216 SourceLocation loc,
2217 bool isRelational) {
2218 // Check to make sure we're operating on vectors of the same type and width,
2219 // Allowing one side to be a scalar of element type.
2220 QualType vType = CheckVectorOperands(loc, lex, rex);
2221 if (vType.isNull())
2222 return vType;
2223
2224 QualType lType = lex->getType();
2225 QualType rType = rex->getType();
2226
2227 // For non-floating point types, check for self-comparisons of the form
2228 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2229 // often indicate logic errors in the program.
2230 if (!lType->isFloatingType()) {
2231 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2232 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2233 if (DRL->getDecl() == DRR->getDecl())
2234 Diag(loc, diag::warn_selfcomparison);
2235 }
2236
2237 // Check for comparisons of floating point operands using != and ==.
2238 if (!isRelational && lType->isFloatingType()) {
2239 assert (rType->isFloatingType());
2240 CheckFloatComparison(loc,lex,rex);
2241 }
2242
2243 // Return the type for the comparison, which is the same as vector type for
2244 // integer vectors, or an integer type of identical size and number of
2245 // elements for floating point vectors.
2246 if (lType->isIntegerType())
2247 return lType;
2248
2249 const VectorType *VTy = lType->getAsVectorType();
2250
2251 // FIXME: need to deal with non-32b int / non-64b long long
2252 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2253 if (TypeSize == 32) {
2254 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2255 }
2256 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2257 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2258}
2259
Chris Lattner4b009652007-07-25 00:24:17 +00002260inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00002261 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002262{
2263 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2264 return CheckVectorOperands(loc, lex, rex);
2265
Steve Naroff8f708362007-08-24 19:07:16 +00002266 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002267
2268 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002269 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002270 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002271}
2272
2273inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
2274 Expr *&lex, Expr *&rex, SourceLocation loc)
2275{
2276 UsualUnaryConversions(lex);
2277 UsualUnaryConversions(rex);
2278
Eli Friedmanbea3f842008-05-13 20:16:47 +00002279 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002280 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002281 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002282}
2283
2284inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00002285 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00002286{
2287 QualType lhsType = lex->getType();
2288 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner25168a52008-07-26 21:30:36 +00002289 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002290
2291 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00002292 case Expr::MLV_Valid:
2293 break;
2294 case Expr::MLV_ConstQualified:
2295 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2296 return QualType();
2297 case Expr::MLV_ArrayType:
2298 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2299 lhsType.getAsString(), lex->getSourceRange());
2300 return QualType();
2301 case Expr::MLV_NotObjectType:
2302 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2303 lhsType.getAsString(), lex->getSourceRange());
2304 return QualType();
2305 case Expr::MLV_InvalidExpression:
2306 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2307 lex->getSourceRange());
2308 return QualType();
2309 case Expr::MLV_IncompleteType:
2310 case Expr::MLV_IncompleteVoidType:
2311 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2312 lhsType.getAsString(), lex->getSourceRange());
2313 return QualType();
2314 case Expr::MLV_DuplicateVectorComponents:
2315 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2316 lex->getSourceRange());
2317 return QualType();
Steve Naroff076d6cb2008-09-26 14:41:28 +00002318 case Expr::MLV_NotBlockQualified:
2319 Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2320 lex->getSourceRange());
2321 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002322 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002323
Chris Lattner005ed752008-01-04 18:04:52 +00002324 AssignConvertType ConvTy;
Chris Lattner34c85082008-08-21 18:04:13 +00002325 if (compoundType.isNull()) {
2326 // Simple assignment "x = y".
Chris Lattner005ed752008-01-04 18:04:52 +00002327 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner34c85082008-08-21 18:04:13 +00002328
2329 // If the RHS is a unary plus or minus, check to see if they = and + are
2330 // right next to each other. If so, the user may have typo'd "x =+ 4"
2331 // instead of "x += 4".
2332 Expr *RHSCheck = rex;
2333 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2334 RHSCheck = ICE->getSubExpr();
2335 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2336 if ((UO->getOpcode() == UnaryOperator::Plus ||
2337 UO->getOpcode() == UnaryOperator::Minus) &&
2338 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2339 // Only if the two operators are exactly adjacent.
2340 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2341 Diag(loc, diag::warn_not_compound_assign,
2342 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2343 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2344 }
2345 } else {
2346 // Compound assignment "x += y"
Chris Lattner005ed752008-01-04 18:04:52 +00002347 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner34c85082008-08-21 18:04:13 +00002348 }
Chris Lattner005ed752008-01-04 18:04:52 +00002349
2350 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2351 rex, "assigning"))
2352 return QualType();
2353
Chris Lattner4b009652007-07-25 00:24:17 +00002354 // C99 6.5.16p3: The type of an assignment expression is the type of the
2355 // left operand unless the left operand has qualified type, in which case
2356 // it is the unqualified version of the type of the left operand.
2357 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2358 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002359 // C++ 5.17p1: the type of the assignment expression is that of its left
2360 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00002361 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002362}
2363
2364inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2365 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00002366
2367 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2368 DefaultFunctionArrayConversion(rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002369 return rex->getType();
2370}
2371
2372/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2373/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2374QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2375 QualType resType = op->getType();
2376 assert(!resType.isNull() && "no type for increment/decrement expression");
2377
Steve Naroffd30e1932007-08-24 17:20:07 +00002378 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00002379 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002380 if (pt->getPointeeType()->isVoidType()) {
2381 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2382 } else if (!pt->getPointeeType()->isObjectType()) {
2383 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00002384 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2385 resType.getAsString(), op->getSourceRange());
2386 return QualType();
2387 }
Steve Naroffd30e1932007-08-24 17:20:07 +00002388 } else if (!resType->isRealType()) {
2389 if (resType->isComplexType())
2390 // C99 does not support ++/-- on complex types.
2391 Diag(OpLoc, diag::ext_integer_increment_complex,
2392 resType.getAsString(), op->getSourceRange());
2393 else {
2394 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2395 resType.getAsString(), op->getSourceRange());
2396 return QualType();
2397 }
Chris Lattner4b009652007-07-25 00:24:17 +00002398 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002399 // At this point, we know we have a real, complex or pointer type.
2400 // Now make sure the operand is a modifiable lvalue.
Chris Lattner25168a52008-07-26 21:30:36 +00002401 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002402 if (mlval != Expr::MLV_Valid) {
2403 // FIXME: emit a more precise diagnostic...
2404 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2405 op->getSourceRange());
2406 return QualType();
2407 }
2408 return resType;
2409}
2410
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002411/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002412/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002413/// where the declaration is needed for type checking. We only need to
2414/// handle cases when the expression references a function designator
2415/// or is an lvalue. Here are some examples:
2416/// - &(x) => x
2417/// - &*****f => f for f a function designator.
2418/// - &s.xx => s
2419/// - &s.zz[1].yy -> s, if zz is an array
2420/// - *(x + 1) -> x, if x is an array
2421/// - &"123"[2] -> 0
2422/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002423static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002424 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002425 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002426 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002427 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002428 // Fields cannot be declared with a 'register' storage class.
2429 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002430 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002431 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002432 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002433 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002434 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002435
Douglas Gregord2baafd2008-10-21 16:13:35 +00002436 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002437 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002438 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002439 return 0;
2440 else
2441 return VD;
2442 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002443 case Stmt::UnaryOperatorClass: {
2444 UnaryOperator *UO = cast<UnaryOperator>(E);
2445
2446 switch(UO->getOpcode()) {
2447 case UnaryOperator::Deref: {
2448 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002449 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2450 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2451 if (!VD || VD->getType()->isPointerType())
2452 return 0;
2453 return VD;
2454 }
2455 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002456 }
2457 case UnaryOperator::Real:
2458 case UnaryOperator::Imag:
2459 case UnaryOperator::Extension:
2460 return getPrimaryDecl(UO->getSubExpr());
2461 default:
2462 return 0;
2463 }
2464 }
2465 case Stmt::BinaryOperatorClass: {
2466 BinaryOperator *BO = cast<BinaryOperator>(E);
2467
2468 // Handle cases involving pointer arithmetic. The result of an
2469 // Assign or AddAssign is not an lvalue so they can be ignored.
2470
2471 // (x + n) or (n + x) => x
2472 if (BO->getOpcode() == BinaryOperator::Add) {
2473 if (BO->getLHS()->getType()->isPointerType()) {
2474 return getPrimaryDecl(BO->getLHS());
2475 } else if (BO->getRHS()->getType()->isPointerType()) {
2476 return getPrimaryDecl(BO->getRHS());
2477 }
2478 }
2479
2480 return 0;
2481 }
Chris Lattner4b009652007-07-25 00:24:17 +00002482 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002483 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002484 case Stmt::ImplicitCastExprClass:
2485 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002486 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002487 default:
2488 return 0;
2489 }
2490}
2491
2492/// CheckAddressOfOperand - The operand of & must be either a function
2493/// designator or an lvalue designating an object. If it is an lvalue, the
2494/// object cannot be declared with storage class register or be a bit field.
2495/// Note: The usual conversions are *not* applied to the operand of the &
2496/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2497QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002498 if (getLangOptions().C99) {
2499 // Implement C99-only parts of addressof rules.
2500 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2501 if (uOp->getOpcode() == UnaryOperator::Deref)
2502 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2503 // (assuming the deref expression is valid).
2504 return uOp->getSubExpr()->getType();
2505 }
2506 // Technically, there should be a check for array subscript
2507 // expressions here, but the result of one is always an lvalue anyway.
2508 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002509 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002510 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002511
2512 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002513 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2514 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002515 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2516 op->getSourceRange());
2517 return QualType();
2518 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002519 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2520 if (MemExpr->getMemberDecl()->isBitField()) {
2521 Diag(OpLoc, diag::err_typecheck_address_of,
2522 std::string("bit-field"), op->getSourceRange());
2523 return QualType();
2524 }
2525 // Check for Apple extension for accessing vector components.
2526 } else if (isa<ArraySubscriptExpr>(op) &&
2527 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2528 Diag(OpLoc, diag::err_typecheck_address_of,
2529 std::string("vector"), op->getSourceRange());
2530 return QualType();
2531 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002532 // We have an lvalue with a decl. Make sure the decl is not declared
2533 // with the register storage-class specifier.
2534 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2535 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002536 Diag(OpLoc, diag::err_typecheck_address_of,
2537 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002538 return QualType();
2539 }
2540 } else
2541 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002542 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002543
Chris Lattner4b009652007-07-25 00:24:17 +00002544 // If the operand has type "type", the result has type "pointer to type".
2545 return Context.getPointerType(op->getType());
2546}
2547
2548QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2549 UsualUnaryConversions(op);
2550 QualType qType = op->getType();
2551
Chris Lattner7931f4a2007-07-31 16:53:04 +00002552 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002553 // Note that per both C89 and C99, this is always legal, even
2554 // if ptype is an incomplete type or void.
2555 // It would be possible to warn about dereferencing a
2556 // void pointer, but it's completely well-defined,
2557 // and such a warning is unlikely to catch any mistakes.
2558 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002559 }
2560 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2561 qType.getAsString(), op->getSourceRange());
2562 return QualType();
2563}
2564
2565static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2566 tok::TokenKind Kind) {
2567 BinaryOperator::Opcode Opc;
2568 switch (Kind) {
2569 default: assert(0 && "Unknown binop!");
2570 case tok::star: Opc = BinaryOperator::Mul; break;
2571 case tok::slash: Opc = BinaryOperator::Div; break;
2572 case tok::percent: Opc = BinaryOperator::Rem; break;
2573 case tok::plus: Opc = BinaryOperator::Add; break;
2574 case tok::minus: Opc = BinaryOperator::Sub; break;
2575 case tok::lessless: Opc = BinaryOperator::Shl; break;
2576 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2577 case tok::lessequal: Opc = BinaryOperator::LE; break;
2578 case tok::less: Opc = BinaryOperator::LT; break;
2579 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2580 case tok::greater: Opc = BinaryOperator::GT; break;
2581 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2582 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2583 case tok::amp: Opc = BinaryOperator::And; break;
2584 case tok::caret: Opc = BinaryOperator::Xor; break;
2585 case tok::pipe: Opc = BinaryOperator::Or; break;
2586 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2587 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2588 case tok::equal: Opc = BinaryOperator::Assign; break;
2589 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2590 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2591 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2592 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2593 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2594 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2595 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2596 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2597 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2598 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2599 case tok::comma: Opc = BinaryOperator::Comma; break;
2600 }
2601 return Opc;
2602}
2603
2604static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2605 tok::TokenKind Kind) {
2606 UnaryOperator::Opcode Opc;
2607 switch (Kind) {
2608 default: assert(0 && "Unknown unary op!");
2609 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2610 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2611 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2612 case tok::star: Opc = UnaryOperator::Deref; break;
2613 case tok::plus: Opc = UnaryOperator::Plus; break;
2614 case tok::minus: Opc = UnaryOperator::Minus; break;
2615 case tok::tilde: Opc = UnaryOperator::Not; break;
2616 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2617 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2618 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2619 case tok::kw___real: Opc = UnaryOperator::Real; break;
2620 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2621 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2622 }
2623 return Opc;
2624}
2625
2626// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002627Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002628 ExprTy *LHS, ExprTy *RHS) {
2629 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2630 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2631
Steve Naroff87d58b42007-09-16 03:34:24 +00002632 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2633 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002634
2635 QualType ResultTy; // Result type of the binary operator.
2636 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2637
2638 switch (Opc) {
2639 default:
2640 assert(0 && "Unknown binary expr!");
2641 case BinaryOperator::Assign:
2642 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2643 break;
2644 case BinaryOperator::Mul:
2645 case BinaryOperator::Div:
2646 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2647 break;
2648 case BinaryOperator::Rem:
2649 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2650 break;
2651 case BinaryOperator::Add:
2652 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2653 break;
2654 case BinaryOperator::Sub:
2655 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2656 break;
2657 case BinaryOperator::Shl:
2658 case BinaryOperator::Shr:
2659 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2660 break;
2661 case BinaryOperator::LE:
2662 case BinaryOperator::LT:
2663 case BinaryOperator::GE:
2664 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002665 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002666 break;
2667 case BinaryOperator::EQ:
2668 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002669 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00002670 break;
2671 case BinaryOperator::And:
2672 case BinaryOperator::Xor:
2673 case BinaryOperator::Or:
2674 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2675 break;
2676 case BinaryOperator::LAnd:
2677 case BinaryOperator::LOr:
2678 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2679 break;
2680 case BinaryOperator::MulAssign:
2681 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002682 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002683 if (!CompTy.isNull())
2684 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2685 break;
2686 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002687 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002688 if (!CompTy.isNull())
2689 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2690 break;
2691 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002692 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002693 if (!CompTy.isNull())
2694 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2695 break;
2696 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002697 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002698 if (!CompTy.isNull())
2699 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2700 break;
2701 case BinaryOperator::ShlAssign:
2702 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002703 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002704 if (!CompTy.isNull())
2705 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2706 break;
2707 case BinaryOperator::AndAssign:
2708 case BinaryOperator::XorAssign:
2709 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002710 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002711 if (!CompTy.isNull())
2712 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2713 break;
2714 case BinaryOperator::Comma:
2715 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2716 break;
2717 }
2718 if (ResultTy.isNull())
2719 return true;
2720 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00002721 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002722 else
Chris Lattnerf420df12007-08-28 18:36:55 +00002723 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002724}
2725
2726// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002727Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002728 ExprTy *input) {
2729 Expr *Input = (Expr*)input;
2730 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2731 QualType resultType;
2732 switch (Opc) {
2733 default:
2734 assert(0 && "Unimplemented unary expr!");
2735 case UnaryOperator::PreInc:
2736 case UnaryOperator::PreDec:
2737 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2738 break;
2739 case UnaryOperator::AddrOf:
2740 resultType = CheckAddressOfOperand(Input, OpLoc);
2741 break;
2742 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002743 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002744 resultType = CheckIndirectionOperand(Input, OpLoc);
2745 break;
2746 case UnaryOperator::Plus:
2747 case UnaryOperator::Minus:
2748 UsualUnaryConversions(Input);
2749 resultType = Input->getType();
2750 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2751 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2752 resultType.getAsString());
2753 break;
2754 case UnaryOperator::Not: // bitwise complement
2755 UsualUnaryConversions(Input);
2756 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002757 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2758 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2759 // C99 does not support '~' for complex conjugation.
2760 Diag(OpLoc, diag::ext_integer_complement_complex,
2761 resultType.getAsString(), Input->getSourceRange());
2762 else if (!resultType->isIntegerType())
2763 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2764 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002765 break;
2766 case UnaryOperator::LNot: // logical negation
2767 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2768 DefaultFunctionArrayConversion(Input);
2769 resultType = Input->getType();
2770 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2771 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2772 resultType.getAsString());
2773 // LNot always has type int. C99 6.5.3.3p5.
2774 resultType = Context.IntTy;
2775 break;
2776 case UnaryOperator::SizeOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002777 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2778 Input->getSourceRange(), true);
Chris Lattner4b009652007-07-25 00:24:17 +00002779 break;
2780 case UnaryOperator::AlignOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002781 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2782 Input->getSourceRange(), false);
Chris Lattner4b009652007-07-25 00:24:17 +00002783 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002784 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002785 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002786 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002787 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002788 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002789 resultType = Input->getType();
2790 break;
2791 }
2792 if (resultType.isNull())
2793 return true;
2794 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2795}
2796
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002797/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2798Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002799 SourceLocation LabLoc,
2800 IdentifierInfo *LabelII) {
2801 // Look up the record for this label identifier.
2802 LabelStmt *&LabelDecl = LabelMap[LabelII];
2803
Daniel Dunbar879788d2008-08-04 16:51:22 +00002804 // If we haven't seen this label yet, create a forward reference. It
2805 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00002806 if (LabelDecl == 0)
2807 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2808
2809 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002810 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2811 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002812}
2813
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002814Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002815 SourceLocation RPLoc) { // "({..})"
2816 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2817 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2818 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2819
2820 // FIXME: there are a variety of strange constraints to enforce here, for
2821 // example, it is not possible to goto into a stmt expression apparently.
2822 // More semantic analysis is needed.
2823
2824 // FIXME: the last statement in the compount stmt has its value used. We
2825 // should not warn about it being unused.
2826
2827 // If there are sub stmts in the compound stmt, take the type of the last one
2828 // as the type of the stmtexpr.
2829 QualType Ty = Context.VoidTy;
2830
Chris Lattner200964f2008-07-26 19:51:01 +00002831 if (!Compound->body_empty()) {
2832 Stmt *LastStmt = Compound->body_back();
2833 // If LastStmt is a label, skip down through into the body.
2834 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2835 LastStmt = Label->getSubStmt();
2836
2837 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00002838 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00002839 }
Chris Lattner4b009652007-07-25 00:24:17 +00002840
2841 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2842}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002843
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002844Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002845 SourceLocation TypeLoc,
2846 TypeTy *argty,
2847 OffsetOfComponent *CompPtr,
2848 unsigned NumComponents,
2849 SourceLocation RPLoc) {
2850 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2851 assert(!ArgTy.isNull() && "Missing type argument!");
2852
2853 // We must have at least one component that refers to the type, and the first
2854 // one is known to be a field designator. Verify that the ArgTy represents
2855 // a struct/union/class.
2856 if (!ArgTy->isRecordType())
2857 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2858
2859 // Otherwise, create a compound literal expression as the base, and
2860 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002861 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002862
Chris Lattnerb37522e2007-08-31 21:49:13 +00002863 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2864 // GCC extension, diagnose them.
2865 if (NumComponents != 1)
2866 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2867 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2868
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002869 for (unsigned i = 0; i != NumComponents; ++i) {
2870 const OffsetOfComponent &OC = CompPtr[i];
2871 if (OC.isBrackets) {
2872 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00002873 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002874 if (!AT) {
2875 delete Res;
2876 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2877 Res->getType().getAsString());
2878 }
2879
Chris Lattner2af6a802007-08-30 17:59:59 +00002880 // FIXME: C++: Verify that operator[] isn't overloaded.
2881
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002882 // C99 6.5.2.1p1
2883 Expr *Idx = static_cast<Expr*>(OC.U.E);
2884 if (!Idx->getType()->isIntegerType())
2885 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2886 Idx->getSourceRange());
2887
2888 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2889 continue;
2890 }
2891
2892 const RecordType *RC = Res->getType()->getAsRecordType();
2893 if (!RC) {
2894 delete Res;
2895 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2896 Res->getType().getAsString());
2897 }
2898
2899 // Get the decl corresponding to this.
2900 RecordDecl *RD = RC->getDecl();
2901 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2902 if (!MemberDecl)
2903 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2904 OC.U.IdentInfo->getName(),
2905 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002906
2907 // FIXME: C++: Verify that MemberDecl isn't a static field.
2908 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002909 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2910 // matter here.
2911 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002912 }
2913
2914 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2915 BuiltinLoc);
2916}
2917
2918
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002919Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002920 TypeTy *arg1, TypeTy *arg2,
2921 SourceLocation RPLoc) {
2922 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2923 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2924
2925 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2926
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002927 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002928}
2929
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002930Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002931 ExprTy *expr1, ExprTy *expr2,
2932 SourceLocation RPLoc) {
2933 Expr *CondExpr = static_cast<Expr*>(cond);
2934 Expr *LHSExpr = static_cast<Expr*>(expr1);
2935 Expr *RHSExpr = static_cast<Expr*>(expr2);
2936
2937 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2938
2939 // The conditional expression is required to be a constant expression.
2940 llvm::APSInt condEval(32);
2941 SourceLocation ExpLoc;
2942 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2943 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2944 CondExpr->getSourceRange());
2945
2946 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2947 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2948 RHSExpr->getType();
2949 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2950}
2951
Steve Naroff52a81c02008-09-03 18:15:37 +00002952//===----------------------------------------------------------------------===//
2953// Clang Extensions.
2954//===----------------------------------------------------------------------===//
2955
2956/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00002957void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00002958 // Analyze block parameters.
2959 BlockSemaInfo *BSI = new BlockSemaInfo();
2960
2961 // Add BSI to CurBlock.
2962 BSI->PrevBlockInfo = CurBlock;
2963 CurBlock = BSI;
2964
2965 BSI->ReturnType = 0;
2966 BSI->TheScope = BlockScope;
2967
Steve Naroff52059382008-10-10 01:28:17 +00002968 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
2969 PushDeclContext(BSI->TheDecl);
2970}
2971
2972void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00002973 // Analyze arguments to block.
2974 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2975 "Not a function declarator!");
2976 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2977
Steve Naroff52059382008-10-10 01:28:17 +00002978 CurBlock->hasPrototype = FTI.hasPrototype;
2979 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00002980
2981 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2982 // no arguments, not a function that takes a single void argument.
2983 if (FTI.hasPrototype &&
2984 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2985 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2986 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2987 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00002988 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00002989 } else if (FTI.hasPrototype) {
2990 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00002991 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2992 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00002993 }
Steve Naroff52059382008-10-10 01:28:17 +00002994 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
2995
2996 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
2997 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
2998 // If this has an identifier, add it to the scope stack.
2999 if ((*AI)->getIdentifier())
3000 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003001}
3002
3003/// ActOnBlockError - If there is an error parsing a block, this callback
3004/// is invoked to pop the information about the block from the action impl.
3005void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3006 // Ensure that CurBlock is deleted.
3007 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3008
3009 // Pop off CurBlock, handle nested blocks.
3010 CurBlock = CurBlock->PrevBlockInfo;
3011
3012 // FIXME: Delete the ParmVarDecl objects as well???
3013
3014}
3015
3016/// ActOnBlockStmtExpr - This is called when the body of a block statement
3017/// literal was successfully completed. ^(int x){...}
3018Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3019 Scope *CurScope) {
3020 // Ensure that CurBlock is deleted.
3021 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3022 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3023
Steve Naroff52059382008-10-10 01:28:17 +00003024 PopDeclContext();
3025
Steve Naroff52a81c02008-09-03 18:15:37 +00003026 // Pop off CurBlock, handle nested blocks.
3027 CurBlock = CurBlock->PrevBlockInfo;
3028
3029 QualType RetTy = Context.VoidTy;
3030 if (BSI->ReturnType)
3031 RetTy = QualType(BSI->ReturnType, 0);
3032
3033 llvm::SmallVector<QualType, 8> ArgTypes;
3034 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3035 ArgTypes.push_back(BSI->Params[i]->getType());
3036
3037 QualType BlockTy;
3038 if (!BSI->hasPrototype)
3039 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3040 else
3041 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
3042 BSI->isVariadic);
3043
3044 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003045
Steve Naroff95029d92008-10-08 18:44:00 +00003046 BSI->TheDecl->setBody(Body.take());
3047 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003048}
3049
Nate Begemanbd881ef2008-01-30 20:50:20 +00003050/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003051/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003052/// The number of arguments has already been validated to match the number of
3053/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003054static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3055 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003056 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003057 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003058 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3059 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003060
3061 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003062 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003063 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003064 return true;
3065}
3066
3067Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3068 SourceLocation *CommaLocs,
3069 SourceLocation BuiltinLoc,
3070 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003071 // __builtin_overload requires at least 2 arguments
3072 if (NumArgs < 2)
3073 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3074 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003075
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003076 // The first argument is required to be a constant expression. It tells us
3077 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003078 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003079 Expr *NParamsExpr = Args[0];
3080 llvm::APSInt constEval(32);
3081 SourceLocation ExpLoc;
3082 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
3083 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3084 NParamsExpr->getSourceRange());
3085
3086 // Verify that the number of parameters is > 0
3087 unsigned NumParams = constEval.getZExtValue();
3088 if (NumParams == 0)
3089 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3090 NParamsExpr->getSourceRange());
3091 // Verify that we have at least 1 + NumParams arguments to the builtin.
3092 if ((NumParams + 1) > NumArgs)
3093 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3094 SourceRange(BuiltinLoc, RParenLoc));
3095
3096 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003097 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003098 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003099 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3100 // UsualUnaryConversions will convert the function DeclRefExpr into a
3101 // pointer to function.
3102 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003103 const FunctionTypeProto *FnType = 0;
3104 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3105 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003106
3107 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3108 // parameters, and the number of parameters must match the value passed to
3109 // the builtin.
3110 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00003111 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
3112 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003113
3114 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003115 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003116 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003117 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003118 if (OE)
3119 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
3120 OE->getFn()->getSourceRange());
3121 // Remember our match, and continue processing the remaining arguments
3122 // to catch any errors.
3123 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
3124 BuiltinLoc, RParenLoc);
3125 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003126 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003127 // Return the newly created OverloadExpr node, if we succeded in matching
3128 // exactly one of the candidate functions.
3129 if (OE)
3130 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003131
3132 // If we didn't find a matching function Expr in the __builtin_overload list
3133 // the return an error.
3134 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003135 for (unsigned i = 0; i != NumParams; ++i) {
3136 if (i != 0) typeNames += ", ";
3137 typeNames += Args[i+1]->getType().getAsString();
3138 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003139
3140 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3141 SourceRange(BuiltinLoc, RParenLoc));
3142}
3143
Anders Carlsson36760332007-10-15 20:28:48 +00003144Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3145 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003146 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003147 Expr *E = static_cast<Expr*>(expr);
3148 QualType T = QualType::getFromOpaquePtr(type);
3149
3150 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003151
3152 // Get the va_list type
3153 QualType VaListType = Context.getBuiltinVaListType();
3154 // Deal with implicit array decay; for example, on x86-64,
3155 // va_list is an array, but it's supposed to decay to
3156 // a pointer for va_arg.
3157 if (VaListType->isArrayType())
3158 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003159 // Make sure the input expression also decays appropriately.
3160 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003161
3162 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003163 return Diag(E->getLocStart(),
3164 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3165 E->getType().getAsString(),
3166 E->getSourceRange());
3167
3168 // FIXME: Warn if a non-POD type is passed in.
3169
3170 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
3171}
3172
Chris Lattner005ed752008-01-04 18:04:52 +00003173bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3174 SourceLocation Loc,
3175 QualType DstType, QualType SrcType,
3176 Expr *SrcExpr, const char *Flavor) {
3177 // Decode the result (notice that AST's are still created for extensions).
3178 bool isInvalid = false;
3179 unsigned DiagKind;
3180 switch (ConvTy) {
3181 default: assert(0 && "Unknown conversion type");
3182 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003183 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003184 DiagKind = diag::ext_typecheck_convert_pointer_int;
3185 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003186 case IntToPointer:
3187 DiagKind = diag::ext_typecheck_convert_int_pointer;
3188 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003189 case IncompatiblePointer:
3190 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3191 break;
3192 case FunctionVoidPointer:
3193 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3194 break;
3195 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003196 // If the qualifiers lost were because we were applying the
3197 // (deprecated) C++ conversion from a string literal to a char*
3198 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3199 // Ideally, this check would be performed in
3200 // CheckPointerTypesForAssignment. However, that would require a
3201 // bit of refactoring (so that the second argument is an
3202 // expression, rather than a type), which should be done as part
3203 // of a larger effort to fix CheckPointerTypesForAssignment for
3204 // C++ semantics.
3205 if (getLangOptions().CPlusPlus &&
3206 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3207 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003208 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3209 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003210 case IntToBlockPointer:
3211 DiagKind = diag::err_int_to_block_pointer;
3212 break;
3213 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003214 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003215 break;
3216 case BlockVoidPointer:
3217 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3218 break;
Steve Naroff19608432008-10-14 22:18:38 +00003219 case IncompatibleObjCQualifiedId:
3220 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3221 // it can give a more specific diagnostic.
3222 DiagKind = diag::warn_incompatible_qualified_id;
3223 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003224 case Incompatible:
3225 DiagKind = diag::err_typecheck_convert_incompatible;
3226 isInvalid = true;
3227 break;
3228 }
3229
3230 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3231 SrcExpr->getSourceRange());
3232 return isInvalid;
3233}