blob: 7a3c6bdeb15763094bf039da6f19eff0f5a10951 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner04421082008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27
Chris Lattnere7a2e912008-07-25 21:10:04 +000028//===----------------------------------------------------------------------===//
29// Standard Promotions and Conversions
30//===----------------------------------------------------------------------===//
31
Chris Lattnere7a2e912008-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 Lattner67d33d82008-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).
Argyrios Kyrtzidisc39a3d72008-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 Lattner67d33d82008-07-25 21:33:13 +000057 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
58 }
Chris Lattnere7a2e912008-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 Lattner05faf172008-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 Lattnere7a2e912008-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 Lattnerb77792e2008-07-26 22:17:49 +0000111 QualType lhs =
112 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
113 QualType rhs =
114 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattnere7a2e912008-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 Narofff69936d2007-09-16 03:34:24 +0000266/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofff69936d2007-09-16 03:34:24 +0000273Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnera7ad98f2008-02-11 00:02:17 +0000283
284 // Verify that pascal strings aren't too large.
Anders Carlssonee98ac52007-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()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000289
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000290 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000291 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000292 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-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 Lattnera7ad98f2008-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
Reid Spencer5f016e22007-07-11 17:01:13 +0000305 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
306 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000307 Literal.AnyWide, StrTy,
Anders Carlssonee98ac52007-10-15 02:50:23 +0000308 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 StringToks[NumStringToks-1].getLocation());
310}
311
Chris Lattner639e2d32008-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 Naroff08d92e42007-09-15 18:49:24 +0000342/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000343/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000344/// identifier is used in a function call context.
Steve Naroff08d92e42007-09-15 18:49:24 +0000345Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 IdentifierInfo &II,
347 bool HasTrailingLParen) {
Chris Lattner8a934232008-03-31 00:36:02 +0000348 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroffb327ce02008-04-02 14:35:35 +0000349 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattner8a934232008-03-31 00:36:02 +0000350
351 // If this reference is in an Objective-C method, then ivar lookup happens as
352 // well.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000353 if (getCurMethodDecl()) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000354 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattner8a934232008-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 Naroffe8043c32008-04-01 23:04:06 +0000360 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000361 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattner123a11f2008-07-21 04:44:44 +0000362 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattner8a934232008-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 Naroff76de9d72008-08-10 19:10:41 +0000371 // Needed to implement property "super.method" notation.
Daniel Dunbar662e8b52008-08-14 22:04:54 +0000372 if (SD == 0 && &II == SuperID) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000373 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000374 getCurMethodDecl()->getClassInterface()));
Steve Naroff76de9d72008-08-10 19:10:41 +0000375 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000376 }
Chris Lattner8a934232008-03-31 00:36:02 +0000377 }
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner8a934232008-03-31 00:36:02 +0000382 !getLangOptions().CPlusPlus) // Not in C++.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner8a934232008-03-31 00:36:02 +0000390
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000391 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
392 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
393 if (MD->isStatic())
394 // "invalid use of member 'x' in static member function"
395 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
396 FD->getName());
397 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
398 // "invalid use of nonstatic data member 'x'"
399 return Diag(Loc, diag::err_invalid_non_static_member_use,
400 FD->getName());
401
402 if (FD->isInvalidDecl())
403 return true;
404
405 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
406 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
407 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
408 true, FD, Loc, FD->getType());
409 }
410
411 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
412 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000413 if (isa<TypedefDecl>(D))
414 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000415 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian5ef404f2007-12-05 18:16:33 +0000416 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000417 if (isa<NamespaceDecl>(D))
418 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000419
Steve Naroffdd972f22008-09-05 22:11:13 +0000420 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000421 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
422 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
423
Steve Naroffdd972f22008-09-05 22:11:13 +0000424 ValueDecl *VD = cast<ValueDecl>(D);
425
426 // check if referencing an identifier with __attribute__((deprecated)).
427 if (VD->getAttr<DeprecatedAttr>())
428 Diag(Loc, diag::warn_deprecated, VD->getName());
429
430 // Only create DeclRefExpr's for valid Decl's.
431 if (VD->isInvalidDecl())
432 return true;
Chris Lattner639e2d32008-10-20 05:16:36 +0000433
434 // If the identifier reference is inside a block, and it refers to a value
435 // that is outside the block, create a BlockDeclRefExpr instead of a
436 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
437 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000438 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000439 // We do not do this for things like enum constants, global variables, etc,
440 // as they do not get snapshotted.
441 //
442 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff090276f2008-10-10 01:28:17 +0000443 // The BlocksAttr indicates the variable is bound by-reference.
444 if (VD->getAttr<BlocksAttr>())
445 return new BlockDeclRefExpr(VD, VD->getType(), Loc, true);
446
447 // Variable will be bound by-copy, make it const within the closure.
448 VD->getType().addConst();
449 return new BlockDeclRefExpr(VD, VD->getType(), Loc, false);
450 }
451 // If this reference is not in a block or if the referenced variable is
452 // within the block, create a normal DeclRefExpr.
453 return new DeclRefExpr(VD, VD->getType(), Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000454}
455
Chris Lattnerd9f69102008-08-10 01:53:14 +0000456Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000457 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000458 PredefinedExpr::IdentType IT;
Anders Carlsson22742662007-07-21 05:21:51 +0000459
Reid Spencer5f016e22007-07-11 17:01:13 +0000460 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000461 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000462 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
463 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
464 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000465 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000466
467 // Verify that this is in a function context.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000468 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattner1423ea42008-01-12 18:39:25 +0000469 return Diag(Loc, diag::err_predef_outside_function);
Anders Carlsson22742662007-07-21 05:21:51 +0000470
Chris Lattnerfa28b302008-01-12 08:14:25 +0000471 // Pre-defined identifiers are of type char[x], where x is the length of the
472 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000473 unsigned Length;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000474 if (getCurFunctionDecl())
475 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattner8f978d52008-01-12 19:32:28 +0000476 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000477 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattner1423ea42008-01-12 18:39:25 +0000478
Chris Lattner8f978d52008-01-12 19:32:28 +0000479 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000480 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000481 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerd9f69102008-08-10 01:53:14 +0000482 return new PredefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000483}
484
Steve Narofff69936d2007-09-16 03:34:24 +0000485Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000486 llvm::SmallString<16> CharBuffer;
487 CharBuffer.resize(Tok.getLength());
488 const char *ThisTokBegin = &CharBuffer[0];
489 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
490
491 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
492 Tok.getLocation(), PP);
493 if (Literal.hadError())
494 return ExprResult(true);
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000495
496 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
497
Chris Lattnerc250aae2008-06-07 22:35:38 +0000498 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
499 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000500}
501
Steve Narofff69936d2007-09-16 03:34:24 +0000502Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000503 // fast path for a single digit (which is quite common). A single digit
504 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
505 if (Tok.getLength() == 1) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000506 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000507
Chris Lattner98be4942008-03-05 18:54:05 +0000508 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000509 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 Context.IntTy,
511 Tok.getLocation()));
512 }
513 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000514 // Add padding so that NumericLiteralParser can overread by one character.
515 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000516 const char *ThisTokBegin = &IntegerBuffer[0];
517
518 // Get the spelling of the token, which eliminates trigraphs, etc.
519 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner28997ec2008-09-30 20:51:14 +0000520
Reid Spencer5f016e22007-07-11 17:01:13 +0000521 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
522 Tok.getLocation(), PP);
523 if (Literal.hadError)
524 return ExprResult(true);
525
Chris Lattner5d661452007-08-26 03:42:43 +0000526 Expr *Res;
527
528 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000529 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000530 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000531 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000532 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000533 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000534 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000535 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000536
537 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
538
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000539 // isExact will be set by GetFloatValue().
540 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000541 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000542 Ty, Tok.getLocation());
543
Chris Lattner5d661452007-08-26 03:42:43 +0000544 } else if (!Literal.isIntegerLiteral()) {
545 return ExprResult(true);
546 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000547 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000548
Neil Boothb9449512007-08-29 22:00:19 +0000549 // long long is a C99 feature.
550 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000551 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000552 Diag(Tok.getLocation(), diag::ext_longlong);
553
Reid Spencer5f016e22007-07-11 17:01:13 +0000554 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000555 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000556
557 if (Literal.GetIntegerValue(ResultVal)) {
558 // If this value didn't fit into uintmax_t, warn and force to ull.
559 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000560 Ty = Context.UnsignedLongLongTy;
561 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000562 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000563 } else {
564 // If this value fits into a ULL, try to figure out what else it fits into
565 // according to the rules of C99 6.4.4.1p5.
566
567 // Octal, Hexadecimal, and integers with a U suffix are allowed to
568 // be an unsigned int.
569 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
570
571 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000572 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000573 if (!Literal.isLong && !Literal.isLongLong) {
574 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000575 unsigned IntSize = Context.Target.getIntWidth();
576
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 // Does it fit in a unsigned int?
578 if (ResultVal.isIntN(IntSize)) {
579 // Does it fit in a signed int?
580 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000581 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000583 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000584 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000585 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000586 }
587
588 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000589 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000590 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000591
592 // Does it fit in a unsigned long?
593 if (ResultVal.isIntN(LongSize)) {
594 // Does it fit in a signed long?
595 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000596 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000597 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000598 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000599 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000600 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000601 }
602
603 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000604 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000605 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000606
607 // Does it fit in a unsigned long long?
608 if (ResultVal.isIntN(LongLongSize)) {
609 // Does it fit in a signed long long?
610 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000611 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000612 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000613 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000614 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000615 }
616 }
617
618 // If we still couldn't decide a type, we probably have something that
619 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000620 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000621 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000622 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000623 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000624 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000625
626 if (ResultVal.getBitWidth() != Width)
627 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000628 }
629
Chris Lattnerf0467b32008-04-02 04:24:33 +0000630 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000631 }
Chris Lattner5d661452007-08-26 03:42:43 +0000632
633 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
634 if (Literal.isImaginary)
635 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
636
637 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000638}
639
Steve Narofff69936d2007-09-16 03:34:24 +0000640Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000641 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000642 Expr *E = (Expr *)Val;
643 assert((E != 0) && "ActOnParenExpr() missing expr");
644 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +0000645}
646
647/// The UsualUnaryConversions() function is *not* called by this routine.
648/// See C99 6.3.2.1p[2-4] for more details.
649QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000650 SourceLocation OpLoc,
651 const SourceRange &ExprRange,
652 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000653 // C99 6.5.3.4p1:
654 if (isa<FunctionType>(exprType) && isSizeof)
655 // alignof(function) is allowed.
Chris Lattnerbb280a42008-07-25 21:45:37 +0000656 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000657 else if (exprType->isVoidType())
Chris Lattnerbb280a42008-07-25 21:45:37 +0000658 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
659 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000660 else if (exprType->isIncompleteType()) {
661 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
662 diag::err_alignof_incomplete_type,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000663 exprType.getAsString(), ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000664 return QualType(); // error
665 }
666 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
667 return Context.getSizeType();
668}
669
670Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000671ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +0000672 SourceLocation LPLoc, TypeTy *Ty,
673 SourceLocation RPLoc) {
674 // If error parsing type, ignore.
675 if (Ty == 0) return true;
676
677 // Verify that this is a valid expression.
678 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
679
Chris Lattnerbb280a42008-07-25 21:45:37 +0000680 QualType resultType =
681 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Reid Spencer5f016e22007-07-11 17:01:13 +0000682
683 if (resultType.isNull())
684 return true;
685 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
686}
687
Chris Lattner5d794252007-08-24 21:41:10 +0000688QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000689 DefaultFunctionArrayConversion(V);
690
Chris Lattnercc26ed72007-08-26 05:39:26 +0000691 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000692 if (const ComplexType *CT = V->getType()->getAsComplexType())
693 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000694
695 // Otherwise they pass through real integer and floating point types here.
696 if (V->getType()->isArithmeticType())
697 return V->getType();
698
699 // Reject anything else.
700 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
701 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000702}
703
704
Reid Spencer5f016e22007-07-11 17:01:13 +0000705
Steve Narofff69936d2007-09-16 03:34:24 +0000706Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 tok::TokenKind Kind,
708 ExprTy *Input) {
709 UnaryOperator::Opcode Opc;
710 switch (Kind) {
711 default: assert(0 && "Unknown unary op!");
712 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
713 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
714 }
715 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
716 if (result.isNull())
717 return true;
718 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
719}
720
721Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000722ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000723 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000724 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000725
726 // Perform default conversions.
727 DefaultFunctionArrayConversion(LHSExp);
728 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000729
Chris Lattner12d9ff62007-07-16 00:14:47 +0000730 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000731
Reid Spencer5f016e22007-07-11 17:01:13 +0000732 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000733 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 // in the subscript position. As a result, we need to derive the array base
735 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000736 Expr *BaseExpr, *IndexExpr;
737 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000738 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000739 BaseExpr = LHSExp;
740 IndexExpr = RHSExp;
741 // FIXME: need to deal with const...
742 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000743 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000744 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000745 BaseExpr = RHSExp;
746 IndexExpr = LHSExp;
747 // FIXME: need to deal with const...
748 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000749 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
750 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000751 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000752
753 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +0000754 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
755 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begeman213541a2008-04-18 23:10:10 +0000756 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff608e0ee2007-08-03 22:40:33 +0000757 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000758 // FIXME: need to deal with const...
759 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000760 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000761 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
762 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 }
764 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000765 if (!IndexExpr->getType()->isIntegerType())
766 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
767 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000768
Chris Lattner12d9ff62007-07-16 00:14:47 +0000769 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
770 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +0000771 // void (*)(int)) and pointers to incomplete types. Functions are not
772 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000773 if (!ResultType->isObjectType())
774 return Diag(BaseExpr->getLocStart(),
775 diag::err_typecheck_subscript_not_object,
776 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
777
778 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000779}
780
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000781QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +0000782CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000783 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +0000784 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +0000785
786 // This flag determines whether or not the component is to be treated as a
787 // special name, or a regular GLSL-style component access.
788 bool SpecialComponent = false;
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000789
790 // The vector accessor can't exceed the number of elements.
791 const char *compStr = CompName.getName();
792 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begeman213541a2008-04-18 23:10:10 +0000793 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000794 baseType.getAsString(), SourceRange(CompLoc));
795 return QualType();
796 }
Nate Begeman8a997642008-05-09 06:41:27 +0000797
798 // Check that we've found one of the special components, or that the component
799 // names must come from the same set.
800 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
801 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
802 SpecialComponent = true;
803 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +0000804 do
805 compStr++;
806 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
807 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
808 do
809 compStr++;
810 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
811 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
812 do
813 compStr++;
814 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
815 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000816
Nate Begeman8a997642008-05-09 06:41:27 +0000817 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000818 // We didn't get to the end of the string. This means the component names
819 // didn't come from the same set *or* we encountered an illegal name.
Nate Begeman213541a2008-04-18 23:10:10 +0000820 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000821 std::string(compStr,compStr+1), SourceRange(CompLoc));
822 return QualType();
823 }
824 // Each component accessor can't exceed the vector type.
825 compStr = CompName.getName();
826 while (*compStr) {
827 if (vecType->isAccessorWithinNumElements(*compStr))
828 compStr++;
829 else
830 break;
831 }
Nate Begeman8a997642008-05-09 06:41:27 +0000832 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000833 // We didn't get to the end of the string. This means a component accessor
834 // exceeds the number of elements in the vector.
Nate Begeman213541a2008-04-18 23:10:10 +0000835 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000836 baseType.getAsString(), SourceRange(CompLoc));
837 return QualType();
838 }
Nate Begeman8a997642008-05-09 06:41:27 +0000839
840 // If we have a special component name, verify that the current vector length
841 // is an even number, since all special component names return exactly half
842 // the elements.
843 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Daniel Dunbarabee2d72008-09-30 17:22:47 +0000844 Diag(OpLoc, diag::err_ext_vector_component_requires_even,
845 baseType.getAsString(), SourceRange(CompLoc));
Nate Begeman8a997642008-05-09 06:41:27 +0000846 return QualType();
847 }
848
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000849 // The component accessor looks fine - now we need to compute the actual type.
850 // The vector type is implied by the component accessor. For example,
851 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +0000852 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
853 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
854 : strlen(CompName.getName());
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000855 if (CompSize == 1)
856 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000857
Nate Begeman213541a2008-04-18 23:10:10 +0000858 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +0000859 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +0000860 // diagostics look bad. We want extended vector types to appear built-in.
861 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
862 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
863 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +0000864 }
865 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000866}
867
Daniel Dunbar2307d312008-09-03 01:05:41 +0000868/// constructSetterName - Return the setter name for the given
869/// identifier, i.e. "set" + Name where the initial character of Name
870/// has been capitalized.
871// FIXME: Merge with same routine in Parser. But where should this
872// live?
873static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
874 const IdentifierInfo *Name) {
875 unsigned N = Name->getLength();
876 char *SelectorName = new char[3 + N];
877 memcpy(SelectorName, "set", 3);
878 memcpy(&SelectorName[3], Name->getName(), N);
879 SelectorName[3] = toupper(SelectorName[3]);
880
881 IdentifierInfo *Setter =
882 &Idents.get(SelectorName, &SelectorName[3 + N]);
883 delete[] SelectorName;
884 return Setter;
885}
886
Reid Spencer5f016e22007-07-11 17:01:13 +0000887Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000888ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000889 tok::TokenKind OpKind, SourceLocation MemberLoc,
890 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000891 Expr *BaseExpr = static_cast<Expr *>(Base);
892 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +0000893
894 // Perform default conversions.
895 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000896
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000897 QualType BaseType = BaseExpr->getType();
898 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000899
Chris Lattner68a057b2008-07-21 04:36:39 +0000900 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
901 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +0000902 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000903 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000904 BaseType = PT->getPointeeType();
905 else
Chris Lattner2a01b722008-07-21 05:35:34 +0000906 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
907 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000908 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000909
Chris Lattner68a057b2008-07-21 04:36:39 +0000910 // Handle field access to simple records. This also handles access to fields
911 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +0000912 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000913 RecordDecl *RDecl = RTy->getDecl();
914 if (RTy->isIncompleteType())
915 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
916 BaseExpr->getSourceRange());
917 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000918 FieldDecl *MemberDecl = RDecl->getMember(&Member);
919 if (!MemberDecl)
Chris Lattner2a01b722008-07-21 05:35:34 +0000920 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
921 BaseExpr->getSourceRange());
Eli Friedman51019072008-02-06 22:48:16 +0000922
923 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedman64ec0cc2008-02-07 05:24:51 +0000924 // FIXME: Handle address space modifiers
Eli Friedman51019072008-02-06 22:48:16 +0000925 QualType MemberType = MemberDecl->getType();
926 unsigned combinedQualifiers =
Chris Lattnerf46699c2008-02-20 20:55:12 +0000927 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman51019072008-02-06 22:48:16 +0000928 MemberType = MemberType.getQualifiedType(combinedQualifiers);
929
Chris Lattner68a057b2008-07-21 04:36:39 +0000930 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman51019072008-02-06 22:48:16 +0000931 MemberLoc, MemberType);
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000932 }
933
Chris Lattnera38e6b12008-07-21 04:59:05 +0000934 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
935 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +0000936 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
937 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000938 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000939 OpKind == tok::arrow);
Chris Lattner2a01b722008-07-21 05:35:34 +0000940 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner1f719742008-07-21 04:42:08 +0000941 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner2a01b722008-07-21 05:35:34 +0000942 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000943 }
944
Chris Lattnera38e6b12008-07-21 04:59:05 +0000945 // Handle Objective-C property access, which is "Obj.property" where Obj is a
946 // pointer to a (potentially qualified) interface type.
947 const PointerType *PTy;
948 const ObjCInterfaceType *IFTy;
949 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
950 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
951 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000952
Daniel Dunbar2307d312008-09-03 01:05:41 +0000953 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +0000954 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
955 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
956
Daniel Dunbar2307d312008-09-03 01:05:41 +0000957 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +0000958 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
959 E = IFTy->qual_end(); I != E; ++I)
960 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
961 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +0000962
963 // If that failed, look for an "implicit" property by seeing if the nullary
964 // selector is implemented.
965
966 // FIXME: The logic for looking up nullary and unary selectors should be
967 // shared with the code in ActOnInstanceMessage.
968
969 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
970 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
971
972 // If this reference is in an @implementation, check for 'private' methods.
973 if (!Getter)
974 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
975 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
976 if (ObjCImplementationDecl *ImpDecl =
977 ObjCImplementations[ClassDecl->getIdentifier()])
978 Getter = ImpDecl->getInstanceMethod(Sel);
979
980 if (Getter) {
981 // If we found a getter then this may be a valid dot-reference, we
982 // need to also look for the matching setter.
983 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
984 &Member);
985 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
986 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
987
988 if (!Setter) {
989 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
990 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
991 if (ObjCImplementationDecl *ImpDecl =
992 ObjCImplementations[ClassDecl->getIdentifier()])
993 Setter = ImpDecl->getInstanceMethod(SetterSel);
994 }
995
996 // FIXME: There are some issues here. First, we are not
997 // diagnosing accesses to read-only properties because we do not
998 // know if this is a getter or setter yet. Second, we are
999 // checking that the type of the setter matches the type we
1000 // expect.
1001 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1002 MemberLoc, BaseExpr);
1003 }
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001004 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001005 // Handle properties on qualified "id" protocols.
1006 const ObjCQualifiedIdType *QIdTy;
1007 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1008 // Check protocols on qualified interfaces.
1009 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1010 E = QIdTy->qual_end(); I != E; ++I)
1011 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1012 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1013 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001014 // Handle 'field access' to vectors, such as 'V.xx'.
1015 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1016 // Component access limited to variables (reject vec4.rg.g).
1017 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1018 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner2a01b722008-07-21 05:35:34 +00001019 return Diag(MemberLoc, diag::err_ext_vector_component_access,
1020 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001021 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1022 if (ret.isNull())
1023 return true;
1024 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1025 }
1026
Chris Lattner2a01b722008-07-21 05:35:34 +00001027 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1028 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001029}
1030
Steve Narofff69936d2007-09-16 03:34:24 +00001031/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001032/// This provides the location of the left/right parens and a list of comma
1033/// locations.
1034Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001035ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +00001036 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +00001037 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +00001038 Expr *Fn = static_cast<Expr *>(fn);
1039 Expr **Args = reinterpret_cast<Expr**>(args);
1040 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001041 FunctionDecl *FDecl = NULL;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001042 OverloadedFunctionDecl *Ovl = NULL;
1043
1044 // If we're directly calling a function or a set of overloaded
1045 // functions, get the appropriate declaration.
1046 {
1047 DeclRefExpr *DRExpr = NULL;
1048 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1049 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1050 else
1051 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1052
1053 if (DRExpr) {
1054 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1055 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1056 }
1057 }
1058
1059 // If we have a set of overloaded functions, perform overload
1060 // resolution to pick the function.
1061 if (Ovl) {
1062 OverloadCandidateSet CandidateSet;
1063 OverloadCandidateSet::iterator Best;
1064 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
1065 switch (BestViableFunction(CandidateSet, Best)) {
1066 case OR_Success:
1067 {
1068 // Success! Let the remainder of this function build a call to
1069 // the function selected by overload resolution.
1070 FDecl = Best->Function;
1071 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1072 Fn->getSourceRange().getBegin());
1073 delete Fn;
1074 Fn = NewFn;
1075 }
1076 break;
1077
1078 case OR_No_Viable_Function:
1079 if (CandidateSet.empty())
1080 Diag(Fn->getSourceRange().getBegin(),
1081 diag::err_ovl_no_viable_function_in_call, Ovl->getName(),
1082 Fn->getSourceRange());
1083 else {
1084 Diag(Fn->getSourceRange().getBegin(),
1085 diag::err_ovl_no_viable_function_in_call_with_cands,
1086 Ovl->getName(), Fn->getSourceRange());
1087 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1088 }
1089 return true;
1090
1091 case OR_Ambiguous:
1092 Diag(Fn->getSourceRange().getBegin(),
1093 diag::err_ovl_ambiguous_call, Ovl->getName(),
1094 Fn->getSourceRange());
1095 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1096 return true;
1097 }
1098 }
Chris Lattner04421082008-04-08 04:40:51 +00001099
1100 // Promote the function operand.
1101 UsualUnaryConversions(Fn);
1102
Chris Lattner925e60d2007-12-28 05:29:59 +00001103 // Make the call expr early, before semantic checks. This guarantees cleanup
1104 // of arguments and function on error.
Chris Lattner8123a952008-04-10 02:22:51 +00001105 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001106 Context.BoolTy, RParenLoc));
Steve Naroffdd972f22008-09-05 22:11:13 +00001107 const FunctionType *FuncT;
1108 if (!Fn->getType()->isBlockPointerType()) {
1109 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1110 // have type pointer to function".
1111 const PointerType *PT = Fn->getType()->getAsPointerType();
1112 if (PT == 0)
1113 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1114 Fn->getSourceRange());
1115 FuncT = PT->getPointeeType()->getAsFunctionType();
1116 } else { // This is a block call.
1117 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1118 getAsFunctionType();
1119 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001120 if (FuncT == 0)
Chris Lattnerad2018f2008-08-14 04:33:24 +00001121 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1122 Fn->getSourceRange());
Chris Lattner925e60d2007-12-28 05:29:59 +00001123
1124 // We know the result type of the call, set it.
1125 TheCall->setType(FuncT->getResultType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001126
Chris Lattner925e60d2007-12-28 05:29:59 +00001127 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001128 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1129 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +00001130 unsigned NumArgsInProto = Proto->getNumArgs();
1131 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001132
Chris Lattner04421082008-04-08 04:40:51 +00001133 // If too few arguments are available (and we don't have default
1134 // arguments for the remaining parameters), don't make the call.
1135 if (NumArgs < NumArgsInProto) {
Chris Lattner8123a952008-04-10 02:22:51 +00001136 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner04421082008-04-08 04:40:51 +00001137 // Use default arguments for missing arguments
1138 NumArgsToCheck = NumArgsInProto;
Chris Lattner8123a952008-04-10 02:22:51 +00001139 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner04421082008-04-08 04:40:51 +00001140 } else
Steve Naroffdd972f22008-09-05 22:11:13 +00001141 return Diag(RParenLoc,
1142 !Fn->getType()->isBlockPointerType()
1143 ? diag::err_typecheck_call_too_few_args
1144 : diag::err_typecheck_block_too_few_args,
Chris Lattner04421082008-04-08 04:40:51 +00001145 Fn->getSourceRange());
1146 }
1147
Chris Lattner925e60d2007-12-28 05:29:59 +00001148 // If too many are passed and not variadic, error on the extras and drop
1149 // them.
1150 if (NumArgs > NumArgsInProto) {
1151 if (!Proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +00001152 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffdd972f22008-09-05 22:11:13 +00001153 !Fn->getType()->isBlockPointerType()
1154 ? diag::err_typecheck_call_too_many_args
1155 : diag::err_typecheck_block_too_many_args,
1156 Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +00001157 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner925e60d2007-12-28 05:29:59 +00001158 Args[NumArgs-1]->getLocEnd()));
1159 // This deletes the extra arguments.
1160 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +00001161 }
1162 NumArgsToCheck = NumArgsInProto;
1163 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001164
Reid Spencer5f016e22007-07-11 17:01:13 +00001165 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +00001166 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00001167 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner04421082008-04-08 04:40:51 +00001168
1169 Expr *Arg;
1170 if (i < NumArgs)
1171 Arg = Args[i];
1172 else
1173 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner5cf216b2008-01-04 18:04:52 +00001174 QualType ArgType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +00001175
Chris Lattner925e60d2007-12-28 05:29:59 +00001176 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001177 AssignConvertType ConvTy =
1178 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner925e60d2007-12-28 05:29:59 +00001179 TheCall->setArg(i, Arg);
Eli Friedmanf1c7b482008-09-02 05:09:35 +00001180
Chris Lattner5cf216b2008-01-04 18:04:52 +00001181 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1182 ArgType, Arg, "passing"))
1183 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001184 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001185
1186 // If this is a variadic call, handle args passed through "...".
1187 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +00001188 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-12-28 05:29:59 +00001189 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1190 Expr *Arg = Args[i];
1191 DefaultArgumentPromotion(Arg);
1192 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001193 }
Steve Naroffb291ab62007-08-28 23:30:39 +00001194 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001195 } else {
1196 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1197
Steve Naroffb291ab62007-08-28 23:30:39 +00001198 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001199 for (unsigned i = 0; i != NumArgs; i++) {
1200 Expr *Arg = Args[i];
1201 DefaultArgumentPromotion(Arg);
1202 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001203 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001205
Chris Lattner59907c42007-08-10 20:18:51 +00001206 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001207 if (FDecl)
1208 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001209
Chris Lattner925e60d2007-12-28 05:29:59 +00001210 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001211}
1212
1213Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001214ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +00001215 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001216 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001217 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001218 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001219 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +00001220 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +00001221
Eli Friedman6223c222008-05-20 05:22:08 +00001222 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001223 if (literalType->isVariableArrayType())
Eli Friedman6223c222008-05-20 05:22:08 +00001224 return Diag(LParenLoc,
1225 diag::err_variable_object_no_init,
1226 SourceRange(LParenLoc,
1227 literalExpr->getSourceRange().getEnd()));
1228 } else if (literalType->isIncompleteType()) {
1229 return Diag(LParenLoc,
1230 diag::err_typecheck_decl_incomplete_type,
1231 literalType.getAsString(),
1232 SourceRange(LParenLoc,
1233 literalExpr->getSourceRange().getEnd()));
1234 }
1235
Steve Naroffd0091aa2008-01-10 22:15:12 +00001236 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff58d18212008-01-09 20:58:06 +00001237 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +00001238
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001239 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffe9b12192008-01-14 18:19:28 +00001240 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001241 if (CheckForConstantInitializer(literalExpr, literalType))
1242 return true;
1243 }
Steve Naroffe9b12192008-01-14 18:19:28 +00001244 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001245}
1246
1247Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001248ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001249 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +00001250 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001251
Steve Naroff08d92e42007-09-15 18:49:24 +00001252 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001253 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001254
Chris Lattnerf0467b32008-04-02 04:24:33 +00001255 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1256 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1257 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001258}
1259
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001260/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001261bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001262 UsualUnaryConversions(castExpr);
1263
1264 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1265 // type needs to be scalar.
1266 if (castType->isVoidType()) {
1267 // Cast to void allows any expr type.
1268 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1269 // GCC struct/union extension: allow cast to self.
1270 if (Context.getCanonicalType(castType) !=
1271 Context.getCanonicalType(castExpr->getType()) ||
1272 (!castType->isStructureType() && !castType->isUnionType())) {
1273 // Reject any other conversions to non-scalar types.
1274 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1275 castType.getAsString(), castExpr->getSourceRange());
1276 }
1277
1278 // accept this, but emit an ext-warn.
1279 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1280 castType.getAsString(), castExpr->getSourceRange());
1281 } else if (!castExpr->getType()->isScalarType() &&
1282 !castExpr->getType()->isVectorType()) {
1283 return Diag(castExpr->getLocStart(),
1284 diag::err_typecheck_expect_scalar_operand,
1285 castExpr->getType().getAsString(),castExpr->getSourceRange());
1286 } else if (castExpr->getType()->isVectorType()) {
1287 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1288 return true;
1289 } else if (castType->isVectorType()) {
1290 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1291 return true;
1292 }
1293 return false;
1294}
1295
Chris Lattnerfe23e212007-12-20 00:44:32 +00001296bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00001297 assert(VectorTy->isVectorType() && "Not a vector type!");
1298
1299 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00001300 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00001301 return Diag(R.getBegin(),
1302 Ty->isVectorType() ?
1303 diag::err_invalid_conversion_between_vectors :
1304 diag::err_invalid_conversion_between_vector_and_integer,
1305 VectorTy.getAsString().c_str(),
1306 Ty.getAsString().c_str(), R);
1307 } else
1308 return Diag(R.getBegin(),
1309 diag::err_invalid_conversion_between_vector_and_scalar,
1310 VectorTy.getAsString().c_str(),
1311 Ty.getAsString().c_str(), R);
1312
1313 return false;
1314}
1315
Steve Naroff4aa88f82007-07-19 01:06:55 +00001316Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001317ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +00001319 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00001320
1321 Expr *castExpr = static_cast<Expr*>(Op);
1322 QualType castType = QualType::getFromOpaquePtr(Ty);
1323
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001324 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1325 return true;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001326 return new ExplicitCastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001327}
1328
Chris Lattnera21ddb32007-11-26 01:40:58 +00001329/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1330/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00001331inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00001332 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001333 UsualUnaryConversions(cond);
1334 UsualUnaryConversions(lex);
1335 UsualUnaryConversions(rex);
1336 QualType condT = cond->getType();
1337 QualType lexT = lex->getType();
1338 QualType rexT = rex->getType();
1339
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +00001341 if (!condT->isScalarType()) { // C99 6.5.15p2
1342 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1343 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +00001344 return QualType();
1345 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001346
1347 // Now check the two expressions.
1348
1349 // If both operands have arithmetic type, do the usual arithmetic conversions
1350 // to find a common type: C99 6.5.15p3,5.
1351 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00001352 UsualArithmeticConversions(lex, rex);
1353 return lex->getType();
1354 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001355
1356 // If both operands are the same structure or union type, the result is that
1357 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001358 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00001359 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00001360 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00001361 // "If both the operands have structure or union type, the result has
1362 // that type." This implies that CV qualifiers are dropped.
1363 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001364 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001365
1366 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00001367 // The following || allows only one side to be void (a GCC-ism).
1368 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00001369 if (!lexT->isVoidType())
Steve Naroffe701c0a2008-05-12 21:44:38 +00001370 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1371 rex->getSourceRange());
1372 if (!rexT->isVoidType())
1373 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopesd8de7252008-06-04 19:14:12 +00001374 lex->getSourceRange());
Eli Friedman0e724012008-06-04 19:47:51 +00001375 ImpCastExprToType(lex, Context.VoidTy);
1376 ImpCastExprToType(rex, Context.VoidTy);
1377 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00001378 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00001379 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1380 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001381 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1382 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001383 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001384 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001385 return lexT;
1386 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001387 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1388 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001389 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001390 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001391 return rexT;
1392 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00001393 // Handle the case where both operands are pointers before we handle null
1394 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001395 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1396 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1397 // get the "pointed to" types
1398 QualType lhptee = LHSPT->getPointeeType();
1399 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001400
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001401 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1402 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00001403 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001404 // Figure out necessary qualifiers (C99 6.5.15p6)
1405 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001406 QualType destType = Context.getPointerType(destPointee);
1407 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1408 ImpCastExprToType(rex, destType); // promote to void*
1409 return destType;
1410 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00001411 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001412 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001413 QualType destType = Context.getPointerType(destPointee);
1414 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1415 ImpCastExprToType(rex, destType); // promote to void*
1416 return destType;
1417 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001418
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001419 QualType compositeType = lexT;
1420
1421 // If either type is an Objective-C object type then check
1422 // compatibility according to Objective-C.
1423 if (Context.isObjCObjectPointerType(lexT) ||
1424 Context.isObjCObjectPointerType(rexT)) {
1425 // If both operands are interfaces and either operand can be
1426 // assigned to the other, use that type as the composite
1427 // type. This allows
1428 // xxx ? (A*) a : (B*) b
1429 // where B is a subclass of A.
1430 //
1431 // Additionally, as for assignment, if either type is 'id'
1432 // allow silent coercion. Finally, if the types are
1433 // incompatible then make sure to use 'id' as the composite
1434 // type so the result is acceptable for sending messages to.
1435
1436 // FIXME: This code should not be localized to here. Also this
1437 // should use a compatible check instead of abusing the
1438 // canAssignObjCInterfaces code.
1439 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1440 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1441 if (LHSIface && RHSIface &&
1442 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1443 compositeType = lexT;
1444 } else if (LHSIface && RHSIface &&
1445 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1446 compositeType = rexT;
1447 } else if (Context.isObjCIdType(lhptee) ||
1448 Context.isObjCIdType(rhptee)) {
1449 // FIXME: This code looks wrong, because isObjCIdType checks
1450 // the struct but getObjCIdType returns the pointer to
1451 // struct. This is horrible and should be fixed.
1452 compositeType = Context.getObjCIdType();
1453 } else {
1454 QualType incompatTy = Context.getObjCIdType();
1455 ImpCastExprToType(lex, incompatTy);
1456 ImpCastExprToType(rex, incompatTy);
1457 return incompatTy;
1458 }
1459 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1460 rhptee.getUnqualifiedType())) {
Steve Naroffc0ff1ca2008-02-01 22:44:48 +00001461 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001462 lexT.getAsString(), rexT.getAsString(),
1463 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001464 // In this situation, we assume void* type. No especially good
1465 // reason, but this is what gcc does, and we do have to pick
1466 // to get a consistent AST.
1467 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00001468 ImpCastExprToType(lex, incompatTy);
1469 ImpCastExprToType(rex, incompatTy);
1470 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001471 }
1472 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001473 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1474 // differently qualified versions of compatible types, the result type is
1475 // a pointer to an appropriately qualified version of the *composite*
1476 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00001477 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00001478 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00001479 ImpCastExprToType(lex, compositeType);
1480 ImpCastExprToType(rex, compositeType);
1481 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 }
1483 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001484 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1485 // evaluates to "struct objc_object *" (and is handled above when comparing
1486 // id with statically typed objects).
1487 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1488 // GCC allows qualified id and any Objective-C type to devolve to
1489 // id. Currently localizing to here until clear this should be
1490 // part of ObjCQualifiedIdTypesAreCompatible.
1491 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1492 (lexT->isObjCQualifiedIdType() &&
1493 Context.isObjCObjectPointerType(rexT)) ||
1494 (rexT->isObjCQualifiedIdType() &&
1495 Context.isObjCObjectPointerType(lexT))) {
1496 // FIXME: This is not the correct composite type. This only
1497 // happens to work because id can more or less be used anywhere,
1498 // however this may change the type of method sends.
1499 // FIXME: gcc adds some type-checking of the arguments and emits
1500 // (confusing) incompatible comparison warnings in some
1501 // cases. Investigate.
1502 QualType compositeType = Context.getObjCIdType();
1503 ImpCastExprToType(lex, compositeType);
1504 ImpCastExprToType(rex, compositeType);
1505 return compositeType;
1506 }
1507 }
1508
Steve Naroff61f40a22008-09-10 19:17:48 +00001509 // Selection between block pointer types is ok as long as they are the same.
1510 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1511 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1512 return lexT;
1513
Chris Lattner70d67a92008-01-06 22:42:25 +00001514 // Otherwise, the operands are not compatible.
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +00001516 lexT.getAsString(), rexT.getAsString(),
1517 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 return QualType();
1519}
1520
Steve Narofff69936d2007-09-16 03:34:24 +00001521/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00001522/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00001523Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 SourceLocation ColonLoc,
1525 ExprTy *Cond, ExprTy *LHS,
1526 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00001527 Expr *CondExpr = (Expr *) Cond;
1528 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001529
1530 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1531 // was the condition.
1532 bool isLHSNull = LHSExpr == 0;
1533 if (isLHSNull)
1534 LHSExpr = CondExpr;
1535
Chris Lattner26824902007-07-16 21:39:03 +00001536 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1537 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 if (result.isNull())
1539 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001540 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1541 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001542}
1543
Reid Spencer5f016e22007-07-11 17:01:13 +00001544
1545// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1546// being closely modeled after the C99 spec:-). The odd characteristic of this
1547// routine is it effectively iqnores the qualifiers on the top level pointee.
1548// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1549// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001550Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001551Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1552 QualType lhptee, rhptee;
1553
1554 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001555 lhptee = lhsType->getAsPointerType()->getPointeeType();
1556 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001557
1558 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00001559 lhptee = Context.getCanonicalType(lhptee);
1560 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00001561
Chris Lattner5cf216b2008-01-04 18:04:52 +00001562 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001563
1564 // C99 6.5.16.1p1: This following citation is common to constraints
1565 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1566 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00001567 // FIXME: Handle ASQualType
1568 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1569 rhptee.getCVRQualifiers())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001570 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001571
1572 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1573 // incomplete type and the other is a pointer to a qualified or unqualified
1574 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001575 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001576 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001577 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001578
1579 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001580 assert(rhptee->isFunctionType());
1581 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001582 }
1583
1584 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001585 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001586 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001587
1588 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001589 assert(lhptee->isFunctionType());
1590 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001591 }
Eli Friedman3d815e72008-08-22 00:56:42 +00001592
1593 // Check for ObjC interfaces
1594 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1595 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1596 if (LHSIface && RHSIface &&
1597 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1598 return ConvTy;
1599
1600 // ID acts sort of like void* for ObjC interfaces
1601 if (LHSIface && Context.isObjCIdType(rhptee))
1602 return ConvTy;
1603 if (RHSIface && Context.isObjCIdType(lhptee))
1604 return ConvTy;
1605
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1607 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001608 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1609 rhptee.getUnqualifiedType()))
1610 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00001611 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001612}
1613
Steve Naroff1c7d0672008-09-04 15:10:53 +00001614/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1615/// block pointer types are compatible or whether a block and normal pointer
1616/// are compatible. It is more restrict than comparing two function pointer
1617// types.
1618Sema::AssignConvertType
1619Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1620 QualType rhsType) {
1621 QualType lhptee, rhptee;
1622
1623 // get the "pointed to" type (ignoring qualifiers at the top level)
1624 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1625 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1626
1627 // make sure we operate on the canonical type
1628 lhptee = Context.getCanonicalType(lhptee);
1629 rhptee = Context.getCanonicalType(rhptee);
1630
1631 AssignConvertType ConvTy = Compatible;
1632
1633 // For blocks we enforce that qualifiers are identical.
1634 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1635 ConvTy = CompatiblePointerDiscardsQualifiers;
1636
1637 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1638 return IncompatibleBlockPointer;
1639 return ConvTy;
1640}
1641
Reid Spencer5f016e22007-07-11 17:01:13 +00001642/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1643/// has code to accommodate several GCC extensions when type checking
1644/// pointers. Here are some objectionable examples that GCC considers warnings:
1645///
1646/// int a, *pint;
1647/// short *pshort;
1648/// struct foo *pfoo;
1649///
1650/// pint = pshort; // warning: assignment from incompatible pointer type
1651/// a = pint; // warning: assignment makes integer from pointer without a cast
1652/// pint = a; // warning: assignment makes pointer from integer without a cast
1653/// pint = pfoo; // warning: assignment from incompatible pointer type
1654///
1655/// As a result, the code for dealing with pointers is more complex than the
1656/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00001657///
Chris Lattner5cf216b2008-01-04 18:04:52 +00001658Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001659Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00001660 // Get canonical types. We're not formatting these types, just comparing
1661 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001662 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1663 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001664
1665 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00001666 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00001667
Anders Carlsson793680e2007-10-12 23:56:29 +00001668 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattner8f8fc7b2008-04-07 06:52:53 +00001669 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001670 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001671 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001672 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001673
Chris Lattnereca7be62008-04-07 05:30:13 +00001674 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1675 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001676 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00001677 // Relax integer conversions like we do for pointers below.
1678 if (rhsType->isIntegerType())
1679 return IntToPointer;
1680 if (lhsType->isIntegerType())
1681 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00001682 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001683 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00001684
Nate Begemanbe2341d2008-07-14 18:02:46 +00001685 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001686 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00001687 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1688 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00001689 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001690
Nate Begemanbe2341d2008-07-14 18:02:46 +00001691 // If we are allowing lax vector conversions, and LHS and RHS are both
1692 // vectors, the total size only needs to be the same. This is a bitcast;
1693 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00001694 if (getLangOptions().LaxVectorConversions &&
1695 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001696 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1697 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00001698 }
1699 return Incompatible;
1700 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001701
Chris Lattnere8b3e962008-01-04 23:32:24 +00001702 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001704
Chris Lattner78eca282008-04-07 06:49:41 +00001705 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001707 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001708
Chris Lattner78eca282008-04-07 06:49:41 +00001709 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001711
Steve Naroffb4406862008-09-29 18:10:17 +00001712 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00001713 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff1c7d0672008-09-04 15:10:53 +00001714 return BlockVoidPointer;
Steve Naroffb4406862008-09-29 18:10:17 +00001715
1716 // Treat block pointers as objects.
1717 if (getLangOptions().ObjC1 &&
1718 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1719 return Compatible;
1720 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001721 return Incompatible;
1722 }
1723
1724 if (isa<BlockPointerType>(lhsType)) {
1725 if (rhsType->isIntegerType())
1726 return IntToPointer;
1727
Steve Naroffb4406862008-09-29 18:10:17 +00001728 // Treat block pointers as objects.
1729 if (getLangOptions().ObjC1 &&
1730 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1731 return Compatible;
1732
Steve Naroff1c7d0672008-09-04 15:10:53 +00001733 if (rhsType->isBlockPointerType())
1734 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1735
1736 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1737 if (RHSPT->getPointeeType()->isVoidType())
1738 return BlockVoidPointer;
1739 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00001740 return Incompatible;
1741 }
1742
Chris Lattner78eca282008-04-07 06:49:41 +00001743 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001744 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001745 if (lhsType == Context.BoolTy)
1746 return Compatible;
1747
1748 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001749 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00001750
Chris Lattner78eca282008-04-07 06:49:41 +00001751 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001753
1754 if (isa<BlockPointerType>(lhsType) &&
1755 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1756 return BlockVoidPointer;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001757 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001758 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001759
Chris Lattnerfc144e22008-01-04 23:18:45 +00001760 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00001761 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001762 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001763 }
1764 return Incompatible;
1765}
1766
Chris Lattner5cf216b2008-01-04 18:04:52 +00001767Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001768Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroff529a4ad2007-11-27 17:58:44 +00001769 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1770 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00001771 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1772 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00001773 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001774 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00001775 return Compatible;
1776 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001777
1778 // We don't allow conversion of non-null-pointer constants to integers.
1779 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1780 return IntToBlockPointer;
1781
Chris Lattner943140e2007-10-16 02:55:40 +00001782 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001783 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001784 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001785 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001786 //
1787 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1788 // are better understood.
1789 if (!lhsType->isReferenceType())
1790 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001791
Chris Lattner5cf216b2008-01-04 18:04:52 +00001792 Sema::AssignConvertType result =
1793 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00001794
1795 // C99 6.5.16.1p2: The value of the right operand is converted to the
1796 // type of the assignment expression.
1797 if (rExpr->getType() != lhsType)
Chris Lattner1e0a3902008-01-16 19:17:22 +00001798 ImpCastExprToType(rExpr, lhsType);
Steve Narofff1120de2007-08-24 22:33:52 +00001799 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001800}
1801
Chris Lattner5cf216b2008-01-04 18:04:52 +00001802Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001803Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1804 return CheckAssignmentConstraints(lhsType, rhsType);
1805}
1806
Chris Lattnerca5eede2007-12-12 05:47:28 +00001807QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001808 Diag(loc, diag::err_typecheck_invalid_operands,
1809 lex->getType().getAsString(), rex->getType().getAsString(),
1810 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerca5eede2007-12-12 05:47:28 +00001811 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001812}
1813
Steve Naroff49b45262007-07-13 16:58:59 +00001814inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1815 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00001816 // For conversion purposes, we ignore any qualifiers.
1817 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001818 QualType lhsType =
1819 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1820 QualType rhsType =
1821 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001822
Nate Begemanbe2341d2008-07-14 18:02:46 +00001823 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00001824 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001825 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00001826
Nate Begemanbe2341d2008-07-14 18:02:46 +00001827 // Handle the case of a vector & extvector type of the same size and element
1828 // type. It would be nice if we only had one vector type someday.
1829 if (getLangOptions().LaxVectorConversions)
1830 if (const VectorType *LV = lhsType->getAsVectorType())
1831 if (const VectorType *RV = rhsType->getAsVectorType())
1832 if (LV->getElementType() == RV->getElementType() &&
1833 LV->getNumElements() == RV->getNumElements())
1834 return lhsType->isExtVectorType() ? lhsType : rhsType;
1835
1836 // If the lhs is an extended vector and the rhs is a scalar of the same type
1837 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001838 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001839 QualType eltType = V->getElementType();
1840
1841 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1842 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1843 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001844 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001845 return lhsType;
1846 }
1847 }
1848
Nate Begemanbe2341d2008-07-14 18:02:46 +00001849 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00001850 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001851 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001852 QualType eltType = V->getElementType();
1853
1854 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1855 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1856 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001857 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001858 return rhsType;
1859 }
1860 }
1861
Reid Spencer5f016e22007-07-11 17:01:13 +00001862 // You cannot convert between vector values of different size.
1863 Diag(loc, diag::err_typecheck_vector_not_convertable,
1864 lex->getType().getAsString(), rex->getType().getAsString(),
1865 lex->getSourceRange(), rex->getSourceRange());
1866 return QualType();
1867}
1868
1869inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001870 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001871{
Steve Naroff90045e82007-07-13 23:32:42 +00001872 QualType lhsType = lex->getType(), rhsType = rex->getType();
1873
1874 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001875 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001876
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001877 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001878
Steve Naroffa4332e22007-07-17 00:58:39 +00001879 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001880 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001881 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001882}
1883
1884inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001885 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001886{
Steve Naroff90045e82007-07-13 23:32:42 +00001887 QualType lhsType = lex->getType(), rhsType = rex->getType();
1888
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001889 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001890
Steve Naroffa4332e22007-07-17 00:58:39 +00001891 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001892 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001893 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001894}
1895
1896inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001897 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001898{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001899 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001900 return CheckVectorOperands(loc, lex, rex);
1901
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001902 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00001903
Reid Spencer5f016e22007-07-11 17:01:13 +00001904 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001905 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001906 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001907
Eli Friedmand72d16e2008-05-18 18:08:51 +00001908 // Put any potential pointer into PExp
1909 Expr* PExp = lex, *IExp = rex;
1910 if (IExp->getType()->isPointerType())
1911 std::swap(PExp, IExp);
1912
1913 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1914 if (IExp->getType()->isIntegerType()) {
1915 // Check for arithmetic on pointers to incomplete types
1916 if (!PTy->getPointeeType()->isObjectType()) {
1917 if (PTy->getPointeeType()->isVoidType()) {
1918 Diag(loc, diag::ext_gnu_void_ptr,
1919 lex->getSourceRange(), rex->getSourceRange());
1920 } else {
1921 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1922 lex->getType().getAsString(), lex->getSourceRange());
1923 return QualType();
1924 }
1925 }
1926 return PExp->getType();
1927 }
1928 }
1929
Chris Lattnerca5eede2007-12-12 05:47:28 +00001930 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001931}
1932
Chris Lattnereca7be62008-04-07 05:30:13 +00001933// C99 6.5.6
1934QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1935 SourceLocation loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00001936 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001937 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001938
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001939 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001940
Chris Lattner6e4ab612007-12-09 21:53:25 +00001941 // Enforce type constraints: C99 6.5.6p3.
1942
1943 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001944 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001945 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001946
1947 // Either ptr - int or ptr - ptr.
1948 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00001949 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00001950
Chris Lattner6e4ab612007-12-09 21:53:25 +00001951 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00001952 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001953 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001954 if (lpointee->isVoidType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001955 Diag(loc, diag::ext_gnu_void_ptr,
1956 lex->getSourceRange(), rex->getSourceRange());
1957 } else {
1958 Diag(loc, diag::err_typecheck_sub_ptr_object,
1959 lex->getType().getAsString(), lex->getSourceRange());
1960 return QualType();
1961 }
1962 }
1963
1964 // The result type of a pointer-int computation is the pointer type.
1965 if (rex->getType()->isIntegerType())
1966 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001967
Chris Lattner6e4ab612007-12-09 21:53:25 +00001968 // Handle pointer-pointer subtractions.
1969 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00001970 QualType rpointee = RHSPTy->getPointeeType();
1971
Chris Lattner6e4ab612007-12-09 21:53:25 +00001972 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00001973 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001974 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001975 if (rpointee->isVoidType()) {
1976 if (!lpointee->isVoidType())
Chris Lattner6e4ab612007-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 rex->getType().getAsString(), rex->getSourceRange());
1982 return QualType();
1983 }
1984 }
1985
1986 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00001987 if (!Context.typesAreCompatible(
1988 Context.getCanonicalType(lpointee).getUnqualifiedType(),
1989 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001990 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1991 lex->getType().getAsString(), rex->getType().getAsString(),
1992 lex->getSourceRange(), rex->getSourceRange());
1993 return QualType();
1994 }
1995
1996 return Context.getPointerDiffType();
1997 }
1998 }
1999
Chris Lattnerca5eede2007-12-12 05:47:28 +00002000 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002001}
2002
Chris Lattnereca7be62008-04-07 05:30:13 +00002003// C99 6.5.7
2004QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2005 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002006 // C99 6.5.7p2: Each of the operands shall have integer type.
2007 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
2008 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002009
Chris Lattnerca5eede2007-12-12 05:47:28 +00002010 // Shifts don't perform usual arithmetic conversions, they just do integer
2011 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002012 if (!isCompAssign)
2013 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002014 UsualUnaryConversions(rex);
2015
2016 // "The type of the result is that of the promoted left operand."
2017 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002018}
2019
Eli Friedman3d815e72008-08-22 00:56:42 +00002020static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2021 ASTContext& Context) {
2022 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2023 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2024 // ID acts sort of like void* for ObjC interfaces
2025 if (LHSIface && Context.isObjCIdType(RHS))
2026 return true;
2027 if (RHSIface && Context.isObjCIdType(LHS))
2028 return true;
2029 if (!LHSIface || !RHSIface)
2030 return false;
2031 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2032 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2033}
2034
Chris Lattnereca7be62008-04-07 05:30:13 +00002035// C99 6.5.8
2036QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2037 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002038 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2039 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
2040
Chris Lattnera5937dd2007-08-26 01:18:55 +00002041 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002042 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2043 UsualArithmeticConversions(lex, rex);
2044 else {
2045 UsualUnaryConversions(lex);
2046 UsualUnaryConversions(rex);
2047 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002048 QualType lType = lex->getType();
2049 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002050
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002051 // For non-floating point types, check for self-comparisons of the form
2052 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2053 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002054 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002055 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2056 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002057 if (DRL->getDecl() == DRR->getDecl())
2058 Diag(loc, diag::warn_selfcomparison);
2059 }
2060
Chris Lattnera5937dd2007-08-26 01:18:55 +00002061 if (isRelational) {
2062 if (lType->isRealType() && rType->isRealType())
2063 return Context.IntTy;
2064 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002065 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002066 if (lType->isFloatingType()) {
2067 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002068 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002069 }
2070
Chris Lattnera5937dd2007-08-26 01:18:55 +00002071 if (lType->isArithmeticType() && rType->isArithmeticType())
2072 return Context.IntTy;
2073 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002074
Chris Lattnerd28f8152007-08-26 01:10:14 +00002075 bool LHSIsNull = lex->isNullPointerConstant(Context);
2076 bool RHSIsNull = rex->isNullPointerConstant(Context);
2077
Chris Lattnera5937dd2007-08-26 01:18:55 +00002078 // All of the following pointer related warnings are GCC extensions, except
2079 // when handling null pointer constants. One day, we can consider making them
2080 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002081 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002082 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002083 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002084 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002085 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002086
Steve Naroff66296cb2007-11-13 14:57:38 +00002087 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002088 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2089 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002090 RCanPointeeTy.getUnqualifiedType()) &&
2091 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002092 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2093 lType.getAsString(), rType.getAsString(),
2094 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002095 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002096 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002097 return Context.IntTy;
2098 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002099 // Handle block pointer types.
2100 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2101 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2102 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2103
2104 if (!LHSIsNull && !RHSIsNull &&
2105 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2106 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2107 lType.getAsString(), rType.getAsString(),
2108 lex->getSourceRange(), rex->getSourceRange());
2109 }
2110 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2111 return Context.IntTy;
2112 }
Steve Naroff59f53942008-09-28 01:11:11 +00002113 // Allow block pointers to be compared with null pointer constants.
2114 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2115 (lType->isPointerType() && rType->isBlockPointerType())) {
2116 if (!LHSIsNull && !RHSIsNull) {
2117 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2118 lType.getAsString(), rType.getAsString(),
2119 lex->getSourceRange(), rex->getSourceRange());
2120 }
2121 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2122 return Context.IntTy;
2123 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002124
Steve Naroff20373222008-06-03 14:04:54 +00002125 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff87f3b932008-10-20 18:19:10 +00002126 if ((lType->isPointerType() || rType->isPointerType()) &&
2127 !Context.typesAreCompatible(lType, rType)) {
2128 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2129 lType.getAsString(), rType.getAsString(),
2130 lex->getSourceRange(), rex->getSourceRange());
2131 return QualType();
2132 }
Steve Naroff20373222008-06-03 14:04:54 +00002133 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2134 ImpCastExprToType(rex, lType);
2135 return Context.IntTy;
Steve Naroff39579072008-10-14 22:18:38 +00002136 } else {
2137 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
2138 Diag(loc, diag::warn_incompatible_qualified_id_operands,
2139 lex->getType().getAsString(), rex->getType().getAsString(),
2140 lex->getSourceRange(), rex->getSourceRange());
2141 return QualType();
2142 }
Steve Naroff20373222008-06-03 14:04:54 +00002143 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00002144 }
Steve Naroff20373222008-06-03 14:04:54 +00002145 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2146 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002147 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002148 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2149 lType.getAsString(), rType.getAsString(),
2150 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00002151 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002152 return Context.IntTy;
2153 }
Steve Naroff20373222008-06-03 14:04:54 +00002154 if (lType->isIntegerType() &&
2155 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002156 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002157 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2158 lType.getAsString(), rType.getAsString(),
2159 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00002160 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002161 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002162 }
Steve Naroff39218df2008-09-04 16:56:14 +00002163 // Handle block pointers.
2164 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2165 if (!RHSIsNull)
2166 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2167 lType.getAsString(), rType.getAsString(),
2168 lex->getSourceRange(), rex->getSourceRange());
2169 ImpCastExprToType(rex, lType); // promote the integer to pointer
2170 return Context.IntTy;
2171 }
2172 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2173 if (!LHSIsNull)
2174 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2175 lType.getAsString(), rType.getAsString(),
2176 lex->getSourceRange(), rex->getSourceRange());
2177 ImpCastExprToType(lex, rType); // promote the integer to pointer
2178 return Context.IntTy;
2179 }
Chris Lattnerca5eede2007-12-12 05:47:28 +00002180 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002181}
2182
Nate Begemanbe2341d2008-07-14 18:02:46 +00002183/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2184/// operates on extended vector types. Instead of producing an IntTy result,
2185/// like a scalar comparison, a vector comparison produces a vector of integer
2186/// types.
2187QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2188 SourceLocation loc,
2189 bool isRelational) {
2190 // Check to make sure we're operating on vectors of the same type and width,
2191 // Allowing one side to be a scalar of element type.
2192 QualType vType = CheckVectorOperands(loc, lex, rex);
2193 if (vType.isNull())
2194 return vType;
2195
2196 QualType lType = lex->getType();
2197 QualType rType = rex->getType();
2198
2199 // For non-floating point types, check for self-comparisons of the form
2200 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2201 // often indicate logic errors in the program.
2202 if (!lType->isFloatingType()) {
2203 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2204 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2205 if (DRL->getDecl() == DRR->getDecl())
2206 Diag(loc, diag::warn_selfcomparison);
2207 }
2208
2209 // Check for comparisons of floating point operands using != and ==.
2210 if (!isRelational && lType->isFloatingType()) {
2211 assert (rType->isFloatingType());
2212 CheckFloatComparison(loc,lex,rex);
2213 }
2214
2215 // Return the type for the comparison, which is the same as vector type for
2216 // integer vectors, or an integer type of identical size and number of
2217 // elements for floating point vectors.
2218 if (lType->isIntegerType())
2219 return lType;
2220
2221 const VectorType *VTy = lType->getAsVectorType();
2222
2223 // FIXME: need to deal with non-32b int / non-64b long long
2224 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2225 if (TypeSize == 32) {
2226 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2227 }
2228 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2229 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2230}
2231
Reid Spencer5f016e22007-07-11 17:01:13 +00002232inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002233 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002234{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002235 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002236 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002237
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002238 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002239
Steve Naroffa4332e22007-07-17 00:58:39 +00002240 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002241 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00002242 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002243}
2244
2245inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00002246 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00002247{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002248 UsualUnaryConversions(lex);
2249 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002250
Eli Friedman5773a6c2008-05-13 20:16:47 +00002251 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002252 return Context.IntTy;
Chris Lattnerca5eede2007-12-12 05:47:28 +00002253 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002254}
2255
2256inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00002257 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002258{
2259 QualType lhsType = lex->getType();
2260 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner28be73f2008-07-26 21:30:36 +00002261 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002262
2263 switch (mlval) { // C99 6.5.16p2
Chris Lattner5cf216b2008-01-04 18:04:52 +00002264 case Expr::MLV_Valid:
2265 break;
2266 case Expr::MLV_ConstQualified:
2267 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2268 return QualType();
2269 case Expr::MLV_ArrayType:
2270 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2271 lhsType.getAsString(), lex->getSourceRange());
2272 return QualType();
2273 case Expr::MLV_NotObjectType:
2274 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2275 lhsType.getAsString(), lex->getSourceRange());
2276 return QualType();
2277 case Expr::MLV_InvalidExpression:
2278 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2279 lex->getSourceRange());
2280 return QualType();
2281 case Expr::MLV_IncompleteType:
2282 case Expr::MLV_IncompleteVoidType:
2283 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2284 lhsType.getAsString(), lex->getSourceRange());
2285 return QualType();
2286 case Expr::MLV_DuplicateVectorComponents:
2287 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2288 lex->getSourceRange());
2289 return QualType();
Steve Naroff4f6a7d72008-09-26 14:41:28 +00002290 case Expr::MLV_NotBlockQualified:
2291 Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2292 lex->getSourceRange());
2293 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002294 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00002295
Chris Lattner5cf216b2008-01-04 18:04:52 +00002296 AssignConvertType ConvTy;
Chris Lattner2c156472008-08-21 18:04:13 +00002297 if (compoundType.isNull()) {
2298 // Simple assignment "x = y".
Chris Lattner5cf216b2008-01-04 18:04:52 +00002299 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner2c156472008-08-21 18:04:13 +00002300
2301 // If the RHS is a unary plus or minus, check to see if they = and + are
2302 // right next to each other. If so, the user may have typo'd "x =+ 4"
2303 // instead of "x += 4".
2304 Expr *RHSCheck = rex;
2305 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2306 RHSCheck = ICE->getSubExpr();
2307 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2308 if ((UO->getOpcode() == UnaryOperator::Plus ||
2309 UO->getOpcode() == UnaryOperator::Minus) &&
2310 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2311 // Only if the two operators are exactly adjacent.
2312 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2313 Diag(loc, diag::warn_not_compound_assign,
2314 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2315 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2316 }
2317 } else {
2318 // Compound assignment "x += y"
Chris Lattner5cf216b2008-01-04 18:04:52 +00002319 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner2c156472008-08-21 18:04:13 +00002320 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00002321
2322 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2323 rex, "assigning"))
2324 return QualType();
2325
Reid Spencer5f016e22007-07-11 17:01:13 +00002326 // C99 6.5.16p3: The type of an assignment expression is the type of the
2327 // left operand unless the left operand has qualified type, in which case
2328 // it is the unqualified version of the type of the left operand.
2329 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2330 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002331 // C++ 5.17p1: the type of the assignment expression is that of its left
2332 // oprdu.
Chris Lattner5cf216b2008-01-04 18:04:52 +00002333 return lhsType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002334}
2335
2336inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00002337 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00002338
2339 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2340 DefaultFunctionArrayConversion(rex);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002341 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002342}
2343
Steve Naroff49b45262007-07-13 16:58:59 +00002344/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2345/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00002346QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00002347 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002348 assert(!resType.isNull() && "no type for increment/decrement expression");
2349
Steve Naroff084f9ed2007-08-24 17:20:07 +00002350 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00002351 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00002352 if (pt->getPointeeType()->isVoidType()) {
2353 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2354 } else if (!pt->getPointeeType()->isObjectType()) {
2355 // C99 6.5.2.4p2, 6.5.6p2
Reid Spencer5f016e22007-07-11 17:01:13 +00002356 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2357 resType.getAsString(), op->getSourceRange());
2358 return QualType();
2359 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00002360 } else if (!resType->isRealType()) {
2361 if (resType->isComplexType())
2362 // C99 does not support ++/-- on complex types.
2363 Diag(OpLoc, diag::ext_integer_increment_complex,
2364 resType.getAsString(), op->getSourceRange());
2365 else {
2366 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2367 resType.getAsString(), op->getSourceRange());
2368 return QualType();
2369 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002370 }
Steve Naroffdd10e022007-08-23 21:37:33 +00002371 // At this point, we know we have a real, complex or pointer type.
2372 // Now make sure the operand is a modifiable lvalue.
Chris Lattner28be73f2008-07-26 21:30:36 +00002373 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002374 if (mlval != Expr::MLV_Valid) {
2375 // FIXME: emit a more precise diagnostic...
2376 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2377 op->getSourceRange());
2378 return QualType();
2379 }
2380 return resType;
2381}
2382
Anders Carlsson369dee42008-02-01 07:15:58 +00002383/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00002384/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002385/// where the declaration is needed for type checking. We only need to
2386/// handle cases when the expression references a function designator
2387/// or is an lvalue. Here are some examples:
2388/// - &(x) => x
2389/// - &*****f => f for f a function designator.
2390/// - &s.xx => s
2391/// - &s.zz[1].yy -> s, if zz is an array
2392/// - *(x + 1) -> x, if x is an array
2393/// - &"123"[2] -> 0
2394/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002395static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002396 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002397 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002398 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002399 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00002400 // Fields cannot be declared with a 'register' storage class.
2401 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002402 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00002403 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00002404 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00002405 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002406 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00002407
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002408 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00002409 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00002410 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00002411 return 0;
2412 else
2413 return VD;
2414 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002415 case Stmt::UnaryOperatorClass: {
2416 UnaryOperator *UO = cast<UnaryOperator>(E);
2417
2418 switch(UO->getOpcode()) {
2419 case UnaryOperator::Deref: {
2420 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002421 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2422 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2423 if (!VD || VD->getType()->isPointerType())
2424 return 0;
2425 return VD;
2426 }
2427 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002428 }
2429 case UnaryOperator::Real:
2430 case UnaryOperator::Imag:
2431 case UnaryOperator::Extension:
2432 return getPrimaryDecl(UO->getSubExpr());
2433 default:
2434 return 0;
2435 }
2436 }
2437 case Stmt::BinaryOperatorClass: {
2438 BinaryOperator *BO = cast<BinaryOperator>(E);
2439
2440 // Handle cases involving pointer arithmetic. The result of an
2441 // Assign or AddAssign is not an lvalue so they can be ignored.
2442
2443 // (x + n) or (n + x) => x
2444 if (BO->getOpcode() == BinaryOperator::Add) {
2445 if (BO->getLHS()->getType()->isPointerType()) {
2446 return getPrimaryDecl(BO->getLHS());
2447 } else if (BO->getRHS()->getType()->isPointerType()) {
2448 return getPrimaryDecl(BO->getRHS());
2449 }
2450 }
2451
2452 return 0;
2453 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002454 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002455 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00002456 case Stmt::ImplicitCastExprClass:
2457 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002458 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00002459 default:
2460 return 0;
2461 }
2462}
2463
2464/// CheckAddressOfOperand - The operand of & must be either a function
2465/// designator or an lvalue designating an object. If it is an lvalue, the
2466/// object cannot be declared with storage class register or be a bit field.
2467/// Note: The usual conversions are *not* applied to the operand of the &
2468/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2469QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff08f19672008-01-13 17:10:08 +00002470 if (getLangOptions().C99) {
2471 // Implement C99-only parts of addressof rules.
2472 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2473 if (uOp->getOpcode() == UnaryOperator::Deref)
2474 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2475 // (assuming the deref expression is valid).
2476 return uOp->getSubExpr()->getType();
2477 }
2478 // Technically, there should be a check for array subscript
2479 // expressions here, but the result of one is always an lvalue anyway.
2480 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002481 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00002482 Expr::isLvalueResult lval = op->isLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002483
2484 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00002485 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2486 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00002487 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2488 op->getSourceRange());
2489 return QualType();
2490 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00002491 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2492 if (MemExpr->getMemberDecl()->isBitField()) {
2493 Diag(OpLoc, diag::err_typecheck_address_of,
2494 std::string("bit-field"), op->getSourceRange());
2495 return QualType();
2496 }
2497 // Check for Apple extension for accessing vector components.
2498 } else if (isa<ArraySubscriptExpr>(op) &&
2499 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2500 Diag(OpLoc, diag::err_typecheck_address_of,
2501 std::string("vector"), op->getSourceRange());
2502 return QualType();
2503 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00002504 // We have an lvalue with a decl. Make sure the decl is not declared
2505 // with the register storage-class specifier.
2506 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2507 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroffbcb2b612008-02-29 23:30:25 +00002508 Diag(OpLoc, diag::err_typecheck_address_of,
2509 std::string("register variable"), op->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002510 return QualType();
2511 }
2512 } else
2513 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002514 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00002515
Reid Spencer5f016e22007-07-11 17:01:13 +00002516 // If the operand has type "type", the result has type "pointer to type".
2517 return Context.getPointerType(op->getType());
2518}
2519
2520QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002521 UsualUnaryConversions(op);
2522 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002523
Chris Lattnerbefee482007-07-31 16:53:04 +00002524 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff08f19672008-01-13 17:10:08 +00002525 // Note that per both C89 and C99, this is always legal, even
2526 // if ptype is an incomplete type or void.
2527 // It would be possible to warn about dereferencing a
2528 // void pointer, but it's completely well-defined,
2529 // and such a warning is unlikely to catch any mistakes.
2530 return PT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002531 }
2532 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2533 qType.getAsString(), op->getSourceRange());
2534 return QualType();
2535}
2536
2537static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2538 tok::TokenKind Kind) {
2539 BinaryOperator::Opcode Opc;
2540 switch (Kind) {
2541 default: assert(0 && "Unknown binop!");
2542 case tok::star: Opc = BinaryOperator::Mul; break;
2543 case tok::slash: Opc = BinaryOperator::Div; break;
2544 case tok::percent: Opc = BinaryOperator::Rem; break;
2545 case tok::plus: Opc = BinaryOperator::Add; break;
2546 case tok::minus: Opc = BinaryOperator::Sub; break;
2547 case tok::lessless: Opc = BinaryOperator::Shl; break;
2548 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2549 case tok::lessequal: Opc = BinaryOperator::LE; break;
2550 case tok::less: Opc = BinaryOperator::LT; break;
2551 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2552 case tok::greater: Opc = BinaryOperator::GT; break;
2553 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2554 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2555 case tok::amp: Opc = BinaryOperator::And; break;
2556 case tok::caret: Opc = BinaryOperator::Xor; break;
2557 case tok::pipe: Opc = BinaryOperator::Or; break;
2558 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2559 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2560 case tok::equal: Opc = BinaryOperator::Assign; break;
2561 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2562 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2563 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2564 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2565 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2566 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2567 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2568 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2569 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2570 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2571 case tok::comma: Opc = BinaryOperator::Comma; break;
2572 }
2573 return Opc;
2574}
2575
2576static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2577 tok::TokenKind Kind) {
2578 UnaryOperator::Opcode Opc;
2579 switch (Kind) {
2580 default: assert(0 && "Unknown unary op!");
2581 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2582 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2583 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2584 case tok::star: Opc = UnaryOperator::Deref; break;
2585 case tok::plus: Opc = UnaryOperator::Plus; break;
2586 case tok::minus: Opc = UnaryOperator::Minus; break;
2587 case tok::tilde: Opc = UnaryOperator::Not; break;
2588 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2589 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2590 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2591 case tok::kw___real: Opc = UnaryOperator::Real; break;
2592 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2593 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2594 }
2595 return Opc;
2596}
2597
2598// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002599Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00002600 ExprTy *LHS, ExprTy *RHS) {
2601 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2602 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2603
Steve Narofff69936d2007-09-16 03:34:24 +00002604 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2605 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00002606
2607 QualType ResultTy; // Result type of the binary operator.
2608 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2609
2610 switch (Opc) {
2611 default:
2612 assert(0 && "Unknown binary expr!");
2613 case BinaryOperator::Assign:
2614 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2615 break;
2616 case BinaryOperator::Mul:
2617 case BinaryOperator::Div:
2618 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2619 break;
2620 case BinaryOperator::Rem:
2621 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2622 break;
2623 case BinaryOperator::Add:
2624 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2625 break;
2626 case BinaryOperator::Sub:
2627 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2628 break;
2629 case BinaryOperator::Shl:
2630 case BinaryOperator::Shr:
2631 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2632 break;
2633 case BinaryOperator::LE:
2634 case BinaryOperator::LT:
2635 case BinaryOperator::GE:
2636 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002637 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002638 break;
2639 case BinaryOperator::EQ:
2640 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002641 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002642 break;
2643 case BinaryOperator::And:
2644 case BinaryOperator::Xor:
2645 case BinaryOperator::Or:
2646 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2647 break;
2648 case BinaryOperator::LAnd:
2649 case BinaryOperator::LOr:
2650 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2651 break;
2652 case BinaryOperator::MulAssign:
2653 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002654 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002655 if (!CompTy.isNull())
2656 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2657 break;
2658 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002659 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002660 if (!CompTy.isNull())
2661 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2662 break;
2663 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002664 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002665 if (!CompTy.isNull())
2666 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2667 break;
2668 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002669 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002670 if (!CompTy.isNull())
2671 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2672 break;
2673 case BinaryOperator::ShlAssign:
2674 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002675 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002676 if (!CompTy.isNull())
2677 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2678 break;
2679 case BinaryOperator::AndAssign:
2680 case BinaryOperator::XorAssign:
2681 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002682 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002683 if (!CompTy.isNull())
2684 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2685 break;
2686 case BinaryOperator::Comma:
2687 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2688 break;
2689 }
2690 if (ResultTy.isNull())
2691 return true;
2692 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002693 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002694 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002695 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002696}
2697
2698// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002699Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00002700 ExprTy *input) {
2701 Expr *Input = (Expr*)input;
2702 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2703 QualType resultType;
2704 switch (Opc) {
2705 default:
2706 assert(0 && "Unimplemented unary expr!");
2707 case UnaryOperator::PreInc:
2708 case UnaryOperator::PreDec:
2709 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2710 break;
2711 case UnaryOperator::AddrOf:
2712 resultType = CheckAddressOfOperand(Input, OpLoc);
2713 break;
2714 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00002715 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002716 resultType = CheckIndirectionOperand(Input, OpLoc);
2717 break;
2718 case UnaryOperator::Plus:
2719 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002720 UsualUnaryConversions(Input);
2721 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002722 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2723 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2724 resultType.getAsString());
2725 break;
2726 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002727 UsualUnaryConversions(Input);
2728 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00002729 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2730 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2731 // C99 does not support '~' for complex conjugation.
2732 Diag(OpLoc, diag::ext_integer_complement_complex,
2733 resultType.getAsString(), Input->getSourceRange());
2734 else if (!resultType->isIntegerType())
2735 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2736 resultType.getAsString(), Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002737 break;
2738 case UnaryOperator::LNot: // logical negation
2739 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002740 DefaultFunctionArrayConversion(Input);
2741 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002742 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2743 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2744 resultType.getAsString());
2745 // LNot always has type int. C99 6.5.3.3p5.
2746 resultType = Context.IntTy;
2747 break;
2748 case UnaryOperator::SizeOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002749 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2750 Input->getSourceRange(), true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002751 break;
2752 case UnaryOperator::AlignOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002753 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2754 Input->getSourceRange(), false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002755 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00002756 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00002757 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00002758 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00002759 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002760 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00002761 resultType = Input->getType();
2762 break;
2763 }
2764 if (resultType.isNull())
2765 return true;
2766 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2767}
2768
Steve Naroff1b273c42007-09-16 14:56:35 +00002769/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2770Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00002771 SourceLocation LabLoc,
2772 IdentifierInfo *LabelII) {
2773 // Look up the record for this label identifier.
2774 LabelStmt *&LabelDecl = LabelMap[LabelII];
2775
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00002776 // If we haven't seen this label yet, create a forward reference. It
2777 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00002778 if (LabelDecl == 0)
2779 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2780
2781 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00002782 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2783 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00002784}
2785
Steve Naroff1b273c42007-09-16 14:56:35 +00002786Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002787 SourceLocation RPLoc) { // "({..})"
2788 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2789 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2790 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2791
2792 // FIXME: there are a variety of strange constraints to enforce here, for
2793 // example, it is not possible to goto into a stmt expression apparently.
2794 // More semantic analysis is needed.
2795
2796 // FIXME: the last statement in the compount stmt has its value used. We
2797 // should not warn about it being unused.
2798
2799 // If there are sub stmts in the compound stmt, take the type of the last one
2800 // as the type of the stmtexpr.
2801 QualType Ty = Context.VoidTy;
2802
Chris Lattner611b2ec2008-07-26 19:51:01 +00002803 if (!Compound->body_empty()) {
2804 Stmt *LastStmt = Compound->body_back();
2805 // If LastStmt is a label, skip down through into the body.
2806 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2807 LastStmt = Label->getSubStmt();
2808
2809 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002810 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00002811 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002812
2813 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2814}
Steve Naroffd34e9152007-08-01 22:05:33 +00002815
Steve Naroff1b273c42007-09-16 14:56:35 +00002816Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002817 SourceLocation TypeLoc,
2818 TypeTy *argty,
2819 OffsetOfComponent *CompPtr,
2820 unsigned NumComponents,
2821 SourceLocation RPLoc) {
2822 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2823 assert(!ArgTy.isNull() && "Missing type argument!");
2824
2825 // We must have at least one component that refers to the type, and the first
2826 // one is known to be a field designator. Verify that the ArgTy represents
2827 // a struct/union/class.
2828 if (!ArgTy->isRecordType())
2829 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2830
2831 // Otherwise, create a compound literal expression as the base, and
2832 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00002833 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002834
Chris Lattner9e2b75c2007-08-31 21:49:13 +00002835 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2836 // GCC extension, diagnose them.
2837 if (NumComponents != 1)
2838 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2839 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2840
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002841 for (unsigned i = 0; i != NumComponents; ++i) {
2842 const OffsetOfComponent &OC = CompPtr[i];
2843 if (OC.isBrackets) {
2844 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002845 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002846 if (!AT) {
2847 delete Res;
2848 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2849 Res->getType().getAsString());
2850 }
2851
Chris Lattner704fe352007-08-30 17:59:59 +00002852 // FIXME: C++: Verify that operator[] isn't overloaded.
2853
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002854 // C99 6.5.2.1p1
2855 Expr *Idx = static_cast<Expr*>(OC.U.E);
2856 if (!Idx->getType()->isIntegerType())
2857 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2858 Idx->getSourceRange());
2859
2860 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2861 continue;
2862 }
2863
2864 const RecordType *RC = Res->getType()->getAsRecordType();
2865 if (!RC) {
2866 delete Res;
2867 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2868 Res->getType().getAsString());
2869 }
2870
2871 // Get the decl corresponding to this.
2872 RecordDecl *RD = RC->getDecl();
2873 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2874 if (!MemberDecl)
2875 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2876 OC.U.IdentInfo->getName(),
2877 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00002878
2879 // FIXME: C++: Verify that MemberDecl isn't a static field.
2880 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00002881 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2882 // matter here.
2883 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002884 }
2885
2886 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2887 BuiltinLoc);
2888}
2889
2890
Steve Naroff1b273c42007-09-16 14:56:35 +00002891Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00002892 TypeTy *arg1, TypeTy *arg2,
2893 SourceLocation RPLoc) {
2894 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2895 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2896
2897 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2898
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002899 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00002900}
2901
Steve Naroff1b273c42007-09-16 14:56:35 +00002902Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00002903 ExprTy *expr1, ExprTy *expr2,
2904 SourceLocation RPLoc) {
2905 Expr *CondExpr = static_cast<Expr*>(cond);
2906 Expr *LHSExpr = static_cast<Expr*>(expr1);
2907 Expr *RHSExpr = static_cast<Expr*>(expr2);
2908
2909 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2910
2911 // The conditional expression is required to be a constant expression.
2912 llvm::APSInt condEval(32);
2913 SourceLocation ExpLoc;
2914 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2915 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2916 CondExpr->getSourceRange());
2917
2918 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2919 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2920 RHSExpr->getType();
2921 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2922}
2923
Steve Naroff4eb206b2008-09-03 18:15:37 +00002924//===----------------------------------------------------------------------===//
2925// Clang Extensions.
2926//===----------------------------------------------------------------------===//
2927
2928/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00002929void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00002930 // Analyze block parameters.
2931 BlockSemaInfo *BSI = new BlockSemaInfo();
2932
2933 // Add BSI to CurBlock.
2934 BSI->PrevBlockInfo = CurBlock;
2935 CurBlock = BSI;
2936
2937 BSI->ReturnType = 0;
2938 BSI->TheScope = BlockScope;
2939
Steve Naroff090276f2008-10-10 01:28:17 +00002940 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
2941 PushDeclContext(BSI->TheDecl);
2942}
2943
2944void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00002945 // Analyze arguments to block.
2946 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2947 "Not a function declarator!");
2948 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2949
Steve Naroff090276f2008-10-10 01:28:17 +00002950 CurBlock->hasPrototype = FTI.hasPrototype;
2951 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002952
2953 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2954 // no arguments, not a function that takes a single void argument.
2955 if (FTI.hasPrototype &&
2956 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2957 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2958 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2959 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00002960 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002961 } else if (FTI.hasPrototype) {
2962 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00002963 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2964 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002965 }
Steve Naroff090276f2008-10-10 01:28:17 +00002966 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
2967
2968 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
2969 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
2970 // If this has an identifier, add it to the scope stack.
2971 if ((*AI)->getIdentifier())
2972 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00002973}
2974
2975/// ActOnBlockError - If there is an error parsing a block, this callback
2976/// is invoked to pop the information about the block from the action impl.
2977void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
2978 // Ensure that CurBlock is deleted.
2979 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
2980
2981 // Pop off CurBlock, handle nested blocks.
2982 CurBlock = CurBlock->PrevBlockInfo;
2983
2984 // FIXME: Delete the ParmVarDecl objects as well???
2985
2986}
2987
2988/// ActOnBlockStmtExpr - This is called when the body of a block statement
2989/// literal was successfully completed. ^(int x){...}
2990Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
2991 Scope *CurScope) {
2992 // Ensure that CurBlock is deleted.
2993 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2994 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
2995
Steve Naroff090276f2008-10-10 01:28:17 +00002996 PopDeclContext();
2997
Steve Naroff4eb206b2008-09-03 18:15:37 +00002998 // Pop off CurBlock, handle nested blocks.
2999 CurBlock = CurBlock->PrevBlockInfo;
3000
3001 QualType RetTy = Context.VoidTy;
3002 if (BSI->ReturnType)
3003 RetTy = QualType(BSI->ReturnType, 0);
3004
3005 llvm::SmallVector<QualType, 8> ArgTypes;
3006 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3007 ArgTypes.push_back(BSI->Params[i]->getType());
3008
3009 QualType BlockTy;
3010 if (!BSI->hasPrototype)
3011 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3012 else
3013 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
3014 BSI->isVariadic);
3015
3016 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00003017
Steve Naroff1c90bfc2008-10-08 18:44:00 +00003018 BSI->TheDecl->setBody(Body.take());
3019 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003020}
3021
Nate Begeman67295d02008-01-30 20:50:20 +00003022/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00003023/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00003024/// The number of arguments has already been validated to match the number of
3025/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003026static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3027 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00003028 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00003029 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00003030 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3031 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00003032
3033 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00003034 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00003035 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003036 return true;
3037}
3038
3039Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3040 SourceLocation *CommaLocs,
3041 SourceLocation BuiltinLoc,
3042 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003043 // __builtin_overload requires at least 2 arguments
3044 if (NumArgs < 2)
3045 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3046 SourceRange(BuiltinLoc, RParenLoc));
Nate Begemane2ce1d92008-01-17 17:46:27 +00003047
Nate Begemane2ce1d92008-01-17 17:46:27 +00003048 // The first argument is required to be a constant expression. It tells us
3049 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003050 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003051 Expr *NParamsExpr = Args[0];
3052 llvm::APSInt constEval(32);
3053 SourceLocation ExpLoc;
3054 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
3055 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3056 NParamsExpr->getSourceRange());
3057
3058 // Verify that the number of parameters is > 0
3059 unsigned NumParams = constEval.getZExtValue();
3060 if (NumParams == 0)
3061 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3062 NParamsExpr->getSourceRange());
3063 // Verify that we have at least 1 + NumParams arguments to the builtin.
3064 if ((NumParams + 1) > NumArgs)
3065 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3066 SourceRange(BuiltinLoc, RParenLoc));
3067
3068 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00003069 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003070 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003071 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3072 // UsualUnaryConversions will convert the function DeclRefExpr into a
3073 // pointer to function.
3074 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00003075 const FunctionTypeProto *FnType = 0;
3076 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3077 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003078
3079 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3080 // parameters, and the number of parameters must match the value passed to
3081 // the builtin.
3082 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begeman67295d02008-01-30 20:50:20 +00003083 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
3084 Fn->getSourceRange());
Nate Begemane2ce1d92008-01-17 17:46:27 +00003085
3086 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00003087 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00003088 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003089 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003090 if (OE)
3091 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
3092 OE->getFn()->getSourceRange());
3093 // Remember our match, and continue processing the remaining arguments
3094 // to catch any errors.
3095 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
3096 BuiltinLoc, RParenLoc);
3097 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003098 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00003099 // Return the newly created OverloadExpr node, if we succeded in matching
3100 // exactly one of the candidate functions.
3101 if (OE)
3102 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003103
3104 // If we didn't find a matching function Expr in the __builtin_overload list
3105 // the return an error.
3106 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00003107 for (unsigned i = 0; i != NumParams; ++i) {
3108 if (i != 0) typeNames += ", ";
3109 typeNames += Args[i+1]->getType().getAsString();
3110 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003111
3112 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3113 SourceRange(BuiltinLoc, RParenLoc));
3114}
3115
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003116Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3117 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00003118 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003119 Expr *E = static_cast<Expr*>(expr);
3120 QualType T = QualType::getFromOpaquePtr(type);
3121
3122 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003123
3124 // Get the va_list type
3125 QualType VaListType = Context.getBuiltinVaListType();
3126 // Deal with implicit array decay; for example, on x86-64,
3127 // va_list is an array, but it's supposed to decay to
3128 // a pointer for va_arg.
3129 if (VaListType->isArrayType())
3130 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00003131 // Make sure the input expression also decays appropriately.
3132 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003133
3134 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003135 return Diag(E->getLocStart(),
3136 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3137 E->getType().getAsString(),
3138 E->getSourceRange());
3139
3140 // FIXME: Warn if a non-POD type is passed in.
3141
3142 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
3143}
3144
Chris Lattner5cf216b2008-01-04 18:04:52 +00003145bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3146 SourceLocation Loc,
3147 QualType DstType, QualType SrcType,
3148 Expr *SrcExpr, const char *Flavor) {
3149 // Decode the result (notice that AST's are still created for extensions).
3150 bool isInvalid = false;
3151 unsigned DiagKind;
3152 switch (ConvTy) {
3153 default: assert(0 && "Unknown conversion type");
3154 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003155 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00003156 DiagKind = diag::ext_typecheck_convert_pointer_int;
3157 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003158 case IntToPointer:
3159 DiagKind = diag::ext_typecheck_convert_int_pointer;
3160 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003161 case IncompatiblePointer:
3162 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3163 break;
3164 case FunctionVoidPointer:
3165 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3166 break;
3167 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00003168 // If the qualifiers lost were because we were applying the
3169 // (deprecated) C++ conversion from a string literal to a char*
3170 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3171 // Ideally, this check would be performed in
3172 // CheckPointerTypesForAssignment. However, that would require a
3173 // bit of refactoring (so that the second argument is an
3174 // expression, rather than a type), which should be done as part
3175 // of a larger effort to fix CheckPointerTypesForAssignment for
3176 // C++ semantics.
3177 if (getLangOptions().CPlusPlus &&
3178 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3179 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003180 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3181 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003182 case IntToBlockPointer:
3183 DiagKind = diag::err_int_to_block_pointer;
3184 break;
3185 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00003186 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003187 break;
3188 case BlockVoidPointer:
3189 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3190 break;
Steve Naroff39579072008-10-14 22:18:38 +00003191 case IncompatibleObjCQualifiedId:
3192 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3193 // it can give a more specific diagnostic.
3194 DiagKind = diag::warn_incompatible_qualified_id;
3195 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003196 case Incompatible:
3197 DiagKind = diag::err_typecheck_convert_incompatible;
3198 isInvalid = true;
3199 break;
3200 }
3201
3202 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3203 SrcExpr->getSourceRange());
3204 return isInvalid;
3205}