blob: 014e457b9760cd606d5e6ae91b9ac86eaf8d112c [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"
Ted Kremenek588e5eb2007-11-25 00:58:00 +000015#include "SemaUtil.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
Steve Naroff6a8a9a42007-10-02 20:01:56 +000018#include "clang/AST/DeclObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/AST/Expr.h"
Steve Naroff563477d2007-09-18 23:55:05 +000020#include "clang/Parse/DeclSpec.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/Lex/Preprocessor.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Basic/SourceManager.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/TargetInfo.h"
Chris Lattner925e60d2007-12-28 05:29:59 +000027#include "llvm/ADT/OwningPtr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "llvm/ADT/SmallString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000029#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31
Steve Narofff69936d2007-09-16 03:34:24 +000032/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +000033/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
34/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
35/// multiple tokens. However, the common case is that StringToks points to one
36/// string.
37///
38Action::ExprResult
Steve Narofff69936d2007-09-16 03:34:24 +000039Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +000040 assert(NumStringToks && "Must have at least one string!");
41
42 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
43 if (Literal.hadError)
44 return ExprResult(true);
45
46 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
47 for (unsigned i = 0; i != NumStringToks; ++i)
48 StringTokLocs.push_back(StringToks[i].getLocation());
49
50 // FIXME: handle wchar_t
Anders Carlssonee98ac52007-10-15 02:50:23 +000051 QualType t;
52
53 if (Literal.Pascal)
54 t = Context.getPointerType(Context.UnsignedCharTy);
55 else
56 t = Context.getPointerType(Context.CharTy);
57
58 if (Literal.Pascal && Literal.GetStringLength() > 256)
59 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
60 SourceRange(StringToks[0].getLocation(),
61 StringToks[NumStringToks-1].getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +000062
63 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
64 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlssonee98ac52007-10-15 02:50:23 +000065 Literal.AnyWide, t,
66 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +000067 StringToks[NumStringToks-1].getLocation());
68}
69
70
Steve Naroff08d92e42007-09-15 18:49:24 +000071/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +000072/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
73/// identifier is used in an function call context.
Steve Naroff08d92e42007-09-15 18:49:24 +000074Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +000075 IdentifierInfo &II,
76 bool HasTrailingLParen) {
77 // Could be enum-constant or decl.
Steve Naroff8c9f13e2007-09-16 16:16:00 +000078 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Reid Spencer5f016e22007-07-11 17:01:13 +000079 if (D == 0) {
80 // Otherwise, this could be an implicitly declared function reference (legal
81 // in C90, extension in C99).
82 if (HasTrailingLParen &&
83 // Not in C++.
84 !getLangOptions().CPlusPlus)
85 D = ImplicitlyDefineFunction(Loc, II, S);
86 else {
Steve Naroff7779db42007-11-12 14:29:37 +000087 if (CurMethodDecl) {
88 ObjcInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
89 ObjcInterfaceDecl *clsDeclared;
Steve Naroff7e3411b2007-11-15 02:58:25 +000090 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
91 IdentifierInfo &II = Context.Idents.get("self");
92 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
93 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
94 static_cast<Expr*>(SelfExpr.Val), true, true);
95 }
Steve Naroff7779db42007-11-12 14:29:37 +000096 }
Reid Spencer5f016e22007-07-11 17:01:13 +000097 // If this name wasn't predeclared and if this is not a function call,
98 // diagnose the problem.
99 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
100 }
101 }
Steve Naroffe1223f72007-08-28 03:03:08 +0000102 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroff53a32342007-08-28 18:45:29 +0000103 // Only create DeclRefExpr's for valid Decl's.
Steve Naroff5912a352007-08-28 20:14:24 +0000104 if (VD->isInvalidDecl())
Steve Naroffe1223f72007-08-28 03:03:08 +0000105 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000106 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroffe1223f72007-08-28 03:03:08 +0000107 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000108 if (isa<TypedefDecl>(D))
109 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Fariborz Jahanian5ef404f2007-12-05 18:16:33 +0000110 if (isa<ObjcInterfaceDecl>(D))
111 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000112
113 assert(0 && "Invalid decl");
Chris Lattnereddbe032007-07-21 04:57:45 +0000114 abort();
Reid Spencer5f016e22007-07-11 17:01:13 +0000115}
116
Steve Narofff69936d2007-09-16 03:34:24 +0000117Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000118 tok::TokenKind Kind) {
119 PreDefinedExpr::IdentType IT;
120
Reid Spencer5f016e22007-07-11 17:01:13 +0000121 switch (Kind) {
122 default:
123 assert(0 && "Unknown simple primary expr!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000124 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
Anders Carlsson22742662007-07-21 05:21:51 +0000125 IT = PreDefinedExpr::Func;
126 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000128 IT = PreDefinedExpr::Function;
129 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000130 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000131 IT = PreDefinedExpr::PrettyFunction;
132 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000133 }
Anders Carlsson22742662007-07-21 05:21:51 +0000134
135 // Pre-defined identifiers are always of type char *.
136 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000137}
138
Steve Narofff69936d2007-09-16 03:34:24 +0000139Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000140 llvm::SmallString<16> CharBuffer;
141 CharBuffer.resize(Tok.getLength());
142 const char *ThisTokBegin = &CharBuffer[0];
143 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
144
145 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
146 Tok.getLocation(), PP);
147 if (Literal.hadError())
148 return ExprResult(true);
149 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
150 Tok.getLocation());
151}
152
Steve Narofff69936d2007-09-16 03:34:24 +0000153Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000154 // fast path for a single digit (which is quite common). A single digit
155 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
156 if (Tok.getLength() == 1) {
157 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
158
Chris Lattner701e5eb2007-09-04 02:45:27 +0000159 unsigned IntSize = static_cast<unsigned>(
160 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000161 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
162 Context.IntTy,
163 Tok.getLocation()));
164 }
165 llvm::SmallString<512> IntegerBuffer;
166 IntegerBuffer.resize(Tok.getLength());
167 const char *ThisTokBegin = &IntegerBuffer[0];
168
169 // Get the spelling of the token, which eliminates trigraphs, etc.
170 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
171 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
172 Tok.getLocation(), PP);
173 if (Literal.hadError)
174 return ExprResult(true);
175
Chris Lattner5d661452007-08-26 03:42:43 +0000176 Expr *Res;
177
178 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000179 QualType Ty;
180 const llvm::fltSemantics *Format;
181 uint64_t Size; unsigned Align;
182
183 if (Literal.isFloat) {
184 Ty = Context.FloatTy;
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000185 Context.Target.getFloatInfo(Size, Align, Format,
186 Context.getFullLoc(Tok.getLocation()));
187
Chris Lattner525a0502007-09-22 18:29:59 +0000188 } else if (Literal.isLong) {
189 Ty = Context.LongDoubleTy;
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000190 Context.Target.getLongDoubleInfo(Size, Align, Format,
191 Context.getFullLoc(Tok.getLocation()));
Chris Lattner525a0502007-09-22 18:29:59 +0000192 } else {
193 Ty = Context.DoubleTy;
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000194 Context.Target.getDoubleInfo(Size, Align, Format,
195 Context.getFullLoc(Tok.getLocation()));
Chris Lattner525a0502007-09-22 18:29:59 +0000196 }
197
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000198 // isExact will be set by GetFloatValue().
199 bool isExact = false;
200
201 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
202 Ty, Tok.getLocation());
203
Chris Lattner5d661452007-08-26 03:42:43 +0000204 } else if (!Literal.isIntegerLiteral()) {
205 return ExprResult(true);
206 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000207 QualType t;
208
Neil Boothb9449512007-08-29 22:00:19 +0000209 // long long is a C99 feature.
210 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000211 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000212 Diag(Tok.getLocation(), diag::ext_longlong);
213
Reid Spencer5f016e22007-07-11 17:01:13 +0000214 // Get the value in the widest-possible width.
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000215 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(
216 Context.getFullLoc(Tok.getLocation())), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000217
218 if (Literal.GetIntegerValue(ResultVal)) {
219 // If this value didn't fit into uintmax_t, warn and force to ull.
220 Diag(Tok.getLocation(), diag::warn_integer_too_large);
221 t = Context.UnsignedLongLongTy;
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000222 assert(Context.getTypeSize(t, Tok.getLocation()) ==
Reid Spencer5f016e22007-07-11 17:01:13 +0000223 ResultVal.getBitWidth() && "long long is not intmax_t?");
224 } else {
225 // If this value fits into a ULL, try to figure out what else it fits into
226 // according to the rules of C99 6.4.4.1p5.
227
228 // Octal, Hexadecimal, and integers with a U suffix are allowed to
229 // be an unsigned int.
230 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
231
232 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner97c51562007-08-23 21:58:08 +0000233 if (!Literal.isLong && !Literal.isLongLong) {
234 // Are int/unsigned possibilities?
Chris Lattner701e5eb2007-09-04 02:45:27 +0000235 unsigned IntSize = static_cast<unsigned>(
236 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 // Does it fit in a unsigned int?
238 if (ResultVal.isIntN(IntSize)) {
239 // Does it fit in a signed int?
240 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
241 t = Context.IntTy;
242 else if (AllowUnsigned)
243 t = Context.UnsignedIntTy;
244 }
245
246 if (!t.isNull())
247 ResultVal.trunc(IntSize);
248 }
249
250 // Are long/unsigned long possibilities?
251 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner701e5eb2007-09-04 02:45:27 +0000252 unsigned LongSize = static_cast<unsigned>(
253 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000254
255 // Does it fit in a unsigned long?
256 if (ResultVal.isIntN(LongSize)) {
257 // Does it fit in a signed long?
258 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
259 t = Context.LongTy;
260 else if (AllowUnsigned)
261 t = Context.UnsignedLongTy;
262 }
263 if (!t.isNull())
264 ResultVal.trunc(LongSize);
265 }
266
267 // Finally, check long long if needed.
268 if (t.isNull()) {
Chris Lattner701e5eb2007-09-04 02:45:27 +0000269 unsigned LongLongSize = static_cast<unsigned>(
270 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000271
272 // Does it fit in a unsigned long long?
273 if (ResultVal.isIntN(LongLongSize)) {
274 // Does it fit in a signed long long?
275 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
276 t = Context.LongLongTy;
277 else if (AllowUnsigned)
278 t = Context.UnsignedLongLongTy;
279 }
280 }
281
282 // If we still couldn't decide a type, we probably have something that
283 // does not fit in a signed long long, but has no U suffix.
284 if (t.isNull()) {
285 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
286 t = Context.UnsignedLongLongTy;
287 }
288 }
289
Chris Lattner5d661452007-08-26 03:42:43 +0000290 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000291 }
Chris Lattner5d661452007-08-26 03:42:43 +0000292
293 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
294 if (Literal.isImaginary)
295 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
296
297 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000298}
299
Steve Narofff69936d2007-09-16 03:34:24 +0000300Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 ExprTy *Val) {
302 Expr *e = (Expr *)Val;
Steve Narofff69936d2007-09-16 03:34:24 +0000303 assert((e != 0) && "ActOnParenExpr() missing expr");
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 return new ParenExpr(L, R, e);
305}
306
307/// The UsualUnaryConversions() function is *not* called by this routine.
308/// See C99 6.3.2.1p[2-4] for more details.
309QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
310 SourceLocation OpLoc, bool isSizeof) {
311 // C99 6.5.3.4p1:
312 if (isa<FunctionType>(exprType) && isSizeof)
313 // alignof(function) is allowed.
314 Diag(OpLoc, diag::ext_sizeof_function_type);
315 else if (exprType->isVoidType())
316 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
317 else if (exprType->isIncompleteType()) {
318 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
319 diag::err_alignof_incomplete_type,
320 exprType.getAsString());
321 return QualType(); // error
322 }
323 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
324 return Context.getSizeType();
325}
326
327Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000328ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 SourceLocation LPLoc, TypeTy *Ty,
330 SourceLocation RPLoc) {
331 // If error parsing type, ignore.
332 if (Ty == 0) return true;
333
334 // Verify that this is a valid expression.
335 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
336
337 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
338
339 if (resultType.isNull())
340 return true;
341 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
342}
343
Chris Lattner5d794252007-08-24 21:41:10 +0000344QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000345 DefaultFunctionArrayConversion(V);
346
Chris Lattnercc26ed72007-08-26 05:39:26 +0000347 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000348 if (const ComplexType *CT = V->getType()->getAsComplexType())
349 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000350
351 // Otherwise they pass through real integer and floating point types here.
352 if (V->getType()->isArithmeticType())
353 return V->getType();
354
355 // Reject anything else.
356 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
357 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000358}
359
360
Reid Spencer5f016e22007-07-11 17:01:13 +0000361
Steve Narofff69936d2007-09-16 03:34:24 +0000362Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 tok::TokenKind Kind,
364 ExprTy *Input) {
365 UnaryOperator::Opcode Opc;
366 switch (Kind) {
367 default: assert(0 && "Unknown unary op!");
368 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
369 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
370 }
371 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
372 if (result.isNull())
373 return true;
374 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
375}
376
377Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000378ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000380 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000381
382 // Perform default conversions.
383 DefaultFunctionArrayConversion(LHSExp);
384 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000385
Chris Lattner12d9ff62007-07-16 00:14:47 +0000386 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000387
Reid Spencer5f016e22007-07-11 17:01:13 +0000388 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000389 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000390 // in the subscript position. As a result, we need to derive the array base
391 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000392 Expr *BaseExpr, *IndexExpr;
393 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000394 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000395 BaseExpr = LHSExp;
396 IndexExpr = RHSExp;
397 // FIXME: need to deal with const...
398 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000399 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000400 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000401 BaseExpr = RHSExp;
402 IndexExpr = LHSExp;
403 // FIXME: need to deal with const...
404 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000405 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
406 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000407 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000408
409 // Component access limited to variables (reject vec4.rg[1]).
410 if (!isa<DeclRefExpr>(BaseExpr))
411 return Diag(LLoc, diag::err_ocuvector_component_access,
412 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000413 // FIXME: need to deal with const...
414 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000416 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
417 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000418 }
419 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000420 if (!IndexExpr->getType()->isIntegerType())
421 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
422 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000423
Chris Lattner12d9ff62007-07-16 00:14:47 +0000424 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
425 // the following check catches trying to index a pointer to a function (e.g.
426 // void (*)(int)). Functions are not objects in C99.
427 if (!ResultType->isObjectType())
428 return Diag(BaseExpr->getLocStart(),
429 diag::err_typecheck_subscript_not_object,
430 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
431
432 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000433}
434
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000435QualType Sema::
436CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
437 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnerc8629632007-07-31 19:29:30 +0000438 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000439
440 // The vector accessor can't exceed the number of elements.
441 const char *compStr = CompName.getName();
442 if (strlen(compStr) > vecType->getNumElements()) {
443 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
444 baseType.getAsString(), SourceRange(CompLoc));
445 return QualType();
446 }
447 // The component names must come from the same set.
Chris Lattner88dca042007-08-02 22:33:49 +0000448 if (vecType->getPointAccessorIdx(*compStr) != -1) {
449 do
450 compStr++;
451 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
452 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
453 do
454 compStr++;
455 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
456 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
457 do
458 compStr++;
459 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
460 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000461
462 if (*compStr) {
463 // We didn't get to the end of the string. This means the component names
464 // didn't come from the same set *or* we encountered an illegal name.
465 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
466 std::string(compStr,compStr+1), SourceRange(CompLoc));
467 return QualType();
468 }
469 // Each component accessor can't exceed the vector type.
470 compStr = CompName.getName();
471 while (*compStr) {
472 if (vecType->isAccessorWithinNumElements(*compStr))
473 compStr++;
474 else
475 break;
476 }
477 if (*compStr) {
478 // We didn't get to the end of the string. This means a component accessor
479 // exceeds the number of elements in the vector.
480 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
481 baseType.getAsString(), SourceRange(CompLoc));
482 return QualType();
483 }
484 // The component accessor looks fine - now we need to compute the actual type.
485 // The vector type is implied by the component accessor. For example,
486 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
487 unsigned CompSize = strlen(CompName.getName());
488 if (CompSize == 1)
489 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000490
491 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
492 // Now look up the TypeDefDecl from the vector type. Without this,
493 // diagostics look bad. We want OCU vector types to appear built-in.
494 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
495 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
496 return Context.getTypedefType(OCUVectorDecls[i]);
497 }
498 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000499}
500
Reid Spencer5f016e22007-07-11 17:01:13 +0000501Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000502ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000503 tok::TokenKind OpKind, SourceLocation MemberLoc,
504 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000505 Expr *BaseExpr = static_cast<Expr *>(Base);
506 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +0000507
508 // Perform default conversions.
509 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000510
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000511 QualType BaseType = BaseExpr->getType();
512 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000513
Reid Spencer5f016e22007-07-11 17:01:13 +0000514 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000515 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000516 BaseType = PT->getPointeeType();
517 else
518 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
519 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000521 // The base type is either a record or an OCUVectorType.
Chris Lattnerc8629632007-07-31 19:29:30 +0000522 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000523 RecordDecl *RDecl = RTy->getDecl();
524 if (RTy->isIncompleteType())
525 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
526 BaseExpr->getSourceRange());
527 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000528 FieldDecl *MemberDecl = RDecl->getMember(&Member);
529 if (!MemberDecl)
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000530 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
531 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000532 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
533 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff608e0ee2007-08-03 22:40:33 +0000534 // Component access limited to variables (reject vec4.rg.g).
535 if (!isa<DeclRefExpr>(BaseExpr))
536 return Diag(OpLoc, diag::err_ocuvector_component_access,
537 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000538 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
539 if (ret.isNull())
540 return true;
Chris Lattner6481a572007-08-03 17:31:20 +0000541 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000542 } else if (BaseType->isObjcInterfaceType()) {
543 ObjcInterfaceDecl *IFace;
544 if (isa<ObjcInterfaceType>(BaseType.getCanonicalType()))
545 IFace = dyn_cast<ObjcInterfaceType>(BaseType)->getDecl();
546 else
Fariborz Jahanian06cef252007-12-13 20:47:42 +0000547 IFace = dyn_cast<ObjcQualifiedInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000548 ObjcInterfaceDecl *clsDeclared;
549 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
550 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
551 OpKind==tok::arrow);
552 }
553 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
554 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000555}
556
Steve Narofff69936d2007-09-16 03:34:24 +0000557/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +0000558/// This provides the location of the left/right parens and a list of comma
559/// locations.
560Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000561ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +0000562 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +0000563 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000564 Expr *Fn = static_cast<Expr *>(fn);
565 Expr **Args = reinterpret_cast<Expr**>(args);
566 assert(Fn && "no function call expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000567
Chris Lattner925e60d2007-12-28 05:29:59 +0000568 // Make the call expr early, before semantic checks. This guarantees cleanup
569 // of arguments and function on error.
570 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
571 Context.BoolTy, RParenLoc));
572
573 // Promote the function operand.
574 TheCall->setCallee(UsualUnaryConversions(Fn));
575
Reid Spencer5f016e22007-07-11 17:01:13 +0000576 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
577 // type pointer to function".
Chris Lattner925e60d2007-12-28 05:29:59 +0000578 const PointerType *PT = Fn->getType()->getAsPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000579 if (PT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000580 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
581 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner925e60d2007-12-28 05:29:59 +0000582 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
583 if (FuncT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000584 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
585 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner925e60d2007-12-28 05:29:59 +0000586
587 // We know the result type of the call, set it.
588 TheCall->setType(FuncT->getResultType());
Reid Spencer5f016e22007-07-11 17:01:13 +0000589
Chris Lattner925e60d2007-12-28 05:29:59 +0000590 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
592 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +0000593 unsigned NumArgsInProto = Proto->getNumArgs();
594 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000595
Chris Lattner925e60d2007-12-28 05:29:59 +0000596 // If too few arguments are available, don't make the call.
597 if (NumArgs < NumArgsInProto)
598 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
599 Fn->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000600
Chris Lattner925e60d2007-12-28 05:29:59 +0000601 // If too many are passed and not variadic, error on the extras and drop
602 // them.
603 if (NumArgs > NumArgsInProto) {
604 if (!Proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +0000605 Diag(Args[NumArgsInProto]->getLocStart(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000606 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +0000607 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner925e60d2007-12-28 05:29:59 +0000608 Args[NumArgs-1]->getLocEnd()));
609 // This deletes the extra arguments.
610 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +0000611 }
612 NumArgsToCheck = NumArgsInProto;
613 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000614
Reid Spencer5f016e22007-07-11 17:01:13 +0000615 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +0000616 for (unsigned i = 0; i != NumArgsToCheck; i++) {
617 Expr *Arg = Args[i];
618 QualType LHSType = Proto->getArgType(i);
619 QualType RHSType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +0000620
Steve Naroff82c7e6d2007-07-25 20:45:33 +0000621 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattner925e60d2007-12-28 05:29:59 +0000622 if (const ArrayType *AT = LHSType->getAsArrayType())
623 LHSType = Context.getPointerType(AT->getElementType());
624 else if (LHSType->isFunctionType())
625 LHSType = Context.getPointerType(LHSType);
Steve Naroff700204c2007-07-24 21:46:40 +0000626
Chris Lattner925e60d2007-12-28 05:29:59 +0000627 // Compute implicit casts from the operand to the formal argument type.
628 AssignmentCheckResult Result =
629 CheckSingleAssignmentConstraints(LHSType, Arg);
630 TheCall->setArg(i, Arg);
631
632 // Decode the result (notice that AST's are still created for extensions).
633 SourceLocation Loc = Arg->getLocStart();
634 switch (Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000635 case Compatible:
636 break;
637 case PointerFromInt:
Chris Lattner925e60d2007-12-28 05:29:59 +0000638 Diag(Loc, diag::ext_typecheck_passing_pointer_int,
639 LHSType.getAsString(), RHSType.getAsString(),
640 Fn->getSourceRange(), Arg->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000641 break;
642 case IntFromPointer:
Chris Lattner925e60d2007-12-28 05:29:59 +0000643 Diag(Loc, diag::ext_typecheck_passing_pointer_int,
644 LHSType.getAsString(), RHSType.getAsString(),
645 Fn->getSourceRange(), Arg->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000646 break;
647 case IncompatiblePointer:
Chris Lattner925e60d2007-12-28 05:29:59 +0000648 Diag(Loc, diag::ext_typecheck_passing_incompatible_pointer,
649 RHSType.getAsString(), LHSType.getAsString(),
650 Fn->getSourceRange(), Arg->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000651 break;
652 case CompatiblePointerDiscardsQualifiers:
Chris Lattner925e60d2007-12-28 05:29:59 +0000653 Diag(Loc, diag::ext_typecheck_passing_discards_qualifiers,
654 RHSType.getAsString(), LHSType.getAsString(),
655 Fn->getSourceRange(), Arg->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000656 break;
657 case Incompatible:
Chris Lattner925e60d2007-12-28 05:29:59 +0000658 return Diag(Loc, diag::err_typecheck_passing_incompatible,
659 RHSType.getAsString(), LHSType.getAsString(),
660 Fn->getSourceRange(), Arg->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000661 }
662 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000663
664 // If this is a variadic call, handle args passed through "...".
665 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +0000666 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-12-28 05:29:59 +0000667 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
668 Expr *Arg = Args[i];
669 DefaultArgumentPromotion(Arg);
670 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +0000671 }
Steve Naroffb291ab62007-08-28 23:30:39 +0000672 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000673 } else {
674 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
675
Steve Naroffb291ab62007-08-28 23:30:39 +0000676 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +0000677 for (unsigned i = 0; i != NumArgs; i++) {
678 Expr *Arg = Args[i];
679 DefaultArgumentPromotion(Arg);
680 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +0000681 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000682 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000683
Chris Lattner59907c42007-08-10 20:18:51 +0000684 // Do special checking on direct calls to functions.
685 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
686 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
687 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner925e60d2007-12-28 05:29:59 +0000688 if (CheckFunctionCall(FDecl, TheCall.get()))
Anders Carlsson71993dd2007-08-17 05:31:46 +0000689 return true;
Chris Lattner59907c42007-08-10 20:18:51 +0000690
Chris Lattner925e60d2007-12-28 05:29:59 +0000691 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +0000692}
693
694Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000695ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +0000696 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +0000697 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +0000698 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +0000699 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +0000700 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +0000701 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +0000702
Steve Naroff2fdc3742007-12-10 22:44:33 +0000703 // FIXME: add more semantic analysis (C99 6.5.2.5).
704 if (CheckInitializer(literalExpr, literalType, false))
705 return 0;
Anders Carlssond35c8322007-12-05 07:24:19 +0000706
Steve Naroffaff1edd2007-07-19 21:32:11 +0000707 return new CompoundLiteralExpr(literalType, literalExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000708}
709
710Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000711ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000712 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +0000713 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000714
Steve Naroff08d92e42007-09-15 18:49:24 +0000715 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +0000716 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000717
Steve Naroff38374b02007-09-02 20:30:18 +0000718 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
719 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
720 return e;
Steve Naroff4aa88f82007-07-19 01:06:55 +0000721}
722
Chris Lattnerfe23e212007-12-20 00:44:32 +0000723bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +0000724 assert(VectorTy->isVectorType() && "Not a vector type!");
725
726 if (Ty->isVectorType() || Ty->isIntegerType()) {
727 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
728 Context.getTypeSize(Ty, SourceLocation()))
729 return Diag(R.getBegin(),
730 Ty->isVectorType() ?
731 diag::err_invalid_conversion_between_vectors :
732 diag::err_invalid_conversion_between_vector_and_integer,
733 VectorTy.getAsString().c_str(),
734 Ty.getAsString().c_str(), R);
735 } else
736 return Diag(R.getBegin(),
737 diag::err_invalid_conversion_between_vector_and_scalar,
738 VectorTy.getAsString().c_str(),
739 Ty.getAsString().c_str(), R);
740
741 return false;
742}
743
Steve Naroff4aa88f82007-07-19 01:06:55 +0000744Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000745ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +0000747 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +0000748
749 Expr *castExpr = static_cast<Expr*>(Op);
750 QualType castType = QualType::getFromOpaquePtr(Ty);
751
Steve Naroff711602b2007-08-31 00:32:44 +0000752 UsualUnaryConversions(castExpr);
753
Chris Lattner75af4802007-07-18 16:00:06 +0000754 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
755 // type needs to be scalar.
Chris Lattner3da2db42007-10-29 04:26:44 +0000756 if (!castType->isVoidType()) { // Cast to void allows any expr type.
757 if (!castType->isScalarType())
758 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
759 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Anders Carlssona64db8f2007-11-27 05:51:55 +0000760 if (!castExpr->getType()->isScalarType())
Chris Lattner3da2db42007-10-29 04:26:44 +0000761 return Diag(castExpr->getLocStart(),
762 diag::err_typecheck_expect_scalar_operand,
763 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssona64db8f2007-11-27 05:51:55 +0000764
765 if (castExpr->getType()->isVectorType()) {
766 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
767 castExpr->getType(), castType))
768 return true;
769 } else if (castType->isVectorType()) {
770 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
771 castType, castExpr->getType()))
772 return true;
Chris Lattner3da2db42007-10-29 04:26:44 +0000773 }
Steve Naroff16beff82007-07-16 23:25:18 +0000774 }
775 return new CastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000776}
777
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000778// promoteExprToType - a helper function to ensure we create exactly one
779// ImplicitCastExpr.
780static void promoteExprToType(Expr *&expr, QualType type) {
781 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
782 impCast->setType(type);
783 else
784 expr = new ImplicitCastExpr(type, expr);
785 return;
786}
787
Chris Lattnera21ddb32007-11-26 01:40:58 +0000788/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
789/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +0000790inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +0000791 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000792 UsualUnaryConversions(cond);
793 UsualUnaryConversions(lex);
794 UsualUnaryConversions(rex);
795 QualType condT = cond->getType();
796 QualType lexT = lex->getType();
797 QualType rexT = rex->getType();
798
Reid Spencer5f016e22007-07-11 17:01:13 +0000799 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +0000800 if (!condT->isScalarType()) { // C99 6.5.15p2
801 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
802 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +0000803 return QualType();
804 }
805 // now check the two expressions.
Steve Naroffa4332e22007-07-17 00:58:39 +0000806 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
807 UsualArithmeticConversions(lex, rex);
808 return lex->getType();
809 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000810 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
811 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
Chris Lattnera21ddb32007-11-26 01:40:58 +0000812 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000813 return lexT;
814
Reid Spencer5f016e22007-07-11 17:01:13 +0000815 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000816 lexT.getAsString(), rexT.getAsString(),
817 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000818 return QualType();
819 }
820 }
Chris Lattner590b6642007-07-15 23:26:56 +0000821 // C99 6.5.15p3
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000822 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
823 promoteExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff49b45262007-07-13 16:58:59 +0000824 return lexT;
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000825 }
826 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
827 promoteExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff49b45262007-07-13 16:58:59 +0000828 return rexT;
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000829 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000830 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
831 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
832 // get the "pointed to" types
833 QualType lhptee = LHSPT->getPointeeType();
834 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000835
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000836 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
837 if (lhptee->isVoidType() &&
838 (rhptee->isObjectType() || rhptee->isIncompleteType()))
839 return lexT;
840 if (rhptee->isVoidType() &&
841 (lhptee->isObjectType() || lhptee->isIncompleteType()))
842 return rexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000843
Steve Naroffec0550f2007-10-15 20:41:53 +0000844 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
845 rhptee.getUnqualifiedType())) {
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000846 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
847 lexT.getAsString(), rexT.getAsString(),
848 lex->getSourceRange(), rex->getSourceRange());
849 return lexT; // FIXME: this is an _ext - is this return o.k?
850 }
851 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000852 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
853 // differently qualified versions of compatible types, the result type is
854 // a pointer to an appropriately qualified version of the *composite*
855 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000856 return lexT; // FIXME: Need to return the composite type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000857 }
858 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000859
Steve Naroff49b45262007-07-13 16:58:59 +0000860 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
861 return lexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000862
863 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000864 lexT.getAsString(), rexT.getAsString(),
865 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000866 return QualType();
867}
868
Steve Narofff69936d2007-09-16 03:34:24 +0000869/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +0000870/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +0000871Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 SourceLocation ColonLoc,
873 ExprTy *Cond, ExprTy *LHS,
874 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +0000875 Expr *CondExpr = (Expr *) Cond;
876 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +0000877
878 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
879 // was the condition.
880 bool isLHSNull = LHSExpr == 0;
881 if (isLHSNull)
882 LHSExpr = CondExpr;
883
Chris Lattner26824902007-07-16 21:39:03 +0000884 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
885 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000886 if (result.isNull())
887 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +0000888 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
889 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000890}
891
Steve Naroffb291ab62007-08-28 23:30:39 +0000892/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
893/// do not have a prototype. Integer promotions are performed on each
894/// argument, and arguments that have type float are promoted to double.
Chris Lattner925e60d2007-12-28 05:29:59 +0000895void Sema::DefaultArgumentPromotion(Expr *&Expr) {
896 QualType Ty = Expr->getType();
897 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffb291ab62007-08-28 23:30:39 +0000898
Chris Lattner925e60d2007-12-28 05:29:59 +0000899 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
900 promoteExprToType(Expr, Context.IntTy);
901 if (Ty == Context.FloatTy)
902 promoteExprToType(Expr, Context.DoubleTy);
Steve Naroffb291ab62007-08-28 23:30:39 +0000903}
904
Steve Narofffa2eaab2007-07-15 02:02:06 +0000905/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000906void Sema::DefaultFunctionArrayConversion(Expr *&e) {
Steve Narofffa2eaab2007-07-15 02:02:06 +0000907 QualType t = e->getType();
Steve Naroff90045e82007-07-13 23:32:42 +0000908 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
Bill Wendling08ad47c2007-07-17 03:52:31 +0000909
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000910 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000911 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
912 t = e->getType();
913 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000914 if (t->isFunctionType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000915 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnerc8629632007-07-31 19:29:30 +0000916 else if (const ArrayType *ary = t->getAsArrayType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000917 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000918}
919
920/// UsualUnaryConversion - Performs various conversions that are common to most
921/// operators (C99 6.3). The conversions of array and function types are
922/// sometimes surpressed. For example, the array->pointer conversion doesn't
923/// apply if the array is an argument to the sizeof or address (&) operators.
924/// In these instances, this routine should *not* be called.
Chris Lattner925e60d2007-12-28 05:29:59 +0000925Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
926 QualType Ty = Expr->getType();
927 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000928
Chris Lattner925e60d2007-12-28 05:29:59 +0000929 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
930 promoteExprToType(Expr, Ref->getReferenceeType()); // C++ [expr]
931 Ty = Expr->getType();
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000932 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000933 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
934 promoteExprToType(Expr, Context.IntTy);
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000935 else
Chris Lattner925e60d2007-12-28 05:29:59 +0000936 DefaultFunctionArrayConversion(Expr);
937
938 return Expr;
Reid Spencer5f016e22007-07-11 17:01:13 +0000939}
940
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000941/// UsualArithmeticConversions - Performs various conversions that are common to
Reid Spencer5f016e22007-07-11 17:01:13 +0000942/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
943/// routine returns the first non-arithmetic type found. The client is
944/// responsible for emitting appropriate error diagnostics.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000945QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
946 bool isCompAssign) {
Steve Naroff8702a0f2007-08-25 19:54:59 +0000947 if (!isCompAssign) {
948 UsualUnaryConversions(lhsExpr);
949 UsualUnaryConversions(rhsExpr);
950 }
Steve Naroff3187e202007-10-18 18:55:53 +0000951 // For conversion purposes, we ignore any qualifiers.
952 // For example, "const float" and "float" are equivalent.
Steve Narofff68a63f2007-11-10 19:45:54 +0000953 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
954 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000955
956 // If both types are identical, no conversion is needed.
Steve Naroff3187e202007-10-18 18:55:53 +0000957 if (lhs == rhs)
958 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000959
960 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
961 // The caller can deal with this (e.g. pointer + int).
Steve Naroffa4332e22007-07-17 00:58:39 +0000962 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000963 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000964
965 // At this point, we have two different arithmetic types.
966
967 // Handle complex types first (C99 6.3.1.8p1).
968 if (lhs->isComplexType() || rhs->isComplexType()) {
969 // if we have an integer operand, the result is the complex type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000970 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000971 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
972 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000973 }
974 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000975 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
976 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000977 }
Steve Narofff1448a02007-08-27 01:27:54 +0000978 // This handles complex/complex, complex/float, or float/complex.
979 // When both operands are complex, the shorter operand is converted to the
980 // type of the longer, and that is the type of the result. This corresponds
981 // to what is done when combining two real floating-point operands.
982 // The fun begins when size promotion occur across type domains.
983 // From H&S 6.3.4: When one operand is complex and the other is a real
984 // floating-point type, the less precise type is converted, within it's
985 // real or complex domain, to the precision of the other type. For example,
986 // when combining a "long double" with a "double _Complex", the
987 // "double _Complex" is promoted to "long double _Complex".
Steve Narofffb0d4962007-08-27 15:30:22 +0000988 int result = Context.compareFloatingType(lhs, rhs);
989
990 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff55fe4552007-08-27 21:32:55 +0000991 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
992 if (!isCompAssign)
993 promoteExprToType(rhsExpr, rhs);
994 } else if (result < 0) { // The right side is bigger, convert lhs.
995 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
996 if (!isCompAssign)
997 promoteExprToType(lhsExpr, lhs);
998 }
999 // At this point, lhs and rhs have the same rank/size. Now, make sure the
1000 // domains match. This is a requirement for our implementation, C99
1001 // does not require this promotion.
1002 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1003 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff29960362007-08-27 21:43:43 +00001004 if (!isCompAssign)
1005 promoteExprToType(lhsExpr, rhs);
1006 return rhs;
Steve Naroff55fe4552007-08-27 21:32:55 +00001007 } else { // handle "_Complex double, double".
Steve Naroff29960362007-08-27 21:43:43 +00001008 if (!isCompAssign)
1009 promoteExprToType(rhsExpr, lhs);
1010 return lhs;
Steve Naroff55fe4552007-08-27 21:32:55 +00001011 }
Steve Naroffa4332e22007-07-17 00:58:39 +00001012 }
Steve Naroff29960362007-08-27 21:43:43 +00001013 return lhs; // The domain/size match exactly.
Reid Spencer5f016e22007-07-11 17:01:13 +00001014 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001015 // Now handle "real" floating types (i.e. float, double, long double).
1016 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1017 // if we have an integer operand, the result is the real floating type.
Steve Naroffa4332e22007-07-17 00:58:39 +00001018 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001019 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1020 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001021 }
1022 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001023 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
1024 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001025 }
Steve Narofffa2eaab2007-07-15 02:02:06 +00001026 // We have two real floating types, float/complex combos were handled above.
1027 // Convert the smaller operand to the bigger result.
Steve Narofffb0d4962007-08-27 15:30:22 +00001028 int result = Context.compareFloatingType(lhs, rhs);
1029
1030 if (result > 0) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001031 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1032 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001033 }
Steve Narofffb0d4962007-08-27 15:30:22 +00001034 if (result < 0) { // convert the lhs
1035 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1036 return rhs;
1037 }
1038 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Reid Spencer5f016e22007-07-11 17:01:13 +00001039 }
Steve Narofffa2eaab2007-07-15 02:02:06 +00001040 // Finally, we have two differing integer types.
Steve Naroffa4332e22007-07-17 00:58:39 +00001041 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001042 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1043 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001044 }
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001045 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1046 return rhs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001047}
1048
1049// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1050// being closely modeled after the C99 spec:-). The odd characteristic of this
1051// routine is it effectively iqnores the qualifiers on the top level pointee.
1052// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1053// FIXME: add a couple examples in this comment.
1054Sema::AssignmentCheckResult
1055Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1056 QualType lhptee, rhptee;
1057
1058 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001059 lhptee = lhsType->getAsPointerType()->getPointeeType();
1060 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001061
1062 // make sure we operate on the canonical type
1063 lhptee = lhptee.getCanonicalType();
1064 rhptee = rhptee.getCanonicalType();
1065
1066 AssignmentCheckResult r = Compatible;
1067
1068 // C99 6.5.16.1p1: This following citation is common to constraints
1069 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1070 // qualifiers of the type *pointed to* by the right;
1071 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1072 rhptee.getQualifiers())
1073 r = CompatiblePointerDiscardsQualifiers;
1074
1075 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1076 // incomplete type and the other is a pointer to a qualified or unqualified
1077 // version of void...
1078 if (lhptee.getUnqualifiedType()->isVoidType() &&
1079 (rhptee->isObjectType() || rhptee->isIncompleteType()))
1080 ;
1081 else if (rhptee.getUnqualifiedType()->isVoidType() &&
1082 (lhptee->isObjectType() || lhptee->isIncompleteType()))
1083 ;
1084 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1085 // unqualified versions of compatible types, ...
Steve Naroffec0550f2007-10-15 20:41:53 +00001086 else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1087 rhptee.getUnqualifiedType()))
Reid Spencer5f016e22007-07-11 17:01:13 +00001088 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1089 return r;
1090}
1091
1092/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1093/// has code to accommodate several GCC extensions when type checking
1094/// pointers. Here are some objectionable examples that GCC considers warnings:
1095///
1096/// int a, *pint;
1097/// short *pshort;
1098/// struct foo *pfoo;
1099///
1100/// pint = pshort; // warning: assignment from incompatible pointer type
1101/// a = pint; // warning: assignment makes integer from pointer without a cast
1102/// pint = a; // warning: assignment makes pointer from integer without a cast
1103/// pint = pfoo; // warning: assignment from incompatible pointer type
1104///
1105/// As a result, the code for dealing with pointers is more complex than the
1106/// C99 spec dictates.
1107/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1108///
1109Sema::AssignmentCheckResult
1110Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001111
1112
Steve Naroff8eabdff2007-11-13 00:31:42 +00001113 if (lhsType.getCanonicalType().getUnqualifiedType() ==
1114 rhsType.getCanonicalType().getUnqualifiedType())
Chris Lattner84d35ce2007-10-29 05:15:40 +00001115 return Compatible; // common case, fast path...
Steve Naroff700204c2007-07-24 21:46:40 +00001116
Anders Carlsson793680e2007-10-12 23:56:29 +00001117 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroffec0550f2007-10-15 20:41:53 +00001118 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001119 return Compatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001120 }
1121 else if (lhsType->isObjcQualifiedIdType()
1122 || rhsType->isObjcQualifiedIdType()) {
1123 if (Context.ObjcQualifiedIdTypesAreCompatible(lhsType, rhsType))
1124 return Compatible;
1125 }
1126 else if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001127 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Anders Carlsson695dbb62007-11-30 04:21:22 +00001128 if (!getLangOptions().LaxVectorConversions) {
1129 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1130 return Incompatible;
1131 } else {
Nate Begeman4288c432007-12-30 01:45:55 +00001132 // For OCUVector, allow vector splats; float -> <n x float>
1133 if (const OCUVectorType *LV = lhsType->getAsOCUVectorType()) {
1134 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1135 return Compatible;
1136 }
Anders Carlsson695dbb62007-11-30 04:21:22 +00001137 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman4288c432007-12-30 01:45:55 +00001138 // If LHS and RHS are both integer or both floating point types, and
1139 // the total vector length is the same, allow the conversion. This is
1140 // a bitcast; no bits are changed but the result type is different.
Anders Carlsson695dbb62007-11-30 04:21:22 +00001141 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1142 (lhsType->isRealFloatingType() &&
1143 rhsType->isRealFloatingType())) {
1144 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1145 Context.getTypeSize(rhsType, SourceLocation()))
1146 return Compatible;
1147 }
1148 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001149 return Incompatible;
Anders Carlsson695dbb62007-11-30 04:21:22 +00001150 }
1151 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001152 return Compatible;
1153 } else if (lhsType->isPointerType()) {
1154 if (rhsType->isIntegerType())
1155 return PointerFromInt;
1156
1157 if (rhsType->isPointerType())
1158 return CheckPointerTypesForAssignment(lhsType, rhsType);
1159 } else if (rhsType->isPointerType()) {
1160 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1161 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1162 return IntFromPointer;
1163
1164 if (lhsType->isPointerType())
1165 return CheckPointerTypesForAssignment(lhsType, rhsType);
1166 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroffec0550f2007-10-15 20:41:53 +00001167 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001168 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001169 }
1170 return Incompatible;
1171}
1172
Steve Naroff90045e82007-07-13 23:32:42 +00001173Sema::AssignmentCheckResult
1174Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroff529a4ad2007-11-27 17:58:44 +00001175 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1176 // a null pointer constant.
1177 if (lhsType->isPointerType() && rExpr->isNullPointerConstant(Context)) {
1178 promoteExprToType(rExpr, lhsType);
1179 return Compatible;
1180 }
Chris Lattner943140e2007-10-16 02:55:40 +00001181 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001182 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001183 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001184 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001185 //
1186 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1187 // are better understood.
1188 if (!lhsType->isReferenceType())
1189 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001190
1191 Sema::AssignmentCheckResult result;
Steve Naroff90045e82007-07-13 23:32:42 +00001192
Steve Narofff1120de2007-08-24 22:33:52 +00001193 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1194
1195 // C99 6.5.16.1p2: The value of the right operand is converted to the
1196 // type of the assignment expression.
1197 if (rExpr->getType() != lhsType)
1198 promoteExprToType(rExpr, lhsType);
1199 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001200}
1201
1202Sema::AssignmentCheckResult
1203Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1204 return CheckAssignmentConstraints(lhsType, rhsType);
1205}
1206
Chris Lattnerca5eede2007-12-12 05:47:28 +00001207QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 Diag(loc, diag::err_typecheck_invalid_operands,
1209 lex->getType().getAsString(), rex->getType().getAsString(),
1210 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerca5eede2007-12-12 05:47:28 +00001211 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001212}
1213
Steve Naroff49b45262007-07-13 16:58:59 +00001214inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1215 Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001216 QualType lhsType = lex->getType(), rhsType = rex->getType();
1217
1218 // make sure the vector types are identical.
1219 if (lhsType == rhsType)
1220 return lhsType;
1221 // You cannot convert between vector values of different size.
1222 Diag(loc, diag::err_typecheck_vector_not_convertable,
1223 lex->getType().getAsString(), rex->getType().getAsString(),
1224 lex->getSourceRange(), rex->getSourceRange());
1225 return QualType();
1226}
1227
1228inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001229 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001230{
Steve Naroff90045e82007-07-13 23:32:42 +00001231 QualType lhsType = lex->getType(), rhsType = rex->getType();
1232
1233 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001235
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001236 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001237
Steve Naroffa4332e22007-07-17 00:58:39 +00001238 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001239 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001240 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001241}
1242
1243inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001244 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001245{
Steve Naroff90045e82007-07-13 23:32:42 +00001246 QualType lhsType = lex->getType(), rhsType = rex->getType();
1247
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001248 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001249
Steve Naroffa4332e22007-07-17 00:58:39 +00001250 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001251 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001252 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001253}
1254
1255inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001256 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001257{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001258 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001259 return CheckVectorOperands(loc, lex, rex);
1260
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001261 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Steve Naroff3e5e5562007-07-16 22:23:01 +00001262
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001264 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001265 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001266
Steve Naroffa4332e22007-07-17 00:58:39 +00001267 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1268 return lex->getType();
1269 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1270 return rex->getType();
Chris Lattnerca5eede2007-12-12 05:47:28 +00001271 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001272}
1273
1274inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001275 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001276{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001277 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001278 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001279
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001280 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001281
Chris Lattner6e4ab612007-12-09 21:53:25 +00001282 // Enforce type constraints: C99 6.5.6p3.
1283
1284 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001285 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001286 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001287
1288 // Either ptr - int or ptr - ptr.
1289 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1290 // The LHS must be an object type, not incomplete, function, etc.
1291 if (!LHSPTy->getPointeeType()->isObjectType()) {
1292 // Handle the GNU void* extension.
1293 if (LHSPTy->getPointeeType()->isVoidType()) {
1294 Diag(loc, diag::ext_gnu_void_ptr,
1295 lex->getSourceRange(), rex->getSourceRange());
1296 } else {
1297 Diag(loc, diag::err_typecheck_sub_ptr_object,
1298 lex->getType().getAsString(), lex->getSourceRange());
1299 return QualType();
1300 }
1301 }
1302
1303 // The result type of a pointer-int computation is the pointer type.
1304 if (rex->getType()->isIntegerType())
1305 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001306
Chris Lattner6e4ab612007-12-09 21:53:25 +00001307 // Handle pointer-pointer subtractions.
1308 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1309 // RHS must be an object type, unless void (GNU).
1310 if (!RHSPTy->getPointeeType()->isObjectType()) {
1311 // Handle the GNU void* extension.
1312 if (RHSPTy->getPointeeType()->isVoidType()) {
1313 if (!LHSPTy->getPointeeType()->isVoidType())
1314 Diag(loc, diag::ext_gnu_void_ptr,
1315 lex->getSourceRange(), rex->getSourceRange());
1316 } else {
1317 Diag(loc, diag::err_typecheck_sub_ptr_object,
1318 rex->getType().getAsString(), rex->getSourceRange());
1319 return QualType();
1320 }
1321 }
1322
1323 // Pointee types must be compatible.
1324 if (!Context.typesAreCompatible(LHSPTy->getPointeeType(),
1325 RHSPTy->getPointeeType())) {
1326 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1327 lex->getType().getAsString(), rex->getType().getAsString(),
1328 lex->getSourceRange(), rex->getSourceRange());
1329 return QualType();
1330 }
1331
1332 return Context.getPointerDiffType();
1333 }
1334 }
1335
Chris Lattnerca5eede2007-12-12 05:47:28 +00001336 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001337}
1338
1339inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Chris Lattnerca5eede2007-12-12 05:47:28 +00001340 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1341 // C99 6.5.7p2: Each of the operands shall have integer type.
1342 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1343 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001344
Chris Lattnerca5eede2007-12-12 05:47:28 +00001345 // Shifts don't perform usual arithmetic conversions, they just do integer
1346 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00001347 if (!isCompAssign)
1348 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00001349 UsualUnaryConversions(rex);
1350
1351 // "The type of the result is that of the promoted left operand."
1352 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001353}
1354
Chris Lattnera5937dd2007-08-26 01:18:55 +00001355inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1356 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Reid Spencer5f016e22007-07-11 17:01:13 +00001357{
Chris Lattnera5937dd2007-08-26 01:18:55 +00001358 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00001359 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1360 UsualArithmeticConversions(lex, rex);
1361 else {
1362 UsualUnaryConversions(lex);
1363 UsualUnaryConversions(rex);
1364 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001365 QualType lType = lex->getType();
1366 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001367
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001368 // For non-floating point types, check for self-comparisons of the form
1369 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1370 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001371 if (!lType->isFloatingType()) {
1372 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1373 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1374 if (DRL->getDecl() == DRR->getDecl())
1375 Diag(loc, diag::warn_selfcomparison);
1376 }
1377
Chris Lattnera5937dd2007-08-26 01:18:55 +00001378 if (isRelational) {
1379 if (lType->isRealType() && rType->isRealType())
1380 return Context.IntTy;
1381 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001382 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001383 if (lType->isFloatingType()) {
1384 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001385 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00001386 }
1387
Chris Lattnera5937dd2007-08-26 01:18:55 +00001388 if (lType->isArithmeticType() && rType->isArithmeticType())
1389 return Context.IntTy;
1390 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001391
Chris Lattnerd28f8152007-08-26 01:10:14 +00001392 bool LHSIsNull = lex->isNullPointerConstant(Context);
1393 bool RHSIsNull = rex->isNullPointerConstant(Context);
1394
Chris Lattnera5937dd2007-08-26 01:18:55 +00001395 // All of the following pointer related warnings are GCC extensions, except
1396 // when handling null pointer constants. One day, we can consider making them
1397 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00001398 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff66296cb2007-11-13 14:57:38 +00001399
1400 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1401 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1402 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroffec0550f2007-10-15 20:41:53 +00001403 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1404 rType.getUnqualifiedType())) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001405 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1406 lType.getAsString(), rType.getAsString(),
1407 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001408 }
Chris Lattnerd28f8152007-08-26 01:10:14 +00001409 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001410 return Context.IntTy;
1411 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00001412 if ((lType->isObjcQualifiedIdType() || rType->isObjcQualifiedIdType())
Fariborz Jahaniand0c89c42007-12-21 00:33:59 +00001413 && Context.ObjcQualifiedIdTypesAreCompatible(lType, rType, true)) {
Fariborz Jahanian7359f042007-12-20 01:06:58 +00001414 promoteExprToType(rex, lType);
1415 return Context.IntTy;
1416 }
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001417 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001418 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001419 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1420 lType.getAsString(), rType.getAsString(),
1421 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001422 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001423 return Context.IntTy;
1424 }
1425 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001426 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001427 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1428 lType.getAsString(), rType.getAsString(),
1429 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001430 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001431 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001432 }
Chris Lattnerca5eede2007-12-12 05:47:28 +00001433 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001434}
1435
Reid Spencer5f016e22007-07-11 17:01:13 +00001436inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001437 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001438{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001439 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001440 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001441
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001442 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001443
Steve Naroffa4332e22007-07-17 00:58:39 +00001444 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001445 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001446 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001447}
1448
1449inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00001450 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001451{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001452 UsualUnaryConversions(lex);
1453 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001454
Steve Naroffa4332e22007-07-17 00:58:39 +00001455 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 return Context.IntTy;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001457 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001458}
1459
1460inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00001461 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001462{
1463 QualType lhsType = lex->getType();
1464 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1465 bool hadError = false;
1466 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1467
1468 switch (mlval) { // C99 6.5.16p2
1469 case Expr::MLV_Valid:
1470 break;
1471 case Expr::MLV_ConstQualified:
1472 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1473 hadError = true;
1474 break;
1475 case Expr::MLV_ArrayType:
1476 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1477 lhsType.getAsString(), lex->getSourceRange());
1478 return QualType();
1479 case Expr::MLV_NotObjectType:
1480 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1481 lhsType.getAsString(), lex->getSourceRange());
1482 return QualType();
1483 case Expr::MLV_InvalidExpression:
1484 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1485 lex->getSourceRange());
1486 return QualType();
1487 case Expr::MLV_IncompleteType:
1488 case Expr::MLV_IncompleteVoidType:
1489 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1490 lhsType.getAsString(), lex->getSourceRange());
1491 return QualType();
Steve Narofffec0b492007-07-30 03:29:09 +00001492 case Expr::MLV_DuplicateVectorComponents:
1493 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1494 lex->getSourceRange());
1495 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001496 }
Steve Naroff90045e82007-07-13 23:32:42 +00001497 AssignmentCheckResult result;
1498
1499 if (compoundType.isNull())
1500 result = CheckSingleAssignmentConstraints(lhsType, rex);
1501 else
1502 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001503
Reid Spencer5f016e22007-07-11 17:01:13 +00001504 // decode the result (notice that extensions still return a type).
1505 switch (result) {
1506 case Compatible:
1507 break;
1508 case Incompatible:
1509 Diag(loc, diag::err_typecheck_assign_incompatible,
1510 lhsType.getAsString(), rhsType.getAsString(),
1511 lex->getSourceRange(), rex->getSourceRange());
1512 hadError = true;
1513 break;
1514 case PointerFromInt:
Steve Naroff529a4ad2007-11-27 17:58:44 +00001515 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1516 lhsType.getAsString(), rhsType.getAsString(),
1517 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 break;
1519 case IntFromPointer:
1520 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1521 lhsType.getAsString(), rhsType.getAsString(),
1522 lex->getSourceRange(), rex->getSourceRange());
1523 break;
1524 case IncompatiblePointer:
1525 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1526 lhsType.getAsString(), rhsType.getAsString(),
1527 lex->getSourceRange(), rex->getSourceRange());
1528 break;
1529 case CompatiblePointerDiscardsQualifiers:
1530 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1531 lhsType.getAsString(), rhsType.getAsString(),
1532 lex->getSourceRange(), rex->getSourceRange());
1533 break;
1534 }
1535 // C99 6.5.16p3: The type of an assignment expression is the type of the
1536 // left operand unless the left operand has qualified type, in which case
1537 // it is the unqualified version of the type of the left operand.
1538 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1539 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001540 // C++ 5.17p1: the type of the assignment expression is that of its left
1541 // oprdu.
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 return hadError ? QualType() : lhsType.getUnqualifiedType();
1543}
1544
1545inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00001546 Expr *&lex, Expr *&rex, SourceLocation loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001547 UsualUnaryConversions(rex);
1548 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001549}
1550
Steve Naroff49b45262007-07-13 16:58:59 +00001551/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1552/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00001553QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00001554 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 assert(!resType.isNull() && "no type for increment/decrement expression");
1556
Steve Naroff084f9ed2007-08-24 17:20:07 +00001557 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00001558 if (const PointerType *pt = resType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1560 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1561 resType.getAsString(), op->getSourceRange());
1562 return QualType();
1563 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00001564 } else if (!resType->isRealType()) {
1565 if (resType->isComplexType())
1566 // C99 does not support ++/-- on complex types.
1567 Diag(OpLoc, diag::ext_integer_increment_complex,
1568 resType.getAsString(), op->getSourceRange());
1569 else {
1570 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1571 resType.getAsString(), op->getSourceRange());
1572 return QualType();
1573 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 }
Steve Naroffdd10e022007-08-23 21:37:33 +00001575 // At this point, we know we have a real, complex or pointer type.
1576 // Now make sure the operand is a modifiable lvalue.
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1578 if (mlval != Expr::MLV_Valid) {
1579 // FIXME: emit a more precise diagnostic...
1580 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1581 op->getSourceRange());
1582 return QualType();
1583 }
1584 return resType;
1585}
1586
1587/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1588/// This routine allows us to typecheck complex/recursive expressions
1589/// where the declaration is needed for type checking. Here are some
1590/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1591static Decl *getPrimaryDeclaration(Expr *e) {
1592 switch (e->getStmtClass()) {
1593 case Stmt::DeclRefExprClass:
1594 return cast<DeclRefExpr>(e)->getDecl();
1595 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00001596 // Fields cannot be declared with a 'register' storage class.
1597 // &X->f is always ok, even if X is declared register.
1598 if (cast<MemberExpr>(e)->isArrow())
1599 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1601 case Stmt::ArraySubscriptExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00001602 // &X[4] and &4[X] is invalid if X is invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +00001603 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 case Stmt::UnaryOperatorClass:
1605 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1606 case Stmt::ParenExprClass:
1607 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00001608 case Stmt::ImplicitCastExprClass:
1609 // &X[4] when X is an array, has an implicit cast from array to pointer.
1610 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 default:
1612 return 0;
1613 }
1614}
1615
1616/// CheckAddressOfOperand - The operand of & must be either a function
1617/// designator or an lvalue designating an object. If it is an lvalue, the
1618/// object cannot be declared with storage class register or be a bit field.
1619/// Note: The usual conversions are *not* applied to the operand of the &
1620/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1621QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1622 Decl *dcl = getPrimaryDeclaration(op);
1623 Expr::isLvalueResult lval = op->isLvalue();
1624
1625 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00001626 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1627 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00001628 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1629 op->getSourceRange());
1630 return QualType();
1631 }
1632 } else if (dcl) {
1633 // We have an lvalue with a decl. Make sure the decl is not declared
1634 // with the register storage-class specifier.
1635 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1636 if (vd->getStorageClass() == VarDecl::Register) {
1637 Diag(OpLoc, diag::err_typecheck_address_of_register,
1638 op->getSourceRange());
1639 return QualType();
1640 }
1641 } else
1642 assert(0 && "Unknown/unexpected decl type");
1643
1644 // FIXME: add check for bitfields!
1645 }
1646 // If the operand has type "type", the result has type "pointer to type".
1647 return Context.getPointerType(op->getType());
1648}
1649
1650QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001651 UsualUnaryConversions(op);
1652 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001653
Chris Lattnerbefee482007-07-31 16:53:04 +00001654 if (const PointerType *PT = qType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001655 QualType ptype = PT->getPointeeType();
1656 // C99 6.5.3.2p4. "if it points to an object,...".
1657 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1658 // GCC compat: special case 'void *' (treat as warning).
1659 if (ptype->isVoidType()) {
1660 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1661 qType.getAsString(), op->getSourceRange());
1662 } else {
1663 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1664 ptype.getAsString(), op->getSourceRange());
1665 return QualType();
1666 }
1667 }
1668 return ptype;
1669 }
1670 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1671 qType.getAsString(), op->getSourceRange());
1672 return QualType();
1673}
1674
1675static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1676 tok::TokenKind Kind) {
1677 BinaryOperator::Opcode Opc;
1678 switch (Kind) {
1679 default: assert(0 && "Unknown binop!");
1680 case tok::star: Opc = BinaryOperator::Mul; break;
1681 case tok::slash: Opc = BinaryOperator::Div; break;
1682 case tok::percent: Opc = BinaryOperator::Rem; break;
1683 case tok::plus: Opc = BinaryOperator::Add; break;
1684 case tok::minus: Opc = BinaryOperator::Sub; break;
1685 case tok::lessless: Opc = BinaryOperator::Shl; break;
1686 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1687 case tok::lessequal: Opc = BinaryOperator::LE; break;
1688 case tok::less: Opc = BinaryOperator::LT; break;
1689 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1690 case tok::greater: Opc = BinaryOperator::GT; break;
1691 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1692 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1693 case tok::amp: Opc = BinaryOperator::And; break;
1694 case tok::caret: Opc = BinaryOperator::Xor; break;
1695 case tok::pipe: Opc = BinaryOperator::Or; break;
1696 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1697 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1698 case tok::equal: Opc = BinaryOperator::Assign; break;
1699 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1700 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1701 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1702 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1703 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1704 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1705 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1706 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1707 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1708 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1709 case tok::comma: Opc = BinaryOperator::Comma; break;
1710 }
1711 return Opc;
1712}
1713
1714static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1715 tok::TokenKind Kind) {
1716 UnaryOperator::Opcode Opc;
1717 switch (Kind) {
1718 default: assert(0 && "Unknown unary op!");
1719 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1720 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1721 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1722 case tok::star: Opc = UnaryOperator::Deref; break;
1723 case tok::plus: Opc = UnaryOperator::Plus; break;
1724 case tok::minus: Opc = UnaryOperator::Minus; break;
1725 case tok::tilde: Opc = UnaryOperator::Not; break;
1726 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1727 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1728 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1729 case tok::kw___real: Opc = UnaryOperator::Real; break;
1730 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1731 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1732 }
1733 return Opc;
1734}
1735
1736// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001737Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00001738 ExprTy *LHS, ExprTy *RHS) {
1739 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1740 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1741
Steve Narofff69936d2007-09-16 03:34:24 +00001742 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1743 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00001744
1745 QualType ResultTy; // Result type of the binary operator.
1746 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1747
1748 switch (Opc) {
1749 default:
1750 assert(0 && "Unknown binary expr!");
1751 case BinaryOperator::Assign:
1752 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1753 break;
1754 case BinaryOperator::Mul:
1755 case BinaryOperator::Div:
1756 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1757 break;
1758 case BinaryOperator::Rem:
1759 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1760 break;
1761 case BinaryOperator::Add:
1762 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1763 break;
1764 case BinaryOperator::Sub:
1765 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1766 break;
1767 case BinaryOperator::Shl:
1768 case BinaryOperator::Shr:
1769 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1770 break;
1771 case BinaryOperator::LE:
1772 case BinaryOperator::LT:
1773 case BinaryOperator::GE:
1774 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001775 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001776 break;
1777 case BinaryOperator::EQ:
1778 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001779 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001780 break;
1781 case BinaryOperator::And:
1782 case BinaryOperator::Xor:
1783 case BinaryOperator::Or:
1784 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1785 break;
1786 case BinaryOperator::LAnd:
1787 case BinaryOperator::LOr:
1788 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1789 break;
1790 case BinaryOperator::MulAssign:
1791 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001792 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001793 if (!CompTy.isNull())
1794 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1795 break;
1796 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001797 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001798 if (!CompTy.isNull())
1799 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1800 break;
1801 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001802 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001803 if (!CompTy.isNull())
1804 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1805 break;
1806 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001807 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001808 if (!CompTy.isNull())
1809 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1810 break;
1811 case BinaryOperator::ShlAssign:
1812 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001813 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001814 if (!CompTy.isNull())
1815 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1816 break;
1817 case BinaryOperator::AndAssign:
1818 case BinaryOperator::XorAssign:
1819 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001820 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001821 if (!CompTy.isNull())
1822 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1823 break;
1824 case BinaryOperator::Comma:
1825 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1826 break;
1827 }
1828 if (ResultTy.isNull())
1829 return true;
1830 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001831 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001832 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001833 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001834}
1835
1836// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001837Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00001838 ExprTy *input) {
1839 Expr *Input = (Expr*)input;
1840 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1841 QualType resultType;
1842 switch (Opc) {
1843 default:
1844 assert(0 && "Unimplemented unary expr!");
1845 case UnaryOperator::PreInc:
1846 case UnaryOperator::PreDec:
1847 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1848 break;
1849 case UnaryOperator::AddrOf:
1850 resultType = CheckAddressOfOperand(Input, OpLoc);
1851 break;
1852 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00001853 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00001854 resultType = CheckIndirectionOperand(Input, OpLoc);
1855 break;
1856 case UnaryOperator::Plus:
1857 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001858 UsualUnaryConversions(Input);
1859 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001860 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1861 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1862 resultType.getAsString());
1863 break;
1864 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001865 UsualUnaryConversions(Input);
1866 resultType = Input->getType();
Steve Naroff084f9ed2007-08-24 17:20:07 +00001867 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1868 if (!resultType->isIntegerType()) {
1869 if (resultType->isComplexType())
1870 // C99 does not support '~' for complex conjugation.
1871 Diag(OpLoc, diag::ext_integer_complement_complex,
1872 resultType.getAsString());
1873 else
1874 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1875 resultType.getAsString());
1876 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001877 break;
1878 case UnaryOperator::LNot: // logical negation
1879 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001880 DefaultFunctionArrayConversion(Input);
1881 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001882 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1883 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1884 resultType.getAsString());
1885 // LNot always has type int. C99 6.5.3.3p5.
1886 resultType = Context.IntTy;
1887 break;
1888 case UnaryOperator::SizeOf:
1889 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1890 break;
1891 case UnaryOperator::AlignOf:
1892 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1893 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00001894 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00001895 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00001896 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00001897 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001898 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 resultType = Input->getType();
1900 break;
1901 }
1902 if (resultType.isNull())
1903 return true;
1904 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1905}
1906
Steve Naroff1b273c42007-09-16 14:56:35 +00001907/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1908Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001909 SourceLocation LabLoc,
1910 IdentifierInfo *LabelII) {
1911 // Look up the record for this label identifier.
1912 LabelStmt *&LabelDecl = LabelMap[LabelII];
1913
1914 // If we haven't seen this label yet, create a forward reference.
1915 if (LabelDecl == 0)
1916 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1917
1918 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00001919 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1920 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001921}
1922
Steve Naroff1b273c42007-09-16 14:56:35 +00001923Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001924 SourceLocation RPLoc) { // "({..})"
1925 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1926 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1927 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1928
1929 // FIXME: there are a variety of strange constraints to enforce here, for
1930 // example, it is not possible to goto into a stmt expression apparently.
1931 // More semantic analysis is needed.
1932
1933 // FIXME: the last statement in the compount stmt has its value used. We
1934 // should not warn about it being unused.
1935
1936 // If there are sub stmts in the compound stmt, take the type of the last one
1937 // as the type of the stmtexpr.
1938 QualType Ty = Context.VoidTy;
1939
1940 if (!Compound->body_empty())
1941 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1942 Ty = LastExpr->getType();
1943
1944 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1945}
Steve Naroffd34e9152007-08-01 22:05:33 +00001946
Steve Naroff1b273c42007-09-16 14:56:35 +00001947Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001948 SourceLocation TypeLoc,
1949 TypeTy *argty,
1950 OffsetOfComponent *CompPtr,
1951 unsigned NumComponents,
1952 SourceLocation RPLoc) {
1953 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1954 assert(!ArgTy.isNull() && "Missing type argument!");
1955
1956 // We must have at least one component that refers to the type, and the first
1957 // one is known to be a field designator. Verify that the ArgTy represents
1958 // a struct/union/class.
1959 if (!ArgTy->isRecordType())
1960 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1961
1962 // Otherwise, create a compound literal expression as the base, and
1963 // iteratively process the offsetof designators.
1964 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1965
Chris Lattner9e2b75c2007-08-31 21:49:13 +00001966 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1967 // GCC extension, diagnose them.
1968 if (NumComponents != 1)
1969 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1970 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1971
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001972 for (unsigned i = 0; i != NumComponents; ++i) {
1973 const OffsetOfComponent &OC = CompPtr[i];
1974 if (OC.isBrackets) {
1975 // Offset of an array sub-field. TODO: Should we allow vector elements?
1976 const ArrayType *AT = Res->getType()->getAsArrayType();
1977 if (!AT) {
1978 delete Res;
1979 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1980 Res->getType().getAsString());
1981 }
1982
Chris Lattner704fe352007-08-30 17:59:59 +00001983 // FIXME: C++: Verify that operator[] isn't overloaded.
1984
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001985 // C99 6.5.2.1p1
1986 Expr *Idx = static_cast<Expr*>(OC.U.E);
1987 if (!Idx->getType()->isIntegerType())
1988 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1989 Idx->getSourceRange());
1990
1991 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1992 continue;
1993 }
1994
1995 const RecordType *RC = Res->getType()->getAsRecordType();
1996 if (!RC) {
1997 delete Res;
1998 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1999 Res->getType().getAsString());
2000 }
2001
2002 // Get the decl corresponding to this.
2003 RecordDecl *RD = RC->getDecl();
2004 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2005 if (!MemberDecl)
2006 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2007 OC.U.IdentInfo->getName(),
2008 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00002009
2010 // FIXME: C++: Verify that MemberDecl isn't a static field.
2011 // FIXME: Verify that MemberDecl isn't a bitfield.
2012
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002013 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
2014 }
2015
2016 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2017 BuiltinLoc);
2018}
2019
2020
Steve Naroff1b273c42007-09-16 14:56:35 +00002021Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00002022 TypeTy *arg1, TypeTy *arg2,
2023 SourceLocation RPLoc) {
2024 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2025 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2026
2027 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2028
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002029 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00002030}
2031
Steve Naroff1b273c42007-09-16 14:56:35 +00002032Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00002033 ExprTy *expr1, ExprTy *expr2,
2034 SourceLocation RPLoc) {
2035 Expr *CondExpr = static_cast<Expr*>(cond);
2036 Expr *LHSExpr = static_cast<Expr*>(expr1);
2037 Expr *RHSExpr = static_cast<Expr*>(expr2);
2038
2039 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2040
2041 // The conditional expression is required to be a constant expression.
2042 llvm::APSInt condEval(32);
2043 SourceLocation ExpLoc;
2044 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2045 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2046 CondExpr->getSourceRange());
2047
2048 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2049 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2050 RHSExpr->getType();
2051 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2052}
2053
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002054Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2055 ExprTy *expr, TypeTy *type,
2056 SourceLocation RPLoc)
2057{
2058 Expr *E = static_cast<Expr*>(expr);
2059 QualType T = QualType::getFromOpaquePtr(type);
2060
2061 InitBuiltinVaListType();
2062
2063 Sema::AssignmentCheckResult result;
2064
2065 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
2066 E->getType());
2067 if (result != Compatible)
2068 return Diag(E->getLocStart(),
2069 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2070 E->getType().getAsString(),
2071 E->getSourceRange());
2072
2073 // FIXME: Warn if a non-POD type is passed in.
2074
2075 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2076}
2077
Anders Carlsson55085182007-08-21 17:43:55 +00002078// TODO: Move this to SemaObjC.cpp
Chris Lattnerb3a99cd2007-12-12 01:04:12 +00002079Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
2080 ExprTy **Strings,
2081 unsigned NumStrings) {
Chris Lattnerb3a99cd2007-12-12 01:04:12 +00002082 SourceLocation AtLoc = AtLocs[0];
2083 StringLiteral* S = static_cast<StringLiteral *>(Strings[0]);
Fariborz Jahanian79a99f22007-12-12 23:55:49 +00002084 if (NumStrings > 1) {
2085 // Concatenate objc strings.
2086 StringLiteral* ES = static_cast<StringLiteral *>(Strings[NumStrings-1]);
2087 SourceLocation EndLoc = ES->getSourceRange().getEnd();
2088 unsigned Length = 0;
2089 for (unsigned i = 0; i < NumStrings; i++)
2090 Length += static_cast<StringLiteral *>(Strings[i])->getByteLength();
2091 char *strBuf = new char [Length];
2092 char *p = strBuf;
2093 bool isWide = false;
2094 for (unsigned i = 0; i < NumStrings; i++) {
2095 S = static_cast<StringLiteral *>(Strings[i]);
2096 if (S->isWide())
2097 isWide = true;
2098 memcpy(p, S->getStrData(), S->getByteLength());
2099 p += S->getByteLength();
2100 delete S;
2101 }
2102 S = new StringLiteral(strBuf, Length,
2103 isWide, Context.getPointerType(Context.CharTy),
2104 AtLoc, EndLoc);
2105 }
Anders Carlsson55085182007-08-21 17:43:55 +00002106
2107 if (CheckBuiltinCFStringArgument(S))
2108 return true;
2109
Steve Naroff21988912007-10-15 23:35:17 +00002110 if (Context.getObjcConstantStringInterface().isNull()) {
2111 // Initialize the constant string interface lazily. This assumes
2112 // the NSConstantString interface is seen in this translation unit.
2113 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
2114 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
2115 SourceLocation(), TUScope);
Steve Naroffa1fe1172007-10-16 00:00:18 +00002116 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff806a4eb2007-10-18 23:53:51 +00002117 if (!strIFace)
2118 return Diag(S->getLocStart(), diag::err_undef_interface,
2119 NSIdent->getName());
Steve Naroffa1fe1172007-10-16 00:00:18 +00002120 Context.setObjcConstantStringInterface(strIFace);
Steve Naroff21988912007-10-15 23:35:17 +00002121 }
2122 QualType t = Context.getObjcConstantStringInterface();
Anders Carlsson55085182007-08-21 17:43:55 +00002123 t = Context.getPointerType(t);
Steve Naroffbeaf2992007-11-03 11:27:19 +00002124 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlsson55085182007-08-21 17:43:55 +00002125}
Anders Carlssonf9bcf012007-08-22 15:14:15 +00002126
2127Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattner674af952007-10-16 22:51:17 +00002128 SourceLocation EncodeLoc,
Anders Carlssonf9bcf012007-08-22 15:14:15 +00002129 SourceLocation LParenLoc,
2130 TypeTy *Ty,
2131 SourceLocation RParenLoc) {
2132 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
2133
2134 QualType t = Context.getPointerType(Context.CharTy);
2135 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
2136}
Steve Naroff708391a2007-09-17 21:01:15 +00002137
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002138Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
2139 SourceLocation AtLoc,
Fariborz Jahanian2a35fa92007-10-16 23:21:02 +00002140 SourceLocation SelLoc,
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002141 SourceLocation LParenLoc,
2142 SourceLocation RParenLoc) {
Steve Naroff8ee529b2007-10-31 18:42:27 +00002143 QualType t = Context.getObjcSelType();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002144 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
2145}
2146
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002147Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
2148 SourceLocation AtLoc,
2149 SourceLocation ProtoLoc,
2150 SourceLocation LParenLoc,
2151 SourceLocation RParenLoc) {
2152 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
2153 if (!PDecl) {
2154 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
2155 return true;
2156 }
2157
Fariborz Jahanian66c5dfc2007-12-07 00:18:54 +00002158 QualType t = Context.getObjcProtoType();
Fariborz Jahanian3e27aa12007-10-18 22:59:23 +00002159 if (t.isNull())
2160 return true;
Fariborz Jahanian66c5dfc2007-12-07 00:18:54 +00002161 t = Context.getPointerType(t);
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002162 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
2163}
Steve Naroff81bfde92007-10-16 23:12:48 +00002164
2165bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2166 ObjcMethodDecl *Method) {
2167 bool anyIncompatibleArgs = false;
2168
2169 for (unsigned i = 0; i < NumArgs; i++) {
2170 Expr *argExpr = Args[i];
2171 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2172
2173 QualType lhsType = Method->getParamDecl(i)->getType();
2174 QualType rhsType = argExpr->getType();
2175
2176 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2177 if (const ArrayType *ary = lhsType->getAsArrayType())
2178 lhsType = Context.getPointerType(ary->getElementType());
2179 else if (lhsType->isFunctionType())
2180 lhsType = Context.getPointerType(lhsType);
2181
2182 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2183 argExpr);
2184 if (Args[i] != argExpr) // The expression was converted.
2185 Args[i] = argExpr; // Make sure we store the converted expression.
2186 SourceLocation l = argExpr->getLocStart();
2187
2188 // decode the result (notice that AST's are still created for extensions).
2189 switch (result) {
2190 case Compatible:
2191 break;
2192 case PointerFromInt:
Steve Naroff529a4ad2007-11-27 17:58:44 +00002193 Diag(l, diag::ext_typecheck_sending_pointer_int,
2194 lhsType.getAsString(), rhsType.getAsString(),
2195 argExpr->getSourceRange());
Steve Naroff81bfde92007-10-16 23:12:48 +00002196 break;
2197 case IntFromPointer:
2198 Diag(l, diag::ext_typecheck_sending_pointer_int,
2199 lhsType.getAsString(), rhsType.getAsString(),
2200 argExpr->getSourceRange());
2201 break;
2202 case IncompatiblePointer:
2203 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2204 rhsType.getAsString(), lhsType.getAsString(),
2205 argExpr->getSourceRange());
2206 break;
2207 case CompatiblePointerDiscardsQualifiers:
2208 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2209 rhsType.getAsString(), lhsType.getAsString(),
2210 argExpr->getSourceRange());
2211 break;
2212 case Incompatible:
2213 Diag(l, diag::err_typecheck_sending_incompatible,
2214 rhsType.getAsString(), lhsType.getAsString(),
2215 argExpr->getSourceRange());
2216 anyIncompatibleArgs = true;
2217 }
2218 }
2219 return anyIncompatibleArgs;
2220}
2221
Steve Naroff68d331a2007-09-27 14:38:14 +00002222// ActOnClassMessage - used for both unary and keyword messages.
2223// ArgExprs is optional - if it is present, the number of expressions
2224// is obtained from Sel.getNumArgs().
2225Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002226 Scope *S,
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002227 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff49f109c2007-11-15 13:05:42 +00002228 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff708391a2007-09-17 21:01:15 +00002229{
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002230 assert(receiverName && "missing receiver class name");
Steve Naroff563477d2007-09-18 23:55:05 +00002231
Steve Naroff81bfde92007-10-16 23:12:48 +00002232 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002233 ObjcInterfaceDecl* ClassDecl = 0;
2234 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2235 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahaniancffff842007-11-12 20:20:37 +00002236 if (ClassDecl && CurMethodDecl->isInstance()) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002237 // Synthesize a cast to the super class. This hack allows us to loosely
2238 // represent super without creating a special expression node.
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002239 IdentifierInfo &II = Context.Idents.get("self");
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002240 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II, false);
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002241 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2242 superTy = Context.getPointerType(superTy);
2243 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2244 SourceLocation(), ReceiverExpr.Val);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002245 // We are really in an instance method, redirect.
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002246 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
Steve Naroff49f109c2007-11-15 13:05:42 +00002247 Args, NumArgs);
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002248 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002249 // We are sending a message to 'super' within a class method. Do nothing,
2250 // the receiver will pass through as 'super' (how convenient:-).
2251 } else
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002252 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002253
2254 // FIXME: can ClassDecl ever be null?
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002255 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff983df5b2007-10-16 20:39:36 +00002256 QualType returnType;
Steve Naroff945c0a82007-11-05 15:27:52 +00002257
2258 // Before we give up, check if the selector is an instance method.
2259 if (!Method)
2260 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff983df5b2007-10-16 20:39:36 +00002261 if (!Method) {
2262 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2263 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002264 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002265 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002266 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002267 if (Sel.getNumArgs()) {
2268 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2269 return true;
2270 }
Steve Naroff983df5b2007-10-16 20:39:36 +00002271 }
Steve Naroffdb611d52007-11-03 16:37:59 +00002272 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
Steve Naroff49f109c2007-11-15 13:05:42 +00002273 lbrac, rbrac, ArgExprs, NumArgs);
Steve Naroff708391a2007-09-17 21:01:15 +00002274}
2275
Steve Naroff68d331a2007-09-27 14:38:14 +00002276// ActOnInstanceMessage - used for both unary and keyword messages.
2277// ArgExprs is optional - if it is present, the number of expressions
2278// is obtained from Sel.getNumArgs().
2279Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroffbcfb06a2007-09-28 22:22:11 +00002280 ExprTy *receiver, Selector Sel,
Steve Naroff49f109c2007-11-15 13:05:42 +00002281 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff68d331a2007-09-27 14:38:14 +00002282{
Steve Naroff563477d2007-09-18 23:55:05 +00002283 assert(receiver && "missing receiver expression");
2284
Steve Naroff81bfde92007-10-16 23:12:48 +00002285 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroff563477d2007-09-18 23:55:05 +00002286 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002287 QualType receiverType = RExpr->getType();
Steve Naroff3b950172007-10-10 21:53:07 +00002288 QualType returnType;
Steve Naroffdb611d52007-11-03 16:37:59 +00002289 ObjcMethodDecl *Method;
Steve Naroff3b950172007-10-10 21:53:07 +00002290
Steve Naroff7c249152007-11-11 17:52:25 +00002291 if (receiverType == Context.getObjcIdType() ||
2292 receiverType == Context.getObjcClassType()) {
Steve Naroffdb611d52007-11-03 16:37:59 +00002293 Method = InstanceMethodPool[Sel].Method;
Steve Naroffa56f6162007-12-18 01:30:32 +00002294 if (!Method)
2295 Method = FactoryMethodPool[Sel].Method;
Steve Naroff983df5b2007-10-16 20:39:36 +00002296 if (!Method) {
2297 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2298 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002299 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002300 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002301 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002302 if (Sel.getNumArgs())
2303 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2304 return true;
Steve Naroff983df5b2007-10-16 20:39:36 +00002305 }
Steve Naroff3b950172007-10-10 21:53:07 +00002306 } else {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002307 bool receiverIsQualId =
2308 dyn_cast<ObjcQualifiedIdType>(RExpr->getType()) != 0;
Chris Lattner22b73ba2007-10-10 23:42:28 +00002309 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2310 // revisited. how do we get the ClassDecl from the receiver expression?
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002311 if (!receiverIsQualId)
2312 while (receiverType->isPointerType()) {
2313 PointerType *pointerType =
2314 static_cast<PointerType*>(receiverType.getTypePtr());
2315 receiverType = pointerType->getPointeeType();
2316 }
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002317 ObjcInterfaceDecl* ClassDecl;
2318 if (ObjcQualifiedInterfaceType *QIT =
2319 dyn_cast<ObjcQualifiedInterfaceType>(receiverType)) {
Fariborz Jahanian06cef252007-12-13 20:47:42 +00002320 ClassDecl = QIT->getDecl();
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002321 Method = ClassDecl->lookupInstanceMethod(Sel);
2322 if (!Method) {
2323 // search protocols
2324 for (unsigned i = 0; i < QIT->getNumProtocols(); i++) {
2325 ObjcProtocolDecl *PDecl = QIT->getProtocols(i);
2326 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
2327 break;
2328 }
2329 }
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002330 if (!Method)
2331 Diag(lbrac, diag::warn_method_not_found_in_protocol,
2332 std::string("-"), Sel.getName(),
2333 SourceRange(lbrac, rbrac));
2334 }
2335 else if (ObjcQualifiedIdType *QIT =
2336 dyn_cast<ObjcQualifiedIdType>(receiverType)) {
2337 // search protocols
2338 for (unsigned i = 0; i < QIT->getNumProtocols(); i++) {
2339 ObjcProtocolDecl *PDecl = QIT->getProtocols(i);
2340 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
2341 break;
2342 }
2343 if (!Method)
2344 Diag(lbrac, diag::warn_method_not_found_in_protocol,
2345 std::string("-"), Sel.getName(),
2346 SourceRange(lbrac, rbrac));
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002347 }
2348 else {
2349 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2350 "bad receiver type");
2351 ClassDecl = static_cast<ObjcInterfaceType*>(
2352 receiverType.getTypePtr())->getDecl();
2353 // FIXME: consider using InstanceMethodPool, since it will be faster
2354 // than the following method (which can do *many* linear searches). The
2355 // idea is to add class info to InstanceMethodPool...
2356 Method = ClassDecl->lookupInstanceMethod(Sel);
2357 }
Steve Naroff983df5b2007-10-16 20:39:36 +00002358 if (!Method) {
Steve Naroffc43d8682007-11-11 00:10:47 +00002359 // If we have an implementation in scope, check "private" methods.
2360 if (ObjcImplementationDecl *ImpDecl =
2361 ObjcImplementations[ClassDecl->getIdentifier()])
Steve Naroff94a5c332007-12-19 22:27:04 +00002362 Method = ImpDecl->getInstanceMethod(Sel);
Steve Naroff9a4ad372007-12-11 03:38:03 +00002363 // If we still haven't found a method, look in the global pool. This
2364 // behavior isn't very desirable, however we need it for GCC compatibility.
Steve Naroff9feba022007-12-07 20:41:14 +00002365 if (!Method)
2366 Method = InstanceMethodPool[Sel].Method;
Steve Naroffc43d8682007-11-11 00:10:47 +00002367 }
2368 if (!Method) {
Steve Naroff983df5b2007-10-16 20:39:36 +00002369 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2370 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002371 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002372 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002373 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002374 if (Sel.getNumArgs())
2375 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2376 return true;
Steve Naroff983df5b2007-10-16 20:39:36 +00002377 }
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002378 }
Steve Naroffdb611d52007-11-03 16:37:59 +00002379 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
Steve Naroff49f109c2007-11-15 13:05:42 +00002380 ArgExprs, NumArgs);
Steve Naroff708391a2007-09-17 21:01:15 +00002381}