blob: fee94568b78c5f497663b87d8e4c045f55d2798f [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
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +0000405 // FIXME: Handle 'mutable'.
406 return new DeclRefExpr(FD,
407 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000408 }
409
410 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
411 }
Chris Lattner4b009652007-07-25 00:24:17 +0000412 if (isa<TypedefDecl>(D))
413 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000414 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000415 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000416 if (isa<NamespaceDecl>(D))
417 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000418
Steve Naroffd6163f32008-09-05 22:11:13 +0000419 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000420 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
421 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
422
Steve Naroffd6163f32008-09-05 22:11:13 +0000423 ValueDecl *VD = cast<ValueDecl>(D);
424
425 // check if referencing an identifier with __attribute__((deprecated)).
426 if (VD->getAttr<DeprecatedAttr>())
427 Diag(Loc, diag::warn_deprecated, VD->getName());
428
429 // Only create DeclRefExpr's for valid Decl's.
430 if (VD->isInvalidDecl())
431 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000432
433 // If the identifier reference is inside a block, and it refers to a value
434 // that is outside the block, create a BlockDeclRefExpr instead of a
435 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
436 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000437 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000438 // We do not do this for things like enum constants, global variables, etc,
439 // as they do not get snapshotted.
440 //
441 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000442 // The BlocksAttr indicates the variable is bound by-reference.
443 if (VD->getAttr<BlocksAttr>())
444 return new BlockDeclRefExpr(VD, VD->getType(), Loc, true);
445
446 // Variable will be bound by-copy, make it const within the closure.
447 VD->getType().addConst();
448 return new BlockDeclRefExpr(VD, VD->getType(), Loc, false);
449 }
450 // If this reference is not in a block or if the referenced variable is
451 // within the block, create a normal DeclRefExpr.
Douglas Gregor3fb675a2008-10-22 04:14:44 +0000452 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Chris Lattner4b009652007-07-25 00:24:17 +0000453}
454
Chris Lattner69909292008-08-10 01:53:14 +0000455Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000456 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000457 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000458
459 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000460 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000461 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
462 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
463 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000464 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000465
466 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000467 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000468 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000469
Chris Lattner7e637512008-01-12 08:14:25 +0000470 // Pre-defined identifiers are of type char[x], where x is the length of the
471 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000472 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000473 if (getCurFunctionDecl())
474 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000475 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000476 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000477
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000478 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000479 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000480 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000481 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000482}
483
Steve Naroff87d58b42007-09-16 03:34:24 +0000484Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000485 llvm::SmallString<16> CharBuffer;
486 CharBuffer.resize(Tok.getLength());
487 const char *ThisTokBegin = &CharBuffer[0];
488 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
489
490 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
491 Tok.getLocation(), PP);
492 if (Literal.hadError())
493 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000494
495 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
496
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000497 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
498 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000499}
500
Steve Naroff87d58b42007-09-16 03:34:24 +0000501Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000502 // fast path for a single digit (which is quite common). A single digit
503 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
504 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000505 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000506
Chris Lattner8cd0e932008-03-05 18:54:05 +0000507 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000508 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000509 Context.IntTy,
510 Tok.getLocation()));
511 }
512 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000513 // Add padding so that NumericLiteralParser can overread by one character.
514 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000515 const char *ThisTokBegin = &IntegerBuffer[0];
516
517 // Get the spelling of the token, which eliminates trigraphs, etc.
518 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000519
Chris Lattner4b009652007-07-25 00:24:17 +0000520 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
521 Tok.getLocation(), PP);
522 if (Literal.hadError)
523 return ExprResult(true);
524
Chris Lattner1de66eb2007-08-26 03:42:43 +0000525 Expr *Res;
526
527 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000528 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000529 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000530 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000531 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000532 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000533 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000534 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000535
536 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
537
Ted Kremenekddedbe22007-11-29 00:56:49 +0000538 // isExact will be set by GetFloatValue().
539 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000540 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000541 Ty, Tok.getLocation());
542
Chris Lattner1de66eb2007-08-26 03:42:43 +0000543 } else if (!Literal.isIntegerLiteral()) {
544 return ExprResult(true);
545 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000546 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000547
Neil Booth7421e9c2007-08-29 22:00:19 +0000548 // long long is a C99 feature.
549 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000550 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000551 Diag(Tok.getLocation(), diag::ext_longlong);
552
Chris Lattner4b009652007-07-25 00:24:17 +0000553 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000554 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000555
556 if (Literal.GetIntegerValue(ResultVal)) {
557 // If this value didn't fit into uintmax_t, warn and force to ull.
558 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000559 Ty = Context.UnsignedLongLongTy;
560 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000561 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000562 } else {
563 // If this value fits into a ULL, try to figure out what else it fits into
564 // according to the rules of C99 6.4.4.1p5.
565
566 // Octal, Hexadecimal, and integers with a U suffix are allowed to
567 // be an unsigned int.
568 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
569
570 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000571 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000572 if (!Literal.isLong && !Literal.isLongLong) {
573 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000574 unsigned IntSize = Context.Target.getIntWidth();
575
Chris Lattner4b009652007-07-25 00:24:17 +0000576 // Does it fit in a unsigned int?
577 if (ResultVal.isIntN(IntSize)) {
578 // Does it fit in a signed int?
579 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000580 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000581 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000582 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000583 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000584 }
Chris Lattner4b009652007-07-25 00:24:17 +0000585 }
586
587 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000588 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000589 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000590
591 // Does it fit in a unsigned long?
592 if (ResultVal.isIntN(LongSize)) {
593 // Does it fit in a signed long?
594 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000595 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000596 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000597 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000598 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000599 }
Chris Lattner4b009652007-07-25 00:24:17 +0000600 }
601
602 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000603 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000604 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000605
606 // Does it fit in a unsigned long long?
607 if (ResultVal.isIntN(LongLongSize)) {
608 // Does it fit in a signed long long?
609 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000610 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000611 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000612 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000613 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000614 }
615 }
616
617 // If we still couldn't decide a type, we probably have something that
618 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000619 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000620 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000621 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000622 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000623 }
Chris Lattnere4068872008-05-09 05:59:00 +0000624
625 if (ResultVal.getBitWidth() != Width)
626 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000627 }
628
Chris Lattner48d7f382008-04-02 04:24:33 +0000629 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000630 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000631
632 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
633 if (Literal.isImaginary)
634 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
635
636 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000637}
638
Steve Naroff87d58b42007-09-16 03:34:24 +0000639Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000640 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000641 Expr *E = (Expr *)Val;
642 assert((E != 0) && "ActOnParenExpr() missing expr");
643 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000644}
645
646/// The UsualUnaryConversions() function is *not* called by this routine.
647/// See C99 6.3.2.1p[2-4] for more details.
648QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerf814d882008-07-25 21:45:37 +0000649 SourceLocation OpLoc,
650 const SourceRange &ExprRange,
651 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000652 // C99 6.5.3.4p1:
653 if (isa<FunctionType>(exprType) && isSizeof)
654 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000655 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000656 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000657 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
658 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000659 else if (exprType->isIncompleteType()) {
660 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
661 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000662 exprType.getAsString(), ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000663 return QualType(); // error
664 }
665 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
666 return Context.getSizeType();
667}
668
669Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000670ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000671 SourceLocation LPLoc, TypeTy *Ty,
672 SourceLocation RPLoc) {
673 // If error parsing type, ignore.
674 if (Ty == 0) return true;
675
676 // Verify that this is a valid expression.
677 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
678
Chris Lattnerf814d882008-07-25 21:45:37 +0000679 QualType resultType =
680 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Chris Lattner4b009652007-07-25 00:24:17 +0000681
682 if (resultType.isNull())
683 return true;
684 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
685}
686
Chris Lattner5110ad52007-08-24 21:41:10 +0000687QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000688 DefaultFunctionArrayConversion(V);
689
Chris Lattnera16e42d2007-08-26 05:39:26 +0000690 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000691 if (const ComplexType *CT = V->getType()->getAsComplexType())
692 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000693
694 // Otherwise they pass through real integer and floating point types here.
695 if (V->getType()->isArithmeticType())
696 return V->getType();
697
698 // Reject anything else.
699 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
700 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000701}
702
703
Chris Lattner4b009652007-07-25 00:24:17 +0000704
Steve Naroff87d58b42007-09-16 03:34:24 +0000705Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000706 tok::TokenKind Kind,
707 ExprTy *Input) {
708 UnaryOperator::Opcode Opc;
709 switch (Kind) {
710 default: assert(0 && "Unknown unary op!");
711 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
712 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
713 }
714 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
715 if (result.isNull())
716 return true;
717 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
718}
719
720Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000721ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000722 ExprTy *Idx, SourceLocation RLoc) {
723 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
724
725 // Perform default conversions.
726 DefaultFunctionArrayConversion(LHSExp);
727 DefaultFunctionArrayConversion(RHSExp);
728
729 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
730
731 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000732 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000733 // in the subscript position. As a result, we need to derive the array base
734 // and index from the expression types.
735 Expr *BaseExpr, *IndexExpr;
736 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000737 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000738 BaseExpr = LHSExp;
739 IndexExpr = RHSExp;
740 // FIXME: need to deal with const...
741 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000742 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000743 // Handle the uncommon case of "123[Ptr]".
744 BaseExpr = RHSExp;
745 IndexExpr = LHSExp;
746 // FIXME: need to deal with const...
747 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000748 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
749 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000750 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000751
752 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000753 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
754 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000755 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000756 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000757 // FIXME: need to deal with const...
758 ResultType = VTy->getElementType();
759 } else {
760 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
761 RHSExp->getSourceRange());
762 }
763 // C99 6.5.2.1p1
764 if (!IndexExpr->getType()->isIntegerType())
765 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
766 IndexExpr->getSourceRange());
767
768 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
769 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000770 // void (*)(int)) and pointers to incomplete types. Functions are not
771 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000772 if (!ResultType->isObjectType())
773 return Diag(BaseExpr->getLocStart(),
774 diag::err_typecheck_subscript_not_object,
775 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
776
777 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
778}
779
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000780QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000781CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000782 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000783 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000784
785 // This flag determines whether or not the component is to be treated as a
786 // special name, or a regular GLSL-style component access.
787 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000788
789 // The vector accessor can't exceed the number of elements.
790 const char *compStr = CompName.getName();
791 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000792 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000793 baseType.getAsString(), SourceRange(CompLoc));
794 return QualType();
795 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000796
797 // Check that we've found one of the special components, or that the component
798 // names must come from the same set.
799 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
800 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
801 SpecialComponent = true;
802 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000803 do
804 compStr++;
805 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
806 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
807 do
808 compStr++;
809 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
810 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
811 do
812 compStr++;
813 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
814 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000815
Nate Begemanc8e51f82008-05-09 06:41:27 +0000816 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000817 // We didn't get to the end of the string. This means the component names
818 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000819 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000820 std::string(compStr,compStr+1), SourceRange(CompLoc));
821 return QualType();
822 }
823 // Each component accessor can't exceed the vector type.
824 compStr = CompName.getName();
825 while (*compStr) {
826 if (vecType->isAccessorWithinNumElements(*compStr))
827 compStr++;
828 else
829 break;
830 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000831 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000832 // We didn't get to the end of the string. This means a component accessor
833 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000834 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000835 baseType.getAsString(), SourceRange(CompLoc));
836 return QualType();
837 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000838
839 // If we have a special component name, verify that the current vector length
840 // is an even number, since all special component names return exactly half
841 // the elements.
842 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Daniel Dunbar45a91802008-09-30 17:22:47 +0000843 Diag(OpLoc, diag::err_ext_vector_component_requires_even,
844 baseType.getAsString(), SourceRange(CompLoc));
Nate Begemanc8e51f82008-05-09 06:41:27 +0000845 return QualType();
846 }
847
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000848 // The component accessor looks fine - now we need to compute the actual type.
849 // The vector type is implied by the component accessor. For example,
850 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000851 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
852 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
853 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000854 if (CompSize == 1)
855 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000856
Nate Begemanaf6ed502008-04-18 23:10:10 +0000857 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000858 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000859 // diagostics look bad. We want extended vector types to appear built-in.
860 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
861 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
862 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000863 }
864 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000865}
866
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000867/// constructSetterName - Return the setter name for the given
868/// identifier, i.e. "set" + Name where the initial character of Name
869/// has been capitalized.
870// FIXME: Merge with same routine in Parser. But where should this
871// live?
872static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
873 const IdentifierInfo *Name) {
874 unsigned N = Name->getLength();
875 char *SelectorName = new char[3 + N];
876 memcpy(SelectorName, "set", 3);
877 memcpy(&SelectorName[3], Name->getName(), N);
878 SelectorName[3] = toupper(SelectorName[3]);
879
880 IdentifierInfo *Setter =
881 &Idents.get(SelectorName, &SelectorName[3 + N]);
882 delete[] SelectorName;
883 return Setter;
884}
885
Chris Lattner4b009652007-07-25 00:24:17 +0000886Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000887ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000888 tok::TokenKind OpKind, SourceLocation MemberLoc,
889 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000890 Expr *BaseExpr = static_cast<Expr *>(Base);
891 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000892
893 // Perform default conversions.
894 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000895
Steve Naroff2cb66382007-07-26 03:11:44 +0000896 QualType BaseType = BaseExpr->getType();
897 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000898
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000899 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
900 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000901 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000902 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000903 BaseType = PT->getPointeeType();
904 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000905 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
906 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000907 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000908
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000909 // Handle field access to simple records. This also handles access to fields
910 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000911 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000912 RecordDecl *RDecl = RTy->getDecl();
913 if (RTy->isIncompleteType())
914 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
915 BaseExpr->getSourceRange());
916 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000917 FieldDecl *MemberDecl = RDecl->getMember(&Member);
918 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000919 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
920 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000921
922 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000923 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000924 QualType MemberType = MemberDecl->getType();
925 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000926 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000927 MemberType = MemberType.getQualifiedType(combinedQualifiers);
928
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000929 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000930 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000931 }
932
Chris Lattnere9d71612008-07-21 04:59:05 +0000933 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
934 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000935 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
936 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000937 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000938 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000939 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000940 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000941 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000942 }
943
Chris Lattnere9d71612008-07-21 04:59:05 +0000944 // Handle Objective-C property access, which is "Obj.property" where Obj is a
945 // pointer to a (potentially qualified) interface type.
946 const PointerType *PTy;
947 const ObjCInterfaceType *IFTy;
948 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
949 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
950 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +0000951
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000952 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +0000953 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
954 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
955
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000956 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000957 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
958 E = IFTy->qual_end(); I != E; ++I)
959 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
960 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000961
962 // If that failed, look for an "implicit" property by seeing if the nullary
963 // selector is implemented.
964
965 // FIXME: The logic for looking up nullary and unary selectors should be
966 // shared with the code in ActOnInstanceMessage.
967
968 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
969 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
970
971 // If this reference is in an @implementation, check for 'private' methods.
972 if (!Getter)
973 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
974 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
975 if (ObjCImplementationDecl *ImpDecl =
976 ObjCImplementations[ClassDecl->getIdentifier()])
977 Getter = ImpDecl->getInstanceMethod(Sel);
978
Steve Naroff04151f32008-10-22 19:16:27 +0000979 // Look through local category implementations associated with the class.
980 if (!Getter) {
981 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
982 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
983 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
984 }
985 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000986 if (Getter) {
987 // If we found a getter then this may be a valid dot-reference, we
988 // need to also look for the matching setter.
989 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
990 &Member);
991 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
992 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
993
994 if (!Setter) {
995 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
996 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
997 if (ObjCImplementationDecl *ImpDecl =
998 ObjCImplementations[ClassDecl->getIdentifier()])
999 Setter = ImpDecl->getInstanceMethod(SetterSel);
1000 }
1001
1002 // FIXME: There are some issues here. First, we are not
1003 // diagnosing accesses to read-only properties because we do not
1004 // know if this is a getter or setter yet. Second, we are
1005 // checking that the type of the setter matches the type we
1006 // expect.
1007 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1008 MemberLoc, BaseExpr);
1009 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001010 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001011 // Handle properties on qualified "id" protocols.
1012 const ObjCQualifiedIdType *QIdTy;
1013 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1014 // Check protocols on qualified interfaces.
1015 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1016 E = QIdTy->qual_end(); I != E; ++I)
1017 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1018 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1019 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001020 // Handle 'field access' to vectors, such as 'V.xx'.
1021 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1022 // Component access limited to variables (reject vec4.rg.g).
1023 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1024 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +00001025 return Diag(MemberLoc, diag::err_ext_vector_component_access,
1026 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001027 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1028 if (ret.isNull())
1029 return true;
1030 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1031 }
1032
Chris Lattner7d5a8762008-07-21 05:35:34 +00001033 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1034 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001035}
1036
Steve Naroff87d58b42007-09-16 03:34:24 +00001037/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001038/// This provides the location of the left/right parens and a list of comma
1039/// locations.
1040Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001041ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001042 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001043 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1044 Expr *Fn = static_cast<Expr *>(fn);
1045 Expr **Args = reinterpret_cast<Expr**>(args);
1046 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001047 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001048 OverloadedFunctionDecl *Ovl = NULL;
1049
1050 // If we're directly calling a function or a set of overloaded
1051 // functions, get the appropriate declaration.
1052 {
1053 DeclRefExpr *DRExpr = NULL;
1054 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1055 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1056 else
1057 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1058
1059 if (DRExpr) {
1060 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1061 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1062 }
1063 }
1064
1065 // If we have a set of overloaded functions, perform overload
1066 // resolution to pick the function.
1067 if (Ovl) {
1068 OverloadCandidateSet CandidateSet;
1069 OverloadCandidateSet::iterator Best;
1070 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
1071 switch (BestViableFunction(CandidateSet, Best)) {
1072 case OR_Success:
1073 {
1074 // Success! Let the remainder of this function build a call to
1075 // the function selected by overload resolution.
1076 FDecl = Best->Function;
1077 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1078 Fn->getSourceRange().getBegin());
1079 delete Fn;
1080 Fn = NewFn;
1081 }
1082 break;
1083
1084 case OR_No_Viable_Function:
1085 if (CandidateSet.empty())
1086 Diag(Fn->getSourceRange().getBegin(),
1087 diag::err_ovl_no_viable_function_in_call, Ovl->getName(),
1088 Fn->getSourceRange());
1089 else {
1090 Diag(Fn->getSourceRange().getBegin(),
1091 diag::err_ovl_no_viable_function_in_call_with_cands,
1092 Ovl->getName(), Fn->getSourceRange());
1093 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1094 }
1095 return true;
1096
1097 case OR_Ambiguous:
1098 Diag(Fn->getSourceRange().getBegin(),
1099 diag::err_ovl_ambiguous_call, Ovl->getName(),
1100 Fn->getSourceRange());
1101 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1102 return true;
1103 }
1104 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001105
1106 // Promote the function operand.
1107 UsualUnaryConversions(Fn);
1108
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001109 // Make the call expr early, before semantic checks. This guarantees cleanup
1110 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001111 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001112 Context.BoolTy, RParenLoc));
Steve Naroffd6163f32008-09-05 22:11:13 +00001113 const FunctionType *FuncT;
1114 if (!Fn->getType()->isBlockPointerType()) {
1115 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1116 // have type pointer to function".
1117 const PointerType *PT = Fn->getType()->getAsPointerType();
1118 if (PT == 0)
1119 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1120 Fn->getSourceRange());
1121 FuncT = PT->getPointeeType()->getAsFunctionType();
1122 } else { // This is a block call.
1123 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1124 getAsFunctionType();
1125 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001126 if (FuncT == 0)
Chris Lattner61000b12008-08-14 04:33:24 +00001127 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1128 Fn->getSourceRange());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001129
1130 // We know the result type of the call, set it.
1131 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +00001132
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001133 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001134 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1135 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001136 unsigned NumArgsInProto = Proto->getNumArgs();
1137 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001138
Chris Lattner3e254fb2008-04-08 04:40:51 +00001139 // If too few arguments are available (and we don't have default
1140 // arguments for the remaining parameters), don't make the call.
1141 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +00001142 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001143 // Use default arguments for missing arguments
1144 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +00001145 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001146 } else
Steve Naroffd6163f32008-09-05 22:11:13 +00001147 return Diag(RParenLoc,
1148 !Fn->getType()->isBlockPointerType()
1149 ? diag::err_typecheck_call_too_few_args
1150 : diag::err_typecheck_block_too_few_args,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001151 Fn->getSourceRange());
1152 }
1153
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001154 // If too many are passed and not variadic, error on the extras and drop
1155 // them.
1156 if (NumArgs > NumArgsInProto) {
1157 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001158 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffd6163f32008-09-05 22:11:13 +00001159 !Fn->getType()->isBlockPointerType()
1160 ? diag::err_typecheck_call_too_many_args
1161 : diag::err_typecheck_block_too_many_args,
1162 Fn->getSourceRange(),
Chris Lattner4b009652007-07-25 00:24:17 +00001163 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001164 Args[NumArgs-1]->getLocEnd()));
1165 // This deletes the extra arguments.
1166 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001167 }
1168 NumArgsToCheck = NumArgsInProto;
1169 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001170
Chris Lattner4b009652007-07-25 00:24:17 +00001171 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001172 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001173 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001174
1175 Expr *Arg;
1176 if (i < NumArgs)
1177 Arg = Args[i];
1178 else
1179 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001180 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001181
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001182 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +00001183 AssignConvertType ConvTy =
1184 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001185 TheCall->setArg(i, Arg);
Eli Friedman583c31e2008-09-02 05:09:35 +00001186
Chris Lattner005ed752008-01-04 18:04:52 +00001187 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1188 ArgType, Arg, "passing"))
1189 return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001190 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001191
1192 // If this is a variadic call, handle args passed through "...".
1193 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001194 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001195 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1196 Expr *Arg = Args[i];
1197 DefaultArgumentPromotion(Arg);
1198 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001199 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001200 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001201 } else {
1202 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1203
Steve Naroffdb65e052007-08-28 23:30:39 +00001204 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001205 for (unsigned i = 0; i != NumArgs; i++) {
1206 Expr *Arg = Args[i];
1207 DefaultArgumentPromotion(Arg);
1208 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001209 }
Chris Lattner4b009652007-07-25 00:24:17 +00001210 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001211
Chris Lattner2e64c072007-08-10 20:18:51 +00001212 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001213 if (FDecl)
1214 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001215
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001216 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001217}
1218
1219Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001220ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001221 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001222 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001223 QualType literalType = QualType::getFromOpaquePtr(Ty);
1224 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001225 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001226 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001227
Eli Friedman8c2173d2008-05-20 05:22:08 +00001228 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001229 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001230 return Diag(LParenLoc,
1231 diag::err_variable_object_no_init,
1232 SourceRange(LParenLoc,
1233 literalExpr->getSourceRange().getEnd()));
1234 } else if (literalType->isIncompleteType()) {
1235 return Diag(LParenLoc,
1236 diag::err_typecheck_decl_incomplete_type,
1237 literalType.getAsString(),
1238 SourceRange(LParenLoc,
1239 literalExpr->getSourceRange().getEnd()));
1240 }
1241
Steve Narofff0b23542008-01-10 22:15:12 +00001242 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +00001243 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001244
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001245 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001246 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001247 if (CheckForConstantInitializer(literalExpr, literalType))
1248 return true;
1249 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001250 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1251 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,
Chris Lattnerce236e72008-10-26 23:35:51 +00001256 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001257 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001258 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001259
Steve Naroff0acc9c92007-09-15 18:49:24 +00001260 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001261 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001262
Chris Lattner48d7f382008-04-02 04:24:33 +00001263 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1264 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1265 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001266}
1267
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001268/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001269bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001270 UsualUnaryConversions(castExpr);
1271
1272 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1273 // type needs to be scalar.
1274 if (castType->isVoidType()) {
1275 // Cast to void allows any expr type.
1276 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1277 // GCC struct/union extension: allow cast to self.
1278 if (Context.getCanonicalType(castType) !=
1279 Context.getCanonicalType(castExpr->getType()) ||
1280 (!castType->isStructureType() && !castType->isUnionType())) {
1281 // Reject any other conversions to non-scalar types.
1282 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1283 castType.getAsString(), castExpr->getSourceRange());
1284 }
1285
1286 // accept this, but emit an ext-warn.
1287 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1288 castType.getAsString(), castExpr->getSourceRange());
1289 } else if (!castExpr->getType()->isScalarType() &&
1290 !castExpr->getType()->isVectorType()) {
1291 return Diag(castExpr->getLocStart(),
1292 diag::err_typecheck_expect_scalar_operand,
1293 castExpr->getType().getAsString(),castExpr->getSourceRange());
1294 } else if (castExpr->getType()->isVectorType()) {
1295 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1296 return true;
1297 } else if (castType->isVectorType()) {
1298 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1299 return true;
1300 }
1301 return false;
1302}
1303
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001304bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001305 assert(VectorTy->isVectorType() && "Not a vector type!");
1306
1307 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001308 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001309 return Diag(R.getBegin(),
1310 Ty->isVectorType() ?
1311 diag::err_invalid_conversion_between_vectors :
1312 diag::err_invalid_conversion_between_vector_and_integer,
1313 VectorTy.getAsString().c_str(),
1314 Ty.getAsString().c_str(), R);
1315 } else
1316 return Diag(R.getBegin(),
1317 diag::err_invalid_conversion_between_vector_and_scalar,
1318 VectorTy.getAsString().c_str(),
1319 Ty.getAsString().c_str(), R);
1320
1321 return false;
1322}
1323
Chris Lattner4b009652007-07-25 00:24:17 +00001324Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001325ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001326 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001327 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001328
1329 Expr *castExpr = static_cast<Expr*>(Op);
1330 QualType castType = QualType::getFromOpaquePtr(Ty);
1331
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001332 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1333 return true;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001334 return new ExplicitCastExpr(castType, castExpr, LParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001335}
1336
Chris Lattner98a425c2007-11-26 01:40:58 +00001337/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1338/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001339inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1340 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1341 UsualUnaryConversions(cond);
1342 UsualUnaryConversions(lex);
1343 UsualUnaryConversions(rex);
1344 QualType condT = cond->getType();
1345 QualType lexT = lex->getType();
1346 QualType rexT = rex->getType();
1347
1348 // first, check the condition.
1349 if (!condT->isScalarType()) { // C99 6.5.15p2
1350 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1351 condT.getAsString());
1352 return QualType();
1353 }
Chris Lattner992ae932008-01-06 22:42:25 +00001354
1355 // Now check the two expressions.
1356
1357 // If both operands have arithmetic type, do the usual arithmetic conversions
1358 // to find a common type: C99 6.5.15p3,5.
1359 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001360 UsualArithmeticConversions(lex, rex);
1361 return lex->getType();
1362 }
Chris Lattner992ae932008-01-06 22:42:25 +00001363
1364 // If both operands are the same structure or union type, the result is that
1365 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001366 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001367 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001368 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001369 // "If both the operands have structure or union type, the result has
1370 // that type." This implies that CV qualifiers are dropped.
1371 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001372 }
Chris Lattner992ae932008-01-06 22:42:25 +00001373
1374 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001375 // The following || allows only one side to be void (a GCC-ism).
1376 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001377 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001378 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1379 rex->getSourceRange());
1380 if (!rexT->isVoidType())
1381 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001382 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001383 ImpCastExprToType(lex, Context.VoidTy);
1384 ImpCastExprToType(rex, Context.VoidTy);
1385 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001386 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001387 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1388 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001389 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1390 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001391 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001392 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001393 return lexT;
1394 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001395 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1396 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001397 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001398 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001399 return rexT;
1400 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001401 // Handle the case where both operands are pointers before we handle null
1402 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001403 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1404 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1405 // get the "pointed to" types
1406 QualType lhptee = LHSPT->getPointeeType();
1407 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001408
Chris Lattner71225142007-07-31 21:27:01 +00001409 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1410 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001411 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001412 // Figure out necessary qualifiers (C99 6.5.15p6)
1413 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001414 QualType destType = Context.getPointerType(destPointee);
1415 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1416 ImpCastExprToType(rex, destType); // promote to void*
1417 return destType;
1418 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001419 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001420 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001421 QualType destType = Context.getPointerType(destPointee);
1422 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1423 ImpCastExprToType(rex, destType); // promote to void*
1424 return destType;
1425 }
Chris Lattner4b009652007-07-25 00:24:17 +00001426
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001427 QualType compositeType = lexT;
1428
1429 // If either type is an Objective-C object type then check
1430 // compatibility according to Objective-C.
1431 if (Context.isObjCObjectPointerType(lexT) ||
1432 Context.isObjCObjectPointerType(rexT)) {
1433 // If both operands are interfaces and either operand can be
1434 // assigned to the other, use that type as the composite
1435 // type. This allows
1436 // xxx ? (A*) a : (B*) b
1437 // where B is a subclass of A.
1438 //
1439 // Additionally, as for assignment, if either type is 'id'
1440 // allow silent coercion. Finally, if the types are
1441 // incompatible then make sure to use 'id' as the composite
1442 // type so the result is acceptable for sending messages to.
1443
1444 // FIXME: This code should not be localized to here. Also this
1445 // should use a compatible check instead of abusing the
1446 // canAssignObjCInterfaces code.
1447 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1448 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1449 if (LHSIface && RHSIface &&
1450 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1451 compositeType = lexT;
1452 } else if (LHSIface && RHSIface &&
1453 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1454 compositeType = rexT;
1455 } else if (Context.isObjCIdType(lhptee) ||
1456 Context.isObjCIdType(rhptee)) {
1457 // FIXME: This code looks wrong, because isObjCIdType checks
1458 // the struct but getObjCIdType returns the pointer to
1459 // struct. This is horrible and should be fixed.
1460 compositeType = Context.getObjCIdType();
1461 } else {
1462 QualType incompatTy = Context.getObjCIdType();
1463 ImpCastExprToType(lex, incompatTy);
1464 ImpCastExprToType(rex, incompatTy);
1465 return incompatTy;
1466 }
1467 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1468 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001469 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001470 lexT.getAsString(), rexT.getAsString(),
1471 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001472 // In this situation, we assume void* type. No especially good
1473 // reason, but this is what gcc does, and we do have to pick
1474 // to get a consistent AST.
1475 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001476 ImpCastExprToType(lex, incompatTy);
1477 ImpCastExprToType(rex, incompatTy);
1478 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001479 }
1480 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001481 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1482 // differently qualified versions of compatible types, the result type is
1483 // a pointer to an appropriately qualified version of the *composite*
1484 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001485 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001486 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001487 ImpCastExprToType(lex, compositeType);
1488 ImpCastExprToType(rex, compositeType);
1489 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001490 }
Chris Lattner4b009652007-07-25 00:24:17 +00001491 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001492 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1493 // evaluates to "struct objc_object *" (and is handled above when comparing
1494 // id with statically typed objects).
1495 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1496 // GCC allows qualified id and any Objective-C type to devolve to
1497 // id. Currently localizing to here until clear this should be
1498 // part of ObjCQualifiedIdTypesAreCompatible.
1499 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1500 (lexT->isObjCQualifiedIdType() &&
1501 Context.isObjCObjectPointerType(rexT)) ||
1502 (rexT->isObjCQualifiedIdType() &&
1503 Context.isObjCObjectPointerType(lexT))) {
1504 // FIXME: This is not the correct composite type. This only
1505 // happens to work because id can more or less be used anywhere,
1506 // however this may change the type of method sends.
1507 // FIXME: gcc adds some type-checking of the arguments and emits
1508 // (confusing) incompatible comparison warnings in some
1509 // cases. Investigate.
1510 QualType compositeType = Context.getObjCIdType();
1511 ImpCastExprToType(lex, compositeType);
1512 ImpCastExprToType(rex, compositeType);
1513 return compositeType;
1514 }
1515 }
1516
Steve Naroff3eac7692008-09-10 19:17:48 +00001517 // Selection between block pointer types is ok as long as they are the same.
1518 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1519 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1520 return lexT;
1521
Chris Lattner992ae932008-01-06 22:42:25 +00001522 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001523 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1524 lexT.getAsString(), rexT.getAsString(),
1525 lex->getSourceRange(), rex->getSourceRange());
1526 return QualType();
1527}
1528
Steve Naroff87d58b42007-09-16 03:34:24 +00001529/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001530/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001531Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001532 SourceLocation ColonLoc,
1533 ExprTy *Cond, ExprTy *LHS,
1534 ExprTy *RHS) {
1535 Expr *CondExpr = (Expr *) Cond;
1536 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001537
1538 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1539 // was the condition.
1540 bool isLHSNull = LHSExpr == 0;
1541 if (isLHSNull)
1542 LHSExpr = CondExpr;
1543
Chris Lattner4b009652007-07-25 00:24:17 +00001544 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1545 RHSExpr, QuestionLoc);
1546 if (result.isNull())
1547 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001548 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1549 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001550}
1551
Chris Lattner4b009652007-07-25 00:24:17 +00001552
1553// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1554// being closely modeled after the C99 spec:-). The odd characteristic of this
1555// routine is it effectively iqnores the qualifiers on the top level pointee.
1556// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1557// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001558Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001559Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1560 QualType lhptee, rhptee;
1561
1562 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001563 lhptee = lhsType->getAsPointerType()->getPointeeType();
1564 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001565
1566 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001567 lhptee = Context.getCanonicalType(lhptee);
1568 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001569
Chris Lattner005ed752008-01-04 18:04:52 +00001570 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001571
1572 // C99 6.5.16.1p1: This following citation is common to constraints
1573 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1574 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001575 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001576 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001577 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001578
1579 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1580 // incomplete type and the other is a pointer to a qualified or unqualified
1581 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001582 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001583 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001584 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001585
1586 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001587 assert(rhptee->isFunctionType());
1588 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001589 }
1590
1591 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001592 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001593 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001594
1595 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001596 assert(lhptee->isFunctionType());
1597 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001598 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001599
1600 // Check for ObjC interfaces
1601 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1602 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1603 if (LHSIface && RHSIface &&
1604 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1605 return ConvTy;
1606
1607 // ID acts sort of like void* for ObjC interfaces
1608 if (LHSIface && Context.isObjCIdType(rhptee))
1609 return ConvTy;
1610 if (RHSIface && Context.isObjCIdType(lhptee))
1611 return ConvTy;
1612
Chris Lattner4b009652007-07-25 00:24:17 +00001613 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1614 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001615 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1616 rhptee.getUnqualifiedType()))
1617 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001618 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001619}
1620
Steve Naroff3454b6c2008-09-04 15:10:53 +00001621/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1622/// block pointer types are compatible or whether a block and normal pointer
1623/// are compatible. It is more restrict than comparing two function pointer
1624// types.
1625Sema::AssignConvertType
1626Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1627 QualType rhsType) {
1628 QualType lhptee, rhptee;
1629
1630 // get the "pointed to" type (ignoring qualifiers at the top level)
1631 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1632 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1633
1634 // make sure we operate on the canonical type
1635 lhptee = Context.getCanonicalType(lhptee);
1636 rhptee = Context.getCanonicalType(rhptee);
1637
1638 AssignConvertType ConvTy = Compatible;
1639
1640 // For blocks we enforce that qualifiers are identical.
1641 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1642 ConvTy = CompatiblePointerDiscardsQualifiers;
1643
1644 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1645 return IncompatibleBlockPointer;
1646 return ConvTy;
1647}
1648
Chris Lattner4b009652007-07-25 00:24:17 +00001649/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1650/// has code to accommodate several GCC extensions when type checking
1651/// pointers. Here are some objectionable examples that GCC considers warnings:
1652///
1653/// int a, *pint;
1654/// short *pshort;
1655/// struct foo *pfoo;
1656///
1657/// pint = pshort; // warning: assignment from incompatible pointer type
1658/// a = pint; // warning: assignment makes integer from pointer without a cast
1659/// pint = a; // warning: assignment makes pointer from integer without a cast
1660/// pint = pfoo; // warning: assignment from incompatible pointer type
1661///
1662/// As a result, the code for dealing with pointers is more complex than the
1663/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001664///
Chris Lattner005ed752008-01-04 18:04:52 +00001665Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001666Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001667 // Get canonical types. We're not formatting these types, just comparing
1668 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001669 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1670 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001671
1672 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001673 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001674
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001675 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001676 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001677 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001678 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001679 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001680
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001681 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1682 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001683 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001684 // Relax integer conversions like we do for pointers below.
1685 if (rhsType->isIntegerType())
1686 return IntToPointer;
1687 if (lhsType->isIntegerType())
1688 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00001689 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001690 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001691
Nate Begemanc5f0f652008-07-14 18:02:46 +00001692 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001693 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001694 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1695 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001696 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001697
Nate Begemanc5f0f652008-07-14 18:02:46 +00001698 // If we are allowing lax vector conversions, and LHS and RHS are both
1699 // vectors, the total size only needs to be the same. This is a bitcast;
1700 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001701 if (getLangOptions().LaxVectorConversions &&
1702 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001703 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1704 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001705 }
1706 return Incompatible;
1707 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001708
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001709 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001710 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001711
Chris Lattner390564e2008-04-07 06:49:41 +00001712 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001713 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001714 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001715
Chris Lattner390564e2008-04-07 06:49:41 +00001716 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001717 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001718
Steve Naroffa982c712008-09-29 18:10:17 +00001719 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00001720 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff3454b6c2008-09-04 15:10:53 +00001721 return BlockVoidPointer;
Steve Naroffa982c712008-09-29 18:10:17 +00001722
1723 // Treat block pointers as objects.
1724 if (getLangOptions().ObjC1 &&
1725 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1726 return Compatible;
1727 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001728 return Incompatible;
1729 }
1730
1731 if (isa<BlockPointerType>(lhsType)) {
1732 if (rhsType->isIntegerType())
1733 return IntToPointer;
1734
Steve Naroffa982c712008-09-29 18:10:17 +00001735 // Treat block pointers as objects.
1736 if (getLangOptions().ObjC1 &&
1737 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1738 return Compatible;
1739
Steve Naroff3454b6c2008-09-04 15:10:53 +00001740 if (rhsType->isBlockPointerType())
1741 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1742
1743 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1744 if (RHSPT->getPointeeType()->isVoidType())
1745 return BlockVoidPointer;
1746 }
Chris Lattner1853da22008-01-04 23:18:45 +00001747 return Incompatible;
1748 }
1749
Chris Lattner390564e2008-04-07 06:49:41 +00001750 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001751 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001752 if (lhsType == Context.BoolTy)
1753 return Compatible;
1754
1755 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001756 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001757
Chris Lattner390564e2008-04-07 06:49:41 +00001758 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001759 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001760
1761 if (isa<BlockPointerType>(lhsType) &&
1762 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1763 return BlockVoidPointer;
Chris Lattner1853da22008-01-04 23:18:45 +00001764 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001765 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001766
Chris Lattner1853da22008-01-04 23:18:45 +00001767 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001768 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001769 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001770 }
1771 return Incompatible;
1772}
1773
Chris Lattner005ed752008-01-04 18:04:52 +00001774Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001775Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001776 if (getLangOptions().CPlusPlus) {
1777 if (!lhsType->isRecordType()) {
1778 // C++ 5.17p3: If the left operand is not of class type, the
1779 // expression is implicitly converted (C++ 4) to the
1780 // cv-unqualified type of the left operand.
Douglas Gregorbb461502008-10-24 04:54:22 +00001781 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001782 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00001783 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001784 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001785 }
1786
1787 // FIXME: Currently, we fall through and treat C++ classes like C
1788 // structures.
1789 }
1790
Steve Naroffcdee22d2007-11-27 17:58:44 +00001791 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1792 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00001793 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1794 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001795 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001796 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001797 return Compatible;
1798 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001799
1800 // We don't allow conversion of non-null-pointer constants to integers.
1801 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1802 return IntToBlockPointer;
1803
Chris Lattner5f505bf2007-10-16 02:55:40 +00001804 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001805 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001806 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001807 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001808 //
Douglas Gregorf8e92702008-10-24 15:36:09 +00001809 // Suppress this for references: C++ 8.5.3p5. FIXME: revisit when references
Chris Lattner5f505bf2007-10-16 02:55:40 +00001810 // are better understood.
1811 if (!lhsType->isReferenceType())
1812 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001813
Chris Lattner005ed752008-01-04 18:04:52 +00001814 Sema::AssignConvertType result =
1815 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001816
1817 // C99 6.5.16.1p2: The value of the right operand is converted to the
1818 // type of the assignment expression.
1819 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001820 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001821 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001822}
1823
Chris Lattner005ed752008-01-04 18:04:52 +00001824Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001825Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1826 return CheckAssignmentConstraints(lhsType, rhsType);
1827}
1828
Chris Lattner2c8bff72007-12-12 05:47:28 +00001829QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001830 Diag(loc, diag::err_typecheck_invalid_operands,
1831 lex->getType().getAsString(), rex->getType().getAsString(),
1832 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001833 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001834}
1835
1836inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1837 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001838 // For conversion purposes, we ignore any qualifiers.
1839 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001840 QualType lhsType =
1841 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1842 QualType rhsType =
1843 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001844
Nate Begemanc5f0f652008-07-14 18:02:46 +00001845 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001846 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001847 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001848
Nate Begemanc5f0f652008-07-14 18:02:46 +00001849 // Handle the case of a vector & extvector type of the same size and element
1850 // type. It would be nice if we only had one vector type someday.
1851 if (getLangOptions().LaxVectorConversions)
1852 if (const VectorType *LV = lhsType->getAsVectorType())
1853 if (const VectorType *RV = rhsType->getAsVectorType())
1854 if (LV->getElementType() == RV->getElementType() &&
1855 LV->getNumElements() == RV->getNumElements())
1856 return lhsType->isExtVectorType() ? lhsType : rhsType;
1857
1858 // If the lhs is an extended vector and the rhs is a scalar of the same type
1859 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001860 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001861 QualType eltType = V->getElementType();
1862
1863 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1864 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1865 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001866 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001867 return lhsType;
1868 }
1869 }
1870
Nate Begemanc5f0f652008-07-14 18:02:46 +00001871 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001872 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001873 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001874 QualType eltType = V->getElementType();
1875
1876 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1877 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1878 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001879 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001880 return rhsType;
1881 }
1882 }
1883
Chris Lattner4b009652007-07-25 00:24:17 +00001884 // You cannot convert between vector values of different size.
1885 Diag(loc, diag::err_typecheck_vector_not_convertable,
1886 lex->getType().getAsString(), rex->getType().getAsString(),
1887 lex->getSourceRange(), rex->getSourceRange());
1888 return QualType();
1889}
1890
1891inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001892 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001893{
1894 QualType lhsType = lex->getType(), rhsType = rex->getType();
1895
1896 if (lhsType->isVectorType() || rhsType->isVectorType())
1897 return CheckVectorOperands(loc, lex, rex);
1898
Steve Naroff8f708362007-08-24 19:07:16 +00001899 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001900
Chris Lattner4b009652007-07-25 00:24:17 +00001901 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001902 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001903 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001904}
1905
1906inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001907 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001908{
1909 QualType lhsType = lex->getType(), rhsType = rex->getType();
1910
Steve Naroff8f708362007-08-24 19:07:16 +00001911 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001912
Chris Lattner4b009652007-07-25 00:24:17 +00001913 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001914 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001915 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001916}
1917
1918inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001919 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001920{
1921 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1922 return CheckVectorOperands(loc, lex, rex);
1923
Steve Naroff8f708362007-08-24 19:07:16 +00001924 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001925
Chris Lattner4b009652007-07-25 00:24:17 +00001926 // handle the common case first (both operands are arithmetic).
1927 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001928 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001929
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001930 // Put any potential pointer into PExp
1931 Expr* PExp = lex, *IExp = rex;
1932 if (IExp->getType()->isPointerType())
1933 std::swap(PExp, IExp);
1934
1935 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1936 if (IExp->getType()->isIntegerType()) {
1937 // Check for arithmetic on pointers to incomplete types
1938 if (!PTy->getPointeeType()->isObjectType()) {
1939 if (PTy->getPointeeType()->isVoidType()) {
1940 Diag(loc, diag::ext_gnu_void_ptr,
1941 lex->getSourceRange(), rex->getSourceRange());
1942 } else {
1943 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1944 lex->getType().getAsString(), lex->getSourceRange());
1945 return QualType();
1946 }
1947 }
1948 return PExp->getType();
1949 }
1950 }
1951
Chris Lattner2c8bff72007-12-12 05:47:28 +00001952 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001953}
1954
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001955// C99 6.5.6
1956QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1957 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001958 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1959 return CheckVectorOperands(loc, lex, rex);
1960
Steve Naroff8f708362007-08-24 19:07:16 +00001961 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001962
Chris Lattnerf6da2912007-12-09 21:53:25 +00001963 // Enforce type constraints: C99 6.5.6p3.
1964
1965 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001966 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001967 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001968
1969 // Either ptr - int or ptr - ptr.
1970 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001971 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001972
Chris Lattnerf6da2912007-12-09 21:53:25 +00001973 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001974 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001975 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001976 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001977 Diag(loc, diag::ext_gnu_void_ptr,
1978 lex->getSourceRange(), rex->getSourceRange());
1979 } else {
1980 Diag(loc, diag::err_typecheck_sub_ptr_object,
1981 lex->getType().getAsString(), lex->getSourceRange());
1982 return QualType();
1983 }
1984 }
1985
1986 // The result type of a pointer-int computation is the pointer type.
1987 if (rex->getType()->isIntegerType())
1988 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001989
Chris Lattnerf6da2912007-12-09 21:53:25 +00001990 // Handle pointer-pointer subtractions.
1991 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001992 QualType rpointee = RHSPTy->getPointeeType();
1993
Chris Lattnerf6da2912007-12-09 21:53:25 +00001994 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001995 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001996 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001997 if (rpointee->isVoidType()) {
1998 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001999 Diag(loc, diag::ext_gnu_void_ptr,
2000 lex->getSourceRange(), rex->getSourceRange());
2001 } else {
2002 Diag(loc, diag::err_typecheck_sub_ptr_object,
2003 rex->getType().getAsString(), rex->getSourceRange());
2004 return QualType();
2005 }
2006 }
2007
2008 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002009 if (!Context.typesAreCompatible(
2010 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2011 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002012 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
2013 lex->getType().getAsString(), rex->getType().getAsString(),
2014 lex->getSourceRange(), rex->getSourceRange());
2015 return QualType();
2016 }
2017
2018 return Context.getPointerDiffType();
2019 }
2020 }
2021
Chris Lattner2c8bff72007-12-12 05:47:28 +00002022 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002023}
2024
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002025// C99 6.5.7
2026QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2027 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002028 // C99 6.5.7p2: Each of the operands shall have integer type.
2029 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
2030 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002031
Chris Lattner2c8bff72007-12-12 05:47:28 +00002032 // Shifts don't perform usual arithmetic conversions, they just do integer
2033 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002034 if (!isCompAssign)
2035 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002036 UsualUnaryConversions(rex);
2037
2038 // "The type of the result is that of the promoted left operand."
2039 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002040}
2041
Eli Friedman0d9549b2008-08-22 00:56:42 +00002042static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2043 ASTContext& Context) {
2044 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2045 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2046 // ID acts sort of like void* for ObjC interfaces
2047 if (LHSIface && Context.isObjCIdType(RHS))
2048 return true;
2049 if (RHSIface && Context.isObjCIdType(LHS))
2050 return true;
2051 if (!LHSIface || !RHSIface)
2052 return false;
2053 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2054 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2055}
2056
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002057// C99 6.5.8
2058QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2059 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002060 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2061 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
2062
Chris Lattner254f3bc2007-08-26 01:18:55 +00002063 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002064 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2065 UsualArithmeticConversions(lex, rex);
2066 else {
2067 UsualUnaryConversions(lex);
2068 UsualUnaryConversions(rex);
2069 }
Chris Lattner4b009652007-07-25 00:24:17 +00002070 QualType lType = lex->getType();
2071 QualType rType = rex->getType();
2072
Ted Kremenek486509e2007-10-29 17:13:39 +00002073 // For non-floating point types, check for self-comparisons of the form
2074 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2075 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002076 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002077 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2078 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002079 if (DRL->getDecl() == DRR->getDecl())
2080 Diag(loc, diag::warn_selfcomparison);
2081 }
2082
Chris Lattner254f3bc2007-08-26 01:18:55 +00002083 if (isRelational) {
2084 if (lType->isRealType() && rType->isRealType())
2085 return Context.IntTy;
2086 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002087 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002088 if (lType->isFloatingType()) {
2089 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00002090 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002091 }
2092
Chris Lattner254f3bc2007-08-26 01:18:55 +00002093 if (lType->isArithmeticType() && rType->isArithmeticType())
2094 return Context.IntTy;
2095 }
Chris Lattner4b009652007-07-25 00:24:17 +00002096
Chris Lattner22be8422007-08-26 01:10:14 +00002097 bool LHSIsNull = lex->isNullPointerConstant(Context);
2098 bool RHSIsNull = rex->isNullPointerConstant(Context);
2099
Chris Lattner254f3bc2007-08-26 01:18:55 +00002100 // All of the following pointer related warnings are GCC extensions, except
2101 // when handling null pointer constants. One day, we can consider making them
2102 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002103 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002104 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002105 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002106 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002107 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002108
Steve Naroff3b435622007-11-13 14:57:38 +00002109 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002110 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2111 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002112 RCanPointeeTy.getUnqualifiedType()) &&
2113 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroff4462cb02007-08-16 21:48:38 +00002114 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2115 lType.getAsString(), rType.getAsString(),
2116 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002117 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002118 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002119 return Context.IntTy;
2120 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002121 // Handle block pointer types.
2122 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2123 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2124 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2125
2126 if (!LHSIsNull && !RHSIsNull &&
2127 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2128 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2129 lType.getAsString(), rType.getAsString(),
2130 lex->getSourceRange(), rex->getSourceRange());
2131 }
2132 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2133 return Context.IntTy;
2134 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002135 // Allow block pointers to be compared with null pointer constants.
2136 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2137 (lType->isPointerType() && rType->isBlockPointerType())) {
2138 if (!LHSIsNull && !RHSIsNull) {
2139 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2140 lType.getAsString(), rType.getAsString(),
2141 lex->getSourceRange(), rex->getSourceRange());
2142 }
2143 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2144 return Context.IntTy;
2145 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002146
Steve Naroff936c4362008-06-03 14:04:54 +00002147 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002148 if ((lType->isPointerType() || rType->isPointerType()) &&
2149 !Context.typesAreCompatible(lType, rType)) {
2150 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2151 lType.getAsString(), rType.getAsString(),
2152 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002153 ImpCastExprToType(rex, lType);
Steve Naroff792800d2008-10-22 22:40:28 +00002154 return Context.IntTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002155 }
Steve Naroff936c4362008-06-03 14:04:54 +00002156 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2157 ImpCastExprToType(rex, lType);
2158 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002159 } else {
2160 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
2161 Diag(loc, diag::warn_incompatible_qualified_id_operands,
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002162 lType.getAsString(), rType.getAsString(),
Steve Naroff19608432008-10-14 22:18:38 +00002163 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002164 ImpCastExprToType(rex, lType);
Steve Naroff792800d2008-10-22 22:40:28 +00002165 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002166 }
Steve Naroff936c4362008-06-03 14:04:54 +00002167 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002168 }
Steve Naroff936c4362008-06-03 14:04:54 +00002169 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2170 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002171 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002172 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2173 lType.getAsString(), rType.getAsString(),
2174 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002175 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002176 return Context.IntTy;
2177 }
Steve Naroff936c4362008-06-03 14:04:54 +00002178 if (lType->isIntegerType() &&
2179 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002180 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002181 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2182 lType.getAsString(), rType.getAsString(),
2183 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002184 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002185 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002186 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002187 // Handle block pointers.
2188 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2189 if (!RHSIsNull)
2190 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2191 lType.getAsString(), rType.getAsString(),
2192 lex->getSourceRange(), rex->getSourceRange());
2193 ImpCastExprToType(rex, lType); // promote the integer to pointer
2194 return Context.IntTy;
2195 }
2196 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2197 if (!LHSIsNull)
2198 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2199 lType.getAsString(), rType.getAsString(),
2200 lex->getSourceRange(), rex->getSourceRange());
2201 ImpCastExprToType(lex, rType); // promote the integer to pointer
2202 return Context.IntTy;
2203 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00002204 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002205}
2206
Nate Begemanc5f0f652008-07-14 18:02:46 +00002207/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2208/// operates on extended vector types. Instead of producing an IntTy result,
2209/// like a scalar comparison, a vector comparison produces a vector of integer
2210/// types.
2211QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2212 SourceLocation loc,
2213 bool isRelational) {
2214 // Check to make sure we're operating on vectors of the same type and width,
2215 // Allowing one side to be a scalar of element type.
2216 QualType vType = CheckVectorOperands(loc, lex, rex);
2217 if (vType.isNull())
2218 return vType;
2219
2220 QualType lType = lex->getType();
2221 QualType rType = rex->getType();
2222
2223 // For non-floating point types, check for self-comparisons of the form
2224 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2225 // often indicate logic errors in the program.
2226 if (!lType->isFloatingType()) {
2227 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2228 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2229 if (DRL->getDecl() == DRR->getDecl())
2230 Diag(loc, diag::warn_selfcomparison);
2231 }
2232
2233 // Check for comparisons of floating point operands using != and ==.
2234 if (!isRelational && lType->isFloatingType()) {
2235 assert (rType->isFloatingType());
2236 CheckFloatComparison(loc,lex,rex);
2237 }
2238
2239 // Return the type for the comparison, which is the same as vector type for
2240 // integer vectors, or an integer type of identical size and number of
2241 // elements for floating point vectors.
2242 if (lType->isIntegerType())
2243 return lType;
2244
2245 const VectorType *VTy = lType->getAsVectorType();
2246
2247 // FIXME: need to deal with non-32b int / non-64b long long
2248 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2249 if (TypeSize == 32) {
2250 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2251 }
2252 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2253 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2254}
2255
Chris Lattner4b009652007-07-25 00:24:17 +00002256inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00002257 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002258{
2259 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2260 return CheckVectorOperands(loc, lex, rex);
2261
Steve Naroff8f708362007-08-24 19:07:16 +00002262 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002263
2264 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002265 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002266 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002267}
2268
2269inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
2270 Expr *&lex, Expr *&rex, SourceLocation loc)
2271{
2272 UsualUnaryConversions(lex);
2273 UsualUnaryConversions(rex);
2274
Eli Friedmanbea3f842008-05-13 20:16:47 +00002275 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002276 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002277 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002278}
2279
2280inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00002281 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00002282{
2283 QualType lhsType = lex->getType();
2284 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner25168a52008-07-26 21:30:36 +00002285 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002286
2287 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00002288 case Expr::MLV_Valid:
2289 break;
2290 case Expr::MLV_ConstQualified:
2291 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2292 return QualType();
2293 case Expr::MLV_ArrayType:
2294 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2295 lhsType.getAsString(), lex->getSourceRange());
2296 return QualType();
2297 case Expr::MLV_NotObjectType:
2298 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2299 lhsType.getAsString(), lex->getSourceRange());
2300 return QualType();
2301 case Expr::MLV_InvalidExpression:
2302 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2303 lex->getSourceRange());
2304 return QualType();
2305 case Expr::MLV_IncompleteType:
2306 case Expr::MLV_IncompleteVoidType:
2307 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2308 lhsType.getAsString(), lex->getSourceRange());
2309 return QualType();
2310 case Expr::MLV_DuplicateVectorComponents:
2311 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2312 lex->getSourceRange());
2313 return QualType();
Steve Naroff076d6cb2008-09-26 14:41:28 +00002314 case Expr::MLV_NotBlockQualified:
2315 Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2316 lex->getSourceRange());
2317 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002318 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002319
Chris Lattner005ed752008-01-04 18:04:52 +00002320 AssignConvertType ConvTy;
Chris Lattner34c85082008-08-21 18:04:13 +00002321 if (compoundType.isNull()) {
2322 // Simple assignment "x = y".
Chris Lattner005ed752008-01-04 18:04:52 +00002323 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner34c85082008-08-21 18:04:13 +00002324
2325 // If the RHS is a unary plus or minus, check to see if they = and + are
2326 // right next to each other. If so, the user may have typo'd "x =+ 4"
2327 // instead of "x += 4".
2328 Expr *RHSCheck = rex;
2329 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2330 RHSCheck = ICE->getSubExpr();
2331 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2332 if ((UO->getOpcode() == UnaryOperator::Plus ||
2333 UO->getOpcode() == UnaryOperator::Minus) &&
2334 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2335 // Only if the two operators are exactly adjacent.
2336 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2337 Diag(loc, diag::warn_not_compound_assign,
2338 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2339 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2340 }
2341 } else {
2342 // Compound assignment "x += y"
Chris Lattner005ed752008-01-04 18:04:52 +00002343 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner34c85082008-08-21 18:04:13 +00002344 }
Chris Lattner005ed752008-01-04 18:04:52 +00002345
2346 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2347 rex, "assigning"))
2348 return QualType();
2349
Chris Lattner4b009652007-07-25 00:24:17 +00002350 // C99 6.5.16p3: The type of an assignment expression is the type of the
2351 // left operand unless the left operand has qualified type, in which case
2352 // it is the unqualified version of the type of the left operand.
2353 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2354 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002355 // C++ 5.17p1: the type of the assignment expression is that of its left
2356 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00002357 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002358}
2359
2360inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2361 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00002362
2363 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2364 DefaultFunctionArrayConversion(rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002365 return rex->getType();
2366}
2367
2368/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2369/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2370QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2371 QualType resType = op->getType();
2372 assert(!resType.isNull() && "no type for increment/decrement expression");
2373
Steve Naroffd30e1932007-08-24 17:20:07 +00002374 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00002375 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002376 if (pt->getPointeeType()->isVoidType()) {
2377 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2378 } else if (!pt->getPointeeType()->isObjectType()) {
2379 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00002380 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2381 resType.getAsString(), op->getSourceRange());
2382 return QualType();
2383 }
Steve Naroffd30e1932007-08-24 17:20:07 +00002384 } else if (!resType->isRealType()) {
2385 if (resType->isComplexType())
2386 // C99 does not support ++/-- on complex types.
2387 Diag(OpLoc, diag::ext_integer_increment_complex,
2388 resType.getAsString(), op->getSourceRange());
2389 else {
2390 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2391 resType.getAsString(), op->getSourceRange());
2392 return QualType();
2393 }
Chris Lattner4b009652007-07-25 00:24:17 +00002394 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002395 // At this point, we know we have a real, complex or pointer type.
2396 // Now make sure the operand is a modifiable lvalue.
Chris Lattner25168a52008-07-26 21:30:36 +00002397 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002398 if (mlval != Expr::MLV_Valid) {
2399 // FIXME: emit a more precise diagnostic...
2400 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2401 op->getSourceRange());
2402 return QualType();
2403 }
2404 return resType;
2405}
2406
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002407/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002408/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002409/// where the declaration is needed for type checking. We only need to
2410/// handle cases when the expression references a function designator
2411/// or is an lvalue. Here are some examples:
2412/// - &(x) => x
2413/// - &*****f => f for f a function designator.
2414/// - &s.xx => s
2415/// - &s.zz[1].yy -> s, if zz is an array
2416/// - *(x + 1) -> x, if x is an array
2417/// - &"123"[2] -> 0
2418/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002419static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002420 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002421 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002422 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002423 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002424 // Fields cannot be declared with a 'register' storage class.
2425 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002426 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002427 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002428 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002429 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002430 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002431
Douglas Gregord2baafd2008-10-21 16:13:35 +00002432 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002433 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002434 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002435 return 0;
2436 else
2437 return VD;
2438 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002439 case Stmt::UnaryOperatorClass: {
2440 UnaryOperator *UO = cast<UnaryOperator>(E);
2441
2442 switch(UO->getOpcode()) {
2443 case UnaryOperator::Deref: {
2444 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002445 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2446 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2447 if (!VD || VD->getType()->isPointerType())
2448 return 0;
2449 return VD;
2450 }
2451 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002452 }
2453 case UnaryOperator::Real:
2454 case UnaryOperator::Imag:
2455 case UnaryOperator::Extension:
2456 return getPrimaryDecl(UO->getSubExpr());
2457 default:
2458 return 0;
2459 }
2460 }
2461 case Stmt::BinaryOperatorClass: {
2462 BinaryOperator *BO = cast<BinaryOperator>(E);
2463
2464 // Handle cases involving pointer arithmetic. The result of an
2465 // Assign or AddAssign is not an lvalue so they can be ignored.
2466
2467 // (x + n) or (n + x) => x
2468 if (BO->getOpcode() == BinaryOperator::Add) {
2469 if (BO->getLHS()->getType()->isPointerType()) {
2470 return getPrimaryDecl(BO->getLHS());
2471 } else if (BO->getRHS()->getType()->isPointerType()) {
2472 return getPrimaryDecl(BO->getRHS());
2473 }
2474 }
2475
2476 return 0;
2477 }
Chris Lattner4b009652007-07-25 00:24:17 +00002478 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002479 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002480 case Stmt::ImplicitCastExprClass:
2481 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002482 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002483 default:
2484 return 0;
2485 }
2486}
2487
2488/// CheckAddressOfOperand - The operand of & must be either a function
2489/// designator or an lvalue designating an object. If it is an lvalue, the
2490/// object cannot be declared with storage class register or be a bit field.
2491/// Note: The usual conversions are *not* applied to the operand of the &
2492/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2493QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002494 if (getLangOptions().C99) {
2495 // Implement C99-only parts of addressof rules.
2496 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2497 if (uOp->getOpcode() == UnaryOperator::Deref)
2498 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2499 // (assuming the deref expression is valid).
2500 return uOp->getSubExpr()->getType();
2501 }
2502 // Technically, there should be a check for array subscript
2503 // expressions here, but the result of one is always an lvalue anyway.
2504 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002505 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002506 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002507
2508 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002509 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2510 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002511 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2512 op->getSourceRange());
2513 return QualType();
2514 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002515 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2516 if (MemExpr->getMemberDecl()->isBitField()) {
2517 Diag(OpLoc, diag::err_typecheck_address_of,
2518 std::string("bit-field"), op->getSourceRange());
2519 return QualType();
2520 }
2521 // Check for Apple extension for accessing vector components.
2522 } else if (isa<ArraySubscriptExpr>(op) &&
2523 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2524 Diag(OpLoc, diag::err_typecheck_address_of,
2525 std::string("vector"), op->getSourceRange());
2526 return QualType();
2527 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002528 // We have an lvalue with a decl. Make sure the decl is not declared
2529 // with the register storage-class specifier.
2530 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2531 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002532 Diag(OpLoc, diag::err_typecheck_address_of,
2533 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002534 return QualType();
2535 }
2536 } else
2537 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002538 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002539
Chris Lattner4b009652007-07-25 00:24:17 +00002540 // If the operand has type "type", the result has type "pointer to type".
2541 return Context.getPointerType(op->getType());
2542}
2543
2544QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2545 UsualUnaryConversions(op);
2546 QualType qType = op->getType();
2547
Chris Lattner7931f4a2007-07-31 16:53:04 +00002548 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002549 // Note that per both C89 and C99, this is always legal, even
2550 // if ptype is an incomplete type or void.
2551 // It would be possible to warn about dereferencing a
2552 // void pointer, but it's completely well-defined,
2553 // and such a warning is unlikely to catch any mistakes.
2554 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002555 }
2556 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2557 qType.getAsString(), op->getSourceRange());
2558 return QualType();
2559}
2560
2561static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2562 tok::TokenKind Kind) {
2563 BinaryOperator::Opcode Opc;
2564 switch (Kind) {
2565 default: assert(0 && "Unknown binop!");
2566 case tok::star: Opc = BinaryOperator::Mul; break;
2567 case tok::slash: Opc = BinaryOperator::Div; break;
2568 case tok::percent: Opc = BinaryOperator::Rem; break;
2569 case tok::plus: Opc = BinaryOperator::Add; break;
2570 case tok::minus: Opc = BinaryOperator::Sub; break;
2571 case tok::lessless: Opc = BinaryOperator::Shl; break;
2572 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2573 case tok::lessequal: Opc = BinaryOperator::LE; break;
2574 case tok::less: Opc = BinaryOperator::LT; break;
2575 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2576 case tok::greater: Opc = BinaryOperator::GT; break;
2577 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2578 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2579 case tok::amp: Opc = BinaryOperator::And; break;
2580 case tok::caret: Opc = BinaryOperator::Xor; break;
2581 case tok::pipe: Opc = BinaryOperator::Or; break;
2582 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2583 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2584 case tok::equal: Opc = BinaryOperator::Assign; break;
2585 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2586 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2587 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2588 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2589 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2590 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2591 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2592 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2593 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2594 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2595 case tok::comma: Opc = BinaryOperator::Comma; break;
2596 }
2597 return Opc;
2598}
2599
2600static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2601 tok::TokenKind Kind) {
2602 UnaryOperator::Opcode Opc;
2603 switch (Kind) {
2604 default: assert(0 && "Unknown unary op!");
2605 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2606 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2607 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2608 case tok::star: Opc = UnaryOperator::Deref; break;
2609 case tok::plus: Opc = UnaryOperator::Plus; break;
2610 case tok::minus: Opc = UnaryOperator::Minus; break;
2611 case tok::tilde: Opc = UnaryOperator::Not; break;
2612 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2613 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2614 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2615 case tok::kw___real: Opc = UnaryOperator::Real; break;
2616 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2617 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2618 }
2619 return Opc;
2620}
2621
2622// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002623Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002624 ExprTy *LHS, ExprTy *RHS) {
2625 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2626 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2627
Steve Naroff87d58b42007-09-16 03:34:24 +00002628 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2629 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002630
2631 QualType ResultTy; // Result type of the binary operator.
2632 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2633
2634 switch (Opc) {
2635 default:
2636 assert(0 && "Unknown binary expr!");
2637 case BinaryOperator::Assign:
2638 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2639 break;
2640 case BinaryOperator::Mul:
2641 case BinaryOperator::Div:
2642 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2643 break;
2644 case BinaryOperator::Rem:
2645 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2646 break;
2647 case BinaryOperator::Add:
2648 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2649 break;
2650 case BinaryOperator::Sub:
2651 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2652 break;
2653 case BinaryOperator::Shl:
2654 case BinaryOperator::Shr:
2655 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2656 break;
2657 case BinaryOperator::LE:
2658 case BinaryOperator::LT:
2659 case BinaryOperator::GE:
2660 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002661 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002662 break;
2663 case BinaryOperator::EQ:
2664 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002665 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00002666 break;
2667 case BinaryOperator::And:
2668 case BinaryOperator::Xor:
2669 case BinaryOperator::Or:
2670 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2671 break;
2672 case BinaryOperator::LAnd:
2673 case BinaryOperator::LOr:
2674 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2675 break;
2676 case BinaryOperator::MulAssign:
2677 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002678 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002679 if (!CompTy.isNull())
2680 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2681 break;
2682 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002683 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002684 if (!CompTy.isNull())
2685 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2686 break;
2687 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002688 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002689 if (!CompTy.isNull())
2690 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2691 break;
2692 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002693 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002694 if (!CompTy.isNull())
2695 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2696 break;
2697 case BinaryOperator::ShlAssign:
2698 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002699 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002700 if (!CompTy.isNull())
2701 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2702 break;
2703 case BinaryOperator::AndAssign:
2704 case BinaryOperator::XorAssign:
2705 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002706 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002707 if (!CompTy.isNull())
2708 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2709 break;
2710 case BinaryOperator::Comma:
2711 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2712 break;
2713 }
2714 if (ResultTy.isNull())
2715 return true;
2716 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00002717 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002718 else
Chris Lattnerf420df12007-08-28 18:36:55 +00002719 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002720}
2721
2722// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002723Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002724 ExprTy *input) {
2725 Expr *Input = (Expr*)input;
2726 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2727 QualType resultType;
2728 switch (Opc) {
2729 default:
2730 assert(0 && "Unimplemented unary expr!");
2731 case UnaryOperator::PreInc:
2732 case UnaryOperator::PreDec:
2733 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2734 break;
2735 case UnaryOperator::AddrOf:
2736 resultType = CheckAddressOfOperand(Input, OpLoc);
2737 break;
2738 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002739 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002740 resultType = CheckIndirectionOperand(Input, OpLoc);
2741 break;
2742 case UnaryOperator::Plus:
2743 case UnaryOperator::Minus:
2744 UsualUnaryConversions(Input);
2745 resultType = Input->getType();
2746 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2747 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2748 resultType.getAsString());
2749 break;
2750 case UnaryOperator::Not: // bitwise complement
2751 UsualUnaryConversions(Input);
2752 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002753 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2754 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2755 // C99 does not support '~' for complex conjugation.
2756 Diag(OpLoc, diag::ext_integer_complement_complex,
2757 resultType.getAsString(), Input->getSourceRange());
2758 else if (!resultType->isIntegerType())
2759 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2760 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002761 break;
2762 case UnaryOperator::LNot: // logical negation
2763 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2764 DefaultFunctionArrayConversion(Input);
2765 resultType = Input->getType();
2766 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2767 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2768 resultType.getAsString());
2769 // LNot always has type int. C99 6.5.3.3p5.
2770 resultType = Context.IntTy;
2771 break;
2772 case UnaryOperator::SizeOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002773 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2774 Input->getSourceRange(), true);
Chris Lattner4b009652007-07-25 00:24:17 +00002775 break;
2776 case UnaryOperator::AlignOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002777 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2778 Input->getSourceRange(), false);
Chris Lattner4b009652007-07-25 00:24:17 +00002779 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002780 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002781 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002782 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002783 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002784 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002785 resultType = Input->getType();
2786 break;
2787 }
2788 if (resultType.isNull())
2789 return true;
2790 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2791}
2792
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002793/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2794Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002795 SourceLocation LabLoc,
2796 IdentifierInfo *LabelII) {
2797 // Look up the record for this label identifier.
2798 LabelStmt *&LabelDecl = LabelMap[LabelII];
2799
Daniel Dunbar879788d2008-08-04 16:51:22 +00002800 // If we haven't seen this label yet, create a forward reference. It
2801 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00002802 if (LabelDecl == 0)
2803 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2804
2805 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002806 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2807 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002808}
2809
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002810Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002811 SourceLocation RPLoc) { // "({..})"
2812 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2813 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2814 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2815
2816 // FIXME: there are a variety of strange constraints to enforce here, for
2817 // example, it is not possible to goto into a stmt expression apparently.
2818 // More semantic analysis is needed.
2819
2820 // FIXME: the last statement in the compount stmt has its value used. We
2821 // should not warn about it being unused.
2822
2823 // If there are sub stmts in the compound stmt, take the type of the last one
2824 // as the type of the stmtexpr.
2825 QualType Ty = Context.VoidTy;
2826
Chris Lattner200964f2008-07-26 19:51:01 +00002827 if (!Compound->body_empty()) {
2828 Stmt *LastStmt = Compound->body_back();
2829 // If LastStmt is a label, skip down through into the body.
2830 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2831 LastStmt = Label->getSubStmt();
2832
2833 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00002834 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00002835 }
Chris Lattner4b009652007-07-25 00:24:17 +00002836
2837 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2838}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002839
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002840Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002841 SourceLocation TypeLoc,
2842 TypeTy *argty,
2843 OffsetOfComponent *CompPtr,
2844 unsigned NumComponents,
2845 SourceLocation RPLoc) {
2846 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2847 assert(!ArgTy.isNull() && "Missing type argument!");
2848
2849 // We must have at least one component that refers to the type, and the first
2850 // one is known to be a field designator. Verify that the ArgTy represents
2851 // a struct/union/class.
2852 if (!ArgTy->isRecordType())
2853 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2854
2855 // Otherwise, create a compound literal expression as the base, and
2856 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002857 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002858
Chris Lattnerb37522e2007-08-31 21:49:13 +00002859 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2860 // GCC extension, diagnose them.
2861 if (NumComponents != 1)
2862 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2863 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2864
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002865 for (unsigned i = 0; i != NumComponents; ++i) {
2866 const OffsetOfComponent &OC = CompPtr[i];
2867 if (OC.isBrackets) {
2868 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00002869 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002870 if (!AT) {
2871 delete Res;
2872 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2873 Res->getType().getAsString());
2874 }
2875
Chris Lattner2af6a802007-08-30 17:59:59 +00002876 // FIXME: C++: Verify that operator[] isn't overloaded.
2877
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002878 // C99 6.5.2.1p1
2879 Expr *Idx = static_cast<Expr*>(OC.U.E);
2880 if (!Idx->getType()->isIntegerType())
2881 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2882 Idx->getSourceRange());
2883
2884 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2885 continue;
2886 }
2887
2888 const RecordType *RC = Res->getType()->getAsRecordType();
2889 if (!RC) {
2890 delete Res;
2891 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2892 Res->getType().getAsString());
2893 }
2894
2895 // Get the decl corresponding to this.
2896 RecordDecl *RD = RC->getDecl();
2897 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2898 if (!MemberDecl)
2899 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2900 OC.U.IdentInfo->getName(),
2901 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002902
2903 // FIXME: C++: Verify that MemberDecl isn't a static field.
2904 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002905 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2906 // matter here.
2907 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002908 }
2909
2910 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2911 BuiltinLoc);
2912}
2913
2914
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002915Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002916 TypeTy *arg1, TypeTy *arg2,
2917 SourceLocation RPLoc) {
2918 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2919 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2920
2921 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2922
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002923 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002924}
2925
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002926Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002927 ExprTy *expr1, ExprTy *expr2,
2928 SourceLocation RPLoc) {
2929 Expr *CondExpr = static_cast<Expr*>(cond);
2930 Expr *LHSExpr = static_cast<Expr*>(expr1);
2931 Expr *RHSExpr = static_cast<Expr*>(expr2);
2932
2933 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2934
2935 // The conditional expression is required to be a constant expression.
2936 llvm::APSInt condEval(32);
2937 SourceLocation ExpLoc;
2938 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2939 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2940 CondExpr->getSourceRange());
2941
2942 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2943 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2944 RHSExpr->getType();
2945 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2946}
2947
Steve Naroff52a81c02008-09-03 18:15:37 +00002948//===----------------------------------------------------------------------===//
2949// Clang Extensions.
2950//===----------------------------------------------------------------------===//
2951
2952/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00002953void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00002954 // Analyze block parameters.
2955 BlockSemaInfo *BSI = new BlockSemaInfo();
2956
2957 // Add BSI to CurBlock.
2958 BSI->PrevBlockInfo = CurBlock;
2959 CurBlock = BSI;
2960
2961 BSI->ReturnType = 0;
2962 BSI->TheScope = BlockScope;
2963
Steve Naroff52059382008-10-10 01:28:17 +00002964 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
2965 PushDeclContext(BSI->TheDecl);
2966}
2967
2968void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00002969 // Analyze arguments to block.
2970 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2971 "Not a function declarator!");
2972 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2973
Steve Naroff52059382008-10-10 01:28:17 +00002974 CurBlock->hasPrototype = FTI.hasPrototype;
2975 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00002976
2977 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2978 // no arguments, not a function that takes a single void argument.
2979 if (FTI.hasPrototype &&
2980 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2981 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2982 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2983 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00002984 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00002985 } else if (FTI.hasPrototype) {
2986 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00002987 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2988 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00002989 }
Steve Naroff52059382008-10-10 01:28:17 +00002990 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
2991
2992 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
2993 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
2994 // If this has an identifier, add it to the scope stack.
2995 if ((*AI)->getIdentifier())
2996 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00002997}
2998
2999/// ActOnBlockError - If there is an error parsing a block, this callback
3000/// is invoked to pop the information about the block from the action impl.
3001void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3002 // Ensure that CurBlock is deleted.
3003 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3004
3005 // Pop off CurBlock, handle nested blocks.
3006 CurBlock = CurBlock->PrevBlockInfo;
3007
3008 // FIXME: Delete the ParmVarDecl objects as well???
3009
3010}
3011
3012/// ActOnBlockStmtExpr - This is called when the body of a block statement
3013/// literal was successfully completed. ^(int x){...}
3014Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3015 Scope *CurScope) {
3016 // Ensure that CurBlock is deleted.
3017 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3018 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3019
Steve Naroff52059382008-10-10 01:28:17 +00003020 PopDeclContext();
3021
Steve Naroff52a81c02008-09-03 18:15:37 +00003022 // Pop off CurBlock, handle nested blocks.
3023 CurBlock = CurBlock->PrevBlockInfo;
3024
3025 QualType RetTy = Context.VoidTy;
3026 if (BSI->ReturnType)
3027 RetTy = QualType(BSI->ReturnType, 0);
3028
3029 llvm::SmallVector<QualType, 8> ArgTypes;
3030 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3031 ArgTypes.push_back(BSI->Params[i]->getType());
3032
3033 QualType BlockTy;
3034 if (!BSI->hasPrototype)
3035 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3036 else
3037 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003038 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003039
3040 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003041
Steve Naroff95029d92008-10-08 18:44:00 +00003042 BSI->TheDecl->setBody(Body.take());
3043 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003044}
3045
Nate Begemanbd881ef2008-01-30 20:50:20 +00003046/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003047/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003048/// The number of arguments has already been validated to match the number of
3049/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003050static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3051 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003052 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003053 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003054 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3055 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003056
3057 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003058 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003059 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003060 return true;
3061}
3062
3063Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3064 SourceLocation *CommaLocs,
3065 SourceLocation BuiltinLoc,
3066 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003067 // __builtin_overload requires at least 2 arguments
3068 if (NumArgs < 2)
3069 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3070 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003071
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003072 // The first argument is required to be a constant expression. It tells us
3073 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003074 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003075 Expr *NParamsExpr = Args[0];
3076 llvm::APSInt constEval(32);
3077 SourceLocation ExpLoc;
3078 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
3079 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3080 NParamsExpr->getSourceRange());
3081
3082 // Verify that the number of parameters is > 0
3083 unsigned NumParams = constEval.getZExtValue();
3084 if (NumParams == 0)
3085 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3086 NParamsExpr->getSourceRange());
3087 // Verify that we have at least 1 + NumParams arguments to the builtin.
3088 if ((NumParams + 1) > NumArgs)
3089 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3090 SourceRange(BuiltinLoc, RParenLoc));
3091
3092 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003093 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003094 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003095 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3096 // UsualUnaryConversions will convert the function DeclRefExpr into a
3097 // pointer to function.
3098 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003099 const FunctionTypeProto *FnType = 0;
3100 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3101 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003102
3103 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3104 // parameters, and the number of parameters must match the value passed to
3105 // the builtin.
3106 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00003107 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
3108 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003109
3110 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003111 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003112 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003113 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003114 if (OE)
3115 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
3116 OE->getFn()->getSourceRange());
3117 // Remember our match, and continue processing the remaining arguments
3118 // to catch any errors.
3119 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
3120 BuiltinLoc, RParenLoc);
3121 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003122 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003123 // Return the newly created OverloadExpr node, if we succeded in matching
3124 // exactly one of the candidate functions.
3125 if (OE)
3126 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003127
3128 // If we didn't find a matching function Expr in the __builtin_overload list
3129 // the return an error.
3130 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003131 for (unsigned i = 0; i != NumParams; ++i) {
3132 if (i != 0) typeNames += ", ";
3133 typeNames += Args[i+1]->getType().getAsString();
3134 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003135
3136 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3137 SourceRange(BuiltinLoc, RParenLoc));
3138}
3139
Anders Carlsson36760332007-10-15 20:28:48 +00003140Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3141 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003142 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003143 Expr *E = static_cast<Expr*>(expr);
3144 QualType T = QualType::getFromOpaquePtr(type);
3145
3146 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003147
3148 // Get the va_list type
3149 QualType VaListType = Context.getBuiltinVaListType();
3150 // Deal with implicit array decay; for example, on x86-64,
3151 // va_list is an array, but it's supposed to decay to
3152 // a pointer for va_arg.
3153 if (VaListType->isArrayType())
3154 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003155 // Make sure the input expression also decays appropriately.
3156 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003157
3158 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003159 return Diag(E->getLocStart(),
3160 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3161 E->getType().getAsString(),
3162 E->getSourceRange());
3163
3164 // FIXME: Warn if a non-POD type is passed in.
3165
3166 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
3167}
3168
Chris Lattner005ed752008-01-04 18:04:52 +00003169bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3170 SourceLocation Loc,
3171 QualType DstType, QualType SrcType,
3172 Expr *SrcExpr, const char *Flavor) {
3173 // Decode the result (notice that AST's are still created for extensions).
3174 bool isInvalid = false;
3175 unsigned DiagKind;
3176 switch (ConvTy) {
3177 default: assert(0 && "Unknown conversion type");
3178 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003179 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003180 DiagKind = diag::ext_typecheck_convert_pointer_int;
3181 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003182 case IntToPointer:
3183 DiagKind = diag::ext_typecheck_convert_int_pointer;
3184 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003185 case IncompatiblePointer:
3186 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3187 break;
3188 case FunctionVoidPointer:
3189 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3190 break;
3191 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003192 // If the qualifiers lost were because we were applying the
3193 // (deprecated) C++ conversion from a string literal to a char*
3194 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3195 // Ideally, this check would be performed in
3196 // CheckPointerTypesForAssignment. However, that would require a
3197 // bit of refactoring (so that the second argument is an
3198 // expression, rather than a type), which should be done as part
3199 // of a larger effort to fix CheckPointerTypesForAssignment for
3200 // C++ semantics.
3201 if (getLangOptions().CPlusPlus &&
3202 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3203 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003204 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3205 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003206 case IntToBlockPointer:
3207 DiagKind = diag::err_int_to_block_pointer;
3208 break;
3209 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003210 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003211 break;
3212 case BlockVoidPointer:
3213 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3214 break;
Steve Naroff19608432008-10-14 22:18:38 +00003215 case IncompatibleObjCQualifiedId:
3216 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3217 // it can give a more specific diagnostic.
3218 DiagKind = diag::warn_incompatible_qualified_id;
3219 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003220 case Incompatible:
3221 DiagKind = diag::err_typecheck_convert_incompatible;
3222 isInvalid = true;
3223 break;
3224 }
3225
3226 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3227 SrcExpr->getSourceRange());
3228 return isInvalid;
3229}