blob: 99426a29fb12c7c3eae20954895561802d74af03 [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 {
1132 if (lhsType->isVectorType() && rhsType->isVectorType()) {
1133 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1134 (lhsType->isRealFloatingType() &&
1135 rhsType->isRealFloatingType())) {
1136 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1137 Context.getTypeSize(rhsType, SourceLocation()))
1138 return Compatible;
1139 }
1140 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 return Incompatible;
Anders Carlsson695dbb62007-11-30 04:21:22 +00001142 }
1143 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001144 return Compatible;
1145 } else if (lhsType->isPointerType()) {
1146 if (rhsType->isIntegerType())
1147 return PointerFromInt;
1148
1149 if (rhsType->isPointerType())
1150 return CheckPointerTypesForAssignment(lhsType, rhsType);
1151 } else if (rhsType->isPointerType()) {
1152 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1153 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1154 return IntFromPointer;
1155
1156 if (lhsType->isPointerType())
1157 return CheckPointerTypesForAssignment(lhsType, rhsType);
1158 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroffec0550f2007-10-15 20:41:53 +00001159 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001160 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001161 }
1162 return Incompatible;
1163}
1164
Steve Naroff90045e82007-07-13 23:32:42 +00001165Sema::AssignmentCheckResult
1166Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroff529a4ad2007-11-27 17:58:44 +00001167 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1168 // a null pointer constant.
1169 if (lhsType->isPointerType() && rExpr->isNullPointerConstant(Context)) {
1170 promoteExprToType(rExpr, lhsType);
1171 return Compatible;
1172 }
Chris Lattner943140e2007-10-16 02:55:40 +00001173 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001174 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001175 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001176 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001177 //
1178 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1179 // are better understood.
1180 if (!lhsType->isReferenceType())
1181 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001182
1183 Sema::AssignmentCheckResult result;
Steve Naroff90045e82007-07-13 23:32:42 +00001184
Steve Narofff1120de2007-08-24 22:33:52 +00001185 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1186
1187 // C99 6.5.16.1p2: The value of the right operand is converted to the
1188 // type of the assignment expression.
1189 if (rExpr->getType() != lhsType)
1190 promoteExprToType(rExpr, lhsType);
1191 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001192}
1193
1194Sema::AssignmentCheckResult
1195Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1196 return CheckAssignmentConstraints(lhsType, rhsType);
1197}
1198
Chris Lattnerca5eede2007-12-12 05:47:28 +00001199QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 Diag(loc, diag::err_typecheck_invalid_operands,
1201 lex->getType().getAsString(), rex->getType().getAsString(),
1202 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerca5eede2007-12-12 05:47:28 +00001203 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001204}
1205
Steve Naroff49b45262007-07-13 16:58:59 +00001206inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1207 Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 QualType lhsType = lex->getType(), rhsType = rex->getType();
1209
1210 // make sure the vector types are identical.
1211 if (lhsType == rhsType)
1212 return lhsType;
1213 // You cannot convert between vector values of different size.
1214 Diag(loc, diag::err_typecheck_vector_not_convertable,
1215 lex->getType().getAsString(), rex->getType().getAsString(),
1216 lex->getSourceRange(), rex->getSourceRange());
1217 return QualType();
1218}
1219
1220inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001221 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001222{
Steve Naroff90045e82007-07-13 23:32:42 +00001223 QualType lhsType = lex->getType(), rhsType = rex->getType();
1224
1225 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001226 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001227
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001228 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001229
Steve Naroffa4332e22007-07-17 00:58:39 +00001230 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001231 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001232 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001233}
1234
1235inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001236 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001237{
Steve Naroff90045e82007-07-13 23:32:42 +00001238 QualType lhsType = lex->getType(), rhsType = rex->getType();
1239
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001240 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001241
Steve Naroffa4332e22007-07-17 00:58:39 +00001242 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001243 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001244 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001245}
1246
1247inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001248 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001249{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001250 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001251 return CheckVectorOperands(loc, lex, rex);
1252
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001253 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Steve Naroff3e5e5562007-07-16 22:23:01 +00001254
Reid Spencer5f016e22007-07-11 17:01:13 +00001255 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001256 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001257 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001258
Steve Naroffa4332e22007-07-17 00:58:39 +00001259 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1260 return lex->getType();
1261 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1262 return rex->getType();
Chris Lattnerca5eede2007-12-12 05:47:28 +00001263 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001264}
1265
1266inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001267 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001268{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001269 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001270 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001271
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001272 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001273
Chris Lattner6e4ab612007-12-09 21:53:25 +00001274 // Enforce type constraints: C99 6.5.6p3.
1275
1276 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001277 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001278 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001279
1280 // Either ptr - int or ptr - ptr.
1281 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1282 // The LHS must be an object type, not incomplete, function, etc.
1283 if (!LHSPTy->getPointeeType()->isObjectType()) {
1284 // Handle the GNU void* extension.
1285 if (LHSPTy->getPointeeType()->isVoidType()) {
1286 Diag(loc, diag::ext_gnu_void_ptr,
1287 lex->getSourceRange(), rex->getSourceRange());
1288 } else {
1289 Diag(loc, diag::err_typecheck_sub_ptr_object,
1290 lex->getType().getAsString(), lex->getSourceRange());
1291 return QualType();
1292 }
1293 }
1294
1295 // The result type of a pointer-int computation is the pointer type.
1296 if (rex->getType()->isIntegerType())
1297 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001298
Chris Lattner6e4ab612007-12-09 21:53:25 +00001299 // Handle pointer-pointer subtractions.
1300 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1301 // RHS must be an object type, unless void (GNU).
1302 if (!RHSPTy->getPointeeType()->isObjectType()) {
1303 // Handle the GNU void* extension.
1304 if (RHSPTy->getPointeeType()->isVoidType()) {
1305 if (!LHSPTy->getPointeeType()->isVoidType())
1306 Diag(loc, diag::ext_gnu_void_ptr,
1307 lex->getSourceRange(), rex->getSourceRange());
1308 } else {
1309 Diag(loc, diag::err_typecheck_sub_ptr_object,
1310 rex->getType().getAsString(), rex->getSourceRange());
1311 return QualType();
1312 }
1313 }
1314
1315 // Pointee types must be compatible.
1316 if (!Context.typesAreCompatible(LHSPTy->getPointeeType(),
1317 RHSPTy->getPointeeType())) {
1318 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1319 lex->getType().getAsString(), rex->getType().getAsString(),
1320 lex->getSourceRange(), rex->getSourceRange());
1321 return QualType();
1322 }
1323
1324 return Context.getPointerDiffType();
1325 }
1326 }
1327
Chris Lattnerca5eede2007-12-12 05:47:28 +00001328 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001329}
1330
1331inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Chris Lattnerca5eede2007-12-12 05:47:28 +00001332 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1333 // C99 6.5.7p2: Each of the operands shall have integer type.
1334 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1335 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001336
Chris Lattnerca5eede2007-12-12 05:47:28 +00001337 // Shifts don't perform usual arithmetic conversions, they just do integer
1338 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00001339 if (!isCompAssign)
1340 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00001341 UsualUnaryConversions(rex);
1342
1343 // "The type of the result is that of the promoted left operand."
1344 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001345}
1346
Chris Lattnera5937dd2007-08-26 01:18:55 +00001347inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1348 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Reid Spencer5f016e22007-07-11 17:01:13 +00001349{
Chris Lattnera5937dd2007-08-26 01:18:55 +00001350 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00001351 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1352 UsualArithmeticConversions(lex, rex);
1353 else {
1354 UsualUnaryConversions(lex);
1355 UsualUnaryConversions(rex);
1356 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001357 QualType lType = lex->getType();
1358 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001359
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001360 // For non-floating point types, check for self-comparisons of the form
1361 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1362 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001363 if (!lType->isFloatingType()) {
1364 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1365 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1366 if (DRL->getDecl() == DRR->getDecl())
1367 Diag(loc, diag::warn_selfcomparison);
1368 }
1369
Chris Lattnera5937dd2007-08-26 01:18:55 +00001370 if (isRelational) {
1371 if (lType->isRealType() && rType->isRealType())
1372 return Context.IntTy;
1373 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001374 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001375 if (lType->isFloatingType()) {
1376 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001377 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00001378 }
1379
Chris Lattnera5937dd2007-08-26 01:18:55 +00001380 if (lType->isArithmeticType() && rType->isArithmeticType())
1381 return Context.IntTy;
1382 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001383
Chris Lattnerd28f8152007-08-26 01:10:14 +00001384 bool LHSIsNull = lex->isNullPointerConstant(Context);
1385 bool RHSIsNull = rex->isNullPointerConstant(Context);
1386
Chris Lattnera5937dd2007-08-26 01:18:55 +00001387 // All of the following pointer related warnings are GCC extensions, except
1388 // when handling null pointer constants. One day, we can consider making them
1389 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00001390 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff66296cb2007-11-13 14:57:38 +00001391
1392 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1393 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1394 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroffec0550f2007-10-15 20:41:53 +00001395 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1396 rType.getUnqualifiedType())) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001397 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1398 lType.getAsString(), rType.getAsString(),
1399 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 }
Chris Lattnerd28f8152007-08-26 01:10:14 +00001401 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001402 return Context.IntTy;
1403 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00001404 if ((lType->isObjcQualifiedIdType() || rType->isObjcQualifiedIdType())
Fariborz Jahaniand0c89c42007-12-21 00:33:59 +00001405 && Context.ObjcQualifiedIdTypesAreCompatible(lType, rType, true)) {
Fariborz Jahanian7359f042007-12-20 01:06:58 +00001406 promoteExprToType(rex, lType);
1407 return Context.IntTy;
1408 }
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001409 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001410 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001411 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1412 lType.getAsString(), rType.getAsString(),
1413 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001414 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001415 return Context.IntTy;
1416 }
1417 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001418 if (!LHSIsNull)
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(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001423 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 }
Chris Lattnerca5eede2007-12-12 05:47:28 +00001425 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001426}
1427
Reid Spencer5f016e22007-07-11 17:01:13 +00001428inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001429 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001430{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001431 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001432 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001433
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001434 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001435
Steve Naroffa4332e22007-07-17 00:58:39 +00001436 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001437 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001438 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001439}
1440
1441inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00001442 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001443{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001444 UsualUnaryConversions(lex);
1445 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001446
Steve Naroffa4332e22007-07-17 00:58:39 +00001447 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001448 return Context.IntTy;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001449 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001450}
1451
1452inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00001453 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001454{
1455 QualType lhsType = lex->getType();
1456 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1457 bool hadError = false;
1458 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1459
1460 switch (mlval) { // C99 6.5.16p2
1461 case Expr::MLV_Valid:
1462 break;
1463 case Expr::MLV_ConstQualified:
1464 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1465 hadError = true;
1466 break;
1467 case Expr::MLV_ArrayType:
1468 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1469 lhsType.getAsString(), lex->getSourceRange());
1470 return QualType();
1471 case Expr::MLV_NotObjectType:
1472 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1473 lhsType.getAsString(), lex->getSourceRange());
1474 return QualType();
1475 case Expr::MLV_InvalidExpression:
1476 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1477 lex->getSourceRange());
1478 return QualType();
1479 case Expr::MLV_IncompleteType:
1480 case Expr::MLV_IncompleteVoidType:
1481 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1482 lhsType.getAsString(), lex->getSourceRange());
1483 return QualType();
Steve Narofffec0b492007-07-30 03:29:09 +00001484 case Expr::MLV_DuplicateVectorComponents:
1485 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1486 lex->getSourceRange());
1487 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 }
Steve Naroff90045e82007-07-13 23:32:42 +00001489 AssignmentCheckResult result;
1490
1491 if (compoundType.isNull())
1492 result = CheckSingleAssignmentConstraints(lhsType, rex);
1493 else
1494 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001495
Reid Spencer5f016e22007-07-11 17:01:13 +00001496 // decode the result (notice that extensions still return a type).
1497 switch (result) {
1498 case Compatible:
1499 break;
1500 case Incompatible:
1501 Diag(loc, diag::err_typecheck_assign_incompatible,
1502 lhsType.getAsString(), rhsType.getAsString(),
1503 lex->getSourceRange(), rex->getSourceRange());
1504 hadError = true;
1505 break;
1506 case PointerFromInt:
Steve Naroff529a4ad2007-11-27 17:58:44 +00001507 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1508 lhsType.getAsString(), rhsType.getAsString(),
1509 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001510 break;
1511 case IntFromPointer:
1512 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1513 lhsType.getAsString(), rhsType.getAsString(),
1514 lex->getSourceRange(), rex->getSourceRange());
1515 break;
1516 case IncompatiblePointer:
1517 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1518 lhsType.getAsString(), rhsType.getAsString(),
1519 lex->getSourceRange(), rex->getSourceRange());
1520 break;
1521 case CompatiblePointerDiscardsQualifiers:
1522 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1523 lhsType.getAsString(), rhsType.getAsString(),
1524 lex->getSourceRange(), rex->getSourceRange());
1525 break;
1526 }
1527 // C99 6.5.16p3: The type of an assignment expression is the type of the
1528 // left operand unless the left operand has qualified type, in which case
1529 // it is the unqualified version of the type of the left operand.
1530 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1531 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001532 // C++ 5.17p1: the type of the assignment expression is that of its left
1533 // oprdu.
Reid Spencer5f016e22007-07-11 17:01:13 +00001534 return hadError ? QualType() : lhsType.getUnqualifiedType();
1535}
1536
1537inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00001538 Expr *&lex, Expr *&rex, SourceLocation loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001539 UsualUnaryConversions(rex);
1540 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001541}
1542
Steve Naroff49b45262007-07-13 16:58:59 +00001543/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1544/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00001545QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00001546 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001547 assert(!resType.isNull() && "no type for increment/decrement expression");
1548
Steve Naroff084f9ed2007-08-24 17:20:07 +00001549 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00001550 if (const PointerType *pt = resType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1552 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1553 resType.getAsString(), op->getSourceRange());
1554 return QualType();
1555 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00001556 } else if (!resType->isRealType()) {
1557 if (resType->isComplexType())
1558 // C99 does not support ++/-- on complex types.
1559 Diag(OpLoc, diag::ext_integer_increment_complex,
1560 resType.getAsString(), op->getSourceRange());
1561 else {
1562 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1563 resType.getAsString(), op->getSourceRange());
1564 return QualType();
1565 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 }
Steve Naroffdd10e022007-08-23 21:37:33 +00001567 // At this point, we know we have a real, complex or pointer type.
1568 // Now make sure the operand is a modifiable lvalue.
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1570 if (mlval != Expr::MLV_Valid) {
1571 // FIXME: emit a more precise diagnostic...
1572 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1573 op->getSourceRange());
1574 return QualType();
1575 }
1576 return resType;
1577}
1578
1579/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1580/// This routine allows us to typecheck complex/recursive expressions
1581/// where the declaration is needed for type checking. Here are some
1582/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1583static Decl *getPrimaryDeclaration(Expr *e) {
1584 switch (e->getStmtClass()) {
1585 case Stmt::DeclRefExprClass:
1586 return cast<DeclRefExpr>(e)->getDecl();
1587 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00001588 // Fields cannot be declared with a 'register' storage class.
1589 // &X->f is always ok, even if X is declared register.
1590 if (cast<MemberExpr>(e)->isArrow())
1591 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1593 case Stmt::ArraySubscriptExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00001594 // &X[4] and &4[X] is invalid if X is invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +00001595 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 case Stmt::UnaryOperatorClass:
1597 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1598 case Stmt::ParenExprClass:
1599 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00001600 case Stmt::ImplicitCastExprClass:
1601 // &X[4] when X is an array, has an implicit cast from array to pointer.
1602 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00001603 default:
1604 return 0;
1605 }
1606}
1607
1608/// CheckAddressOfOperand - The operand of & must be either a function
1609/// designator or an lvalue designating an object. If it is an lvalue, the
1610/// object cannot be declared with storage class register or be a bit field.
1611/// Note: The usual conversions are *not* applied to the operand of the &
1612/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1613QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1614 Decl *dcl = getPrimaryDeclaration(op);
1615 Expr::isLvalueResult lval = op->isLvalue();
1616
1617 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00001618 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1619 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00001620 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1621 op->getSourceRange());
1622 return QualType();
1623 }
1624 } else if (dcl) {
1625 // We have an lvalue with a decl. Make sure the decl is not declared
1626 // with the register storage-class specifier.
1627 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1628 if (vd->getStorageClass() == VarDecl::Register) {
1629 Diag(OpLoc, diag::err_typecheck_address_of_register,
1630 op->getSourceRange());
1631 return QualType();
1632 }
1633 } else
1634 assert(0 && "Unknown/unexpected decl type");
1635
1636 // FIXME: add check for bitfields!
1637 }
1638 // If the operand has type "type", the result has type "pointer to type".
1639 return Context.getPointerType(op->getType());
1640}
1641
1642QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001643 UsualUnaryConversions(op);
1644 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001645
Chris Lattnerbefee482007-07-31 16:53:04 +00001646 if (const PointerType *PT = qType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 QualType ptype = PT->getPointeeType();
1648 // C99 6.5.3.2p4. "if it points to an object,...".
1649 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1650 // GCC compat: special case 'void *' (treat as warning).
1651 if (ptype->isVoidType()) {
1652 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1653 qType.getAsString(), op->getSourceRange());
1654 } else {
1655 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1656 ptype.getAsString(), op->getSourceRange());
1657 return QualType();
1658 }
1659 }
1660 return ptype;
1661 }
1662 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1663 qType.getAsString(), op->getSourceRange());
1664 return QualType();
1665}
1666
1667static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1668 tok::TokenKind Kind) {
1669 BinaryOperator::Opcode Opc;
1670 switch (Kind) {
1671 default: assert(0 && "Unknown binop!");
1672 case tok::star: Opc = BinaryOperator::Mul; break;
1673 case tok::slash: Opc = BinaryOperator::Div; break;
1674 case tok::percent: Opc = BinaryOperator::Rem; break;
1675 case tok::plus: Opc = BinaryOperator::Add; break;
1676 case tok::minus: Opc = BinaryOperator::Sub; break;
1677 case tok::lessless: Opc = BinaryOperator::Shl; break;
1678 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1679 case tok::lessequal: Opc = BinaryOperator::LE; break;
1680 case tok::less: Opc = BinaryOperator::LT; break;
1681 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1682 case tok::greater: Opc = BinaryOperator::GT; break;
1683 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1684 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1685 case tok::amp: Opc = BinaryOperator::And; break;
1686 case tok::caret: Opc = BinaryOperator::Xor; break;
1687 case tok::pipe: Opc = BinaryOperator::Or; break;
1688 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1689 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1690 case tok::equal: Opc = BinaryOperator::Assign; break;
1691 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1692 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1693 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1694 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1695 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1696 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1697 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1698 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1699 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1700 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1701 case tok::comma: Opc = BinaryOperator::Comma; break;
1702 }
1703 return Opc;
1704}
1705
1706static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1707 tok::TokenKind Kind) {
1708 UnaryOperator::Opcode Opc;
1709 switch (Kind) {
1710 default: assert(0 && "Unknown unary op!");
1711 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1712 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1713 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1714 case tok::star: Opc = UnaryOperator::Deref; break;
1715 case tok::plus: Opc = UnaryOperator::Plus; break;
1716 case tok::minus: Opc = UnaryOperator::Minus; break;
1717 case tok::tilde: Opc = UnaryOperator::Not; break;
1718 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1719 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1720 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1721 case tok::kw___real: Opc = UnaryOperator::Real; break;
1722 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1723 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1724 }
1725 return Opc;
1726}
1727
1728// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001729Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00001730 ExprTy *LHS, ExprTy *RHS) {
1731 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1732 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1733
Steve Narofff69936d2007-09-16 03:34:24 +00001734 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1735 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00001736
1737 QualType ResultTy; // Result type of the binary operator.
1738 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1739
1740 switch (Opc) {
1741 default:
1742 assert(0 && "Unknown binary expr!");
1743 case BinaryOperator::Assign:
1744 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1745 break;
1746 case BinaryOperator::Mul:
1747 case BinaryOperator::Div:
1748 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1749 break;
1750 case BinaryOperator::Rem:
1751 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1752 break;
1753 case BinaryOperator::Add:
1754 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1755 break;
1756 case BinaryOperator::Sub:
1757 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1758 break;
1759 case BinaryOperator::Shl:
1760 case BinaryOperator::Shr:
1761 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1762 break;
1763 case BinaryOperator::LE:
1764 case BinaryOperator::LT:
1765 case BinaryOperator::GE:
1766 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001767 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001768 break;
1769 case BinaryOperator::EQ:
1770 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001771 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001772 break;
1773 case BinaryOperator::And:
1774 case BinaryOperator::Xor:
1775 case BinaryOperator::Or:
1776 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1777 break;
1778 case BinaryOperator::LAnd:
1779 case BinaryOperator::LOr:
1780 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1781 break;
1782 case BinaryOperator::MulAssign:
1783 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001784 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001785 if (!CompTy.isNull())
1786 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1787 break;
1788 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001789 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001790 if (!CompTy.isNull())
1791 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1792 break;
1793 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001794 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001795 if (!CompTy.isNull())
1796 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1797 break;
1798 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001799 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001800 if (!CompTy.isNull())
1801 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1802 break;
1803 case BinaryOperator::ShlAssign:
1804 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001805 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001806 if (!CompTy.isNull())
1807 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1808 break;
1809 case BinaryOperator::AndAssign:
1810 case BinaryOperator::XorAssign:
1811 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001812 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001813 if (!CompTy.isNull())
1814 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1815 break;
1816 case BinaryOperator::Comma:
1817 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1818 break;
1819 }
1820 if (ResultTy.isNull())
1821 return true;
1822 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001823 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001824 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001825 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001826}
1827
1828// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001829Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00001830 ExprTy *input) {
1831 Expr *Input = (Expr*)input;
1832 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1833 QualType resultType;
1834 switch (Opc) {
1835 default:
1836 assert(0 && "Unimplemented unary expr!");
1837 case UnaryOperator::PreInc:
1838 case UnaryOperator::PreDec:
1839 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1840 break;
1841 case UnaryOperator::AddrOf:
1842 resultType = CheckAddressOfOperand(Input, OpLoc);
1843 break;
1844 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00001845 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00001846 resultType = CheckIndirectionOperand(Input, OpLoc);
1847 break;
1848 case UnaryOperator::Plus:
1849 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001850 UsualUnaryConversions(Input);
1851 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001852 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1853 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1854 resultType.getAsString());
1855 break;
1856 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001857 UsualUnaryConversions(Input);
1858 resultType = Input->getType();
Steve Naroff084f9ed2007-08-24 17:20:07 +00001859 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1860 if (!resultType->isIntegerType()) {
1861 if (resultType->isComplexType())
1862 // C99 does not support '~' for complex conjugation.
1863 Diag(OpLoc, diag::ext_integer_complement_complex,
1864 resultType.getAsString());
1865 else
1866 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1867 resultType.getAsString());
1868 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001869 break;
1870 case UnaryOperator::LNot: // logical negation
1871 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001872 DefaultFunctionArrayConversion(Input);
1873 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001874 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1875 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1876 resultType.getAsString());
1877 // LNot always has type int. C99 6.5.3.3p5.
1878 resultType = Context.IntTy;
1879 break;
1880 case UnaryOperator::SizeOf:
1881 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1882 break;
1883 case UnaryOperator::AlignOf:
1884 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1885 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00001886 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00001887 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00001888 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00001889 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001890 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00001891 resultType = Input->getType();
1892 break;
1893 }
1894 if (resultType.isNull())
1895 return true;
1896 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1897}
1898
Steve Naroff1b273c42007-09-16 14:56:35 +00001899/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1900Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001901 SourceLocation LabLoc,
1902 IdentifierInfo *LabelII) {
1903 // Look up the record for this label identifier.
1904 LabelStmt *&LabelDecl = LabelMap[LabelII];
1905
1906 // If we haven't seen this label yet, create a forward reference.
1907 if (LabelDecl == 0)
1908 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1909
1910 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00001911 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1912 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001913}
1914
Steve Naroff1b273c42007-09-16 14:56:35 +00001915Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001916 SourceLocation RPLoc) { // "({..})"
1917 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1918 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1919 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1920
1921 // FIXME: there are a variety of strange constraints to enforce here, for
1922 // example, it is not possible to goto into a stmt expression apparently.
1923 // More semantic analysis is needed.
1924
1925 // FIXME: the last statement in the compount stmt has its value used. We
1926 // should not warn about it being unused.
1927
1928 // If there are sub stmts in the compound stmt, take the type of the last one
1929 // as the type of the stmtexpr.
1930 QualType Ty = Context.VoidTy;
1931
1932 if (!Compound->body_empty())
1933 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1934 Ty = LastExpr->getType();
1935
1936 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1937}
Steve Naroffd34e9152007-08-01 22:05:33 +00001938
Steve Naroff1b273c42007-09-16 14:56:35 +00001939Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001940 SourceLocation TypeLoc,
1941 TypeTy *argty,
1942 OffsetOfComponent *CompPtr,
1943 unsigned NumComponents,
1944 SourceLocation RPLoc) {
1945 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1946 assert(!ArgTy.isNull() && "Missing type argument!");
1947
1948 // We must have at least one component that refers to the type, and the first
1949 // one is known to be a field designator. Verify that the ArgTy represents
1950 // a struct/union/class.
1951 if (!ArgTy->isRecordType())
1952 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1953
1954 // Otherwise, create a compound literal expression as the base, and
1955 // iteratively process the offsetof designators.
1956 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1957
Chris Lattner9e2b75c2007-08-31 21:49:13 +00001958 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1959 // GCC extension, diagnose them.
1960 if (NumComponents != 1)
1961 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1962 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1963
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001964 for (unsigned i = 0; i != NumComponents; ++i) {
1965 const OffsetOfComponent &OC = CompPtr[i];
1966 if (OC.isBrackets) {
1967 // Offset of an array sub-field. TODO: Should we allow vector elements?
1968 const ArrayType *AT = Res->getType()->getAsArrayType();
1969 if (!AT) {
1970 delete Res;
1971 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1972 Res->getType().getAsString());
1973 }
1974
Chris Lattner704fe352007-08-30 17:59:59 +00001975 // FIXME: C++: Verify that operator[] isn't overloaded.
1976
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001977 // C99 6.5.2.1p1
1978 Expr *Idx = static_cast<Expr*>(OC.U.E);
1979 if (!Idx->getType()->isIntegerType())
1980 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1981 Idx->getSourceRange());
1982
1983 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1984 continue;
1985 }
1986
1987 const RecordType *RC = Res->getType()->getAsRecordType();
1988 if (!RC) {
1989 delete Res;
1990 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1991 Res->getType().getAsString());
1992 }
1993
1994 // Get the decl corresponding to this.
1995 RecordDecl *RD = RC->getDecl();
1996 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1997 if (!MemberDecl)
1998 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1999 OC.U.IdentInfo->getName(),
2000 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00002001
2002 // FIXME: C++: Verify that MemberDecl isn't a static field.
2003 // FIXME: Verify that MemberDecl isn't a bitfield.
2004
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002005 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
2006 }
2007
2008 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2009 BuiltinLoc);
2010}
2011
2012
Steve Naroff1b273c42007-09-16 14:56:35 +00002013Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00002014 TypeTy *arg1, TypeTy *arg2,
2015 SourceLocation RPLoc) {
2016 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2017 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2018
2019 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2020
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002021 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00002022}
2023
Steve Naroff1b273c42007-09-16 14:56:35 +00002024Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00002025 ExprTy *expr1, ExprTy *expr2,
2026 SourceLocation RPLoc) {
2027 Expr *CondExpr = static_cast<Expr*>(cond);
2028 Expr *LHSExpr = static_cast<Expr*>(expr1);
2029 Expr *RHSExpr = static_cast<Expr*>(expr2);
2030
2031 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2032
2033 // The conditional expression is required to be a constant expression.
2034 llvm::APSInt condEval(32);
2035 SourceLocation ExpLoc;
2036 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2037 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2038 CondExpr->getSourceRange());
2039
2040 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2041 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2042 RHSExpr->getType();
2043 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2044}
2045
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002046Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2047 ExprTy *expr, TypeTy *type,
2048 SourceLocation RPLoc)
2049{
2050 Expr *E = static_cast<Expr*>(expr);
2051 QualType T = QualType::getFromOpaquePtr(type);
2052
2053 InitBuiltinVaListType();
2054
2055 Sema::AssignmentCheckResult result;
2056
2057 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
2058 E->getType());
2059 if (result != Compatible)
2060 return Diag(E->getLocStart(),
2061 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2062 E->getType().getAsString(),
2063 E->getSourceRange());
2064
2065 // FIXME: Warn if a non-POD type is passed in.
2066
2067 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2068}
2069
Anders Carlsson55085182007-08-21 17:43:55 +00002070// TODO: Move this to SemaObjC.cpp
Chris Lattnerb3a99cd2007-12-12 01:04:12 +00002071Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
2072 ExprTy **Strings,
2073 unsigned NumStrings) {
Chris Lattnerb3a99cd2007-12-12 01:04:12 +00002074 SourceLocation AtLoc = AtLocs[0];
2075 StringLiteral* S = static_cast<StringLiteral *>(Strings[0]);
Fariborz Jahanian79a99f22007-12-12 23:55:49 +00002076 if (NumStrings > 1) {
2077 // Concatenate objc strings.
2078 StringLiteral* ES = static_cast<StringLiteral *>(Strings[NumStrings-1]);
2079 SourceLocation EndLoc = ES->getSourceRange().getEnd();
2080 unsigned Length = 0;
2081 for (unsigned i = 0; i < NumStrings; i++)
2082 Length += static_cast<StringLiteral *>(Strings[i])->getByteLength();
2083 char *strBuf = new char [Length];
2084 char *p = strBuf;
2085 bool isWide = false;
2086 for (unsigned i = 0; i < NumStrings; i++) {
2087 S = static_cast<StringLiteral *>(Strings[i]);
2088 if (S->isWide())
2089 isWide = true;
2090 memcpy(p, S->getStrData(), S->getByteLength());
2091 p += S->getByteLength();
2092 delete S;
2093 }
2094 S = new StringLiteral(strBuf, Length,
2095 isWide, Context.getPointerType(Context.CharTy),
2096 AtLoc, EndLoc);
2097 }
Anders Carlsson55085182007-08-21 17:43:55 +00002098
2099 if (CheckBuiltinCFStringArgument(S))
2100 return true;
2101
Steve Naroff21988912007-10-15 23:35:17 +00002102 if (Context.getObjcConstantStringInterface().isNull()) {
2103 // Initialize the constant string interface lazily. This assumes
2104 // the NSConstantString interface is seen in this translation unit.
2105 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
2106 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
2107 SourceLocation(), TUScope);
Steve Naroffa1fe1172007-10-16 00:00:18 +00002108 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff806a4eb2007-10-18 23:53:51 +00002109 if (!strIFace)
2110 return Diag(S->getLocStart(), diag::err_undef_interface,
2111 NSIdent->getName());
Steve Naroffa1fe1172007-10-16 00:00:18 +00002112 Context.setObjcConstantStringInterface(strIFace);
Steve Naroff21988912007-10-15 23:35:17 +00002113 }
2114 QualType t = Context.getObjcConstantStringInterface();
Anders Carlsson55085182007-08-21 17:43:55 +00002115 t = Context.getPointerType(t);
Steve Naroffbeaf2992007-11-03 11:27:19 +00002116 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlsson55085182007-08-21 17:43:55 +00002117}
Anders Carlssonf9bcf012007-08-22 15:14:15 +00002118
2119Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattner674af952007-10-16 22:51:17 +00002120 SourceLocation EncodeLoc,
Anders Carlssonf9bcf012007-08-22 15:14:15 +00002121 SourceLocation LParenLoc,
2122 TypeTy *Ty,
2123 SourceLocation RParenLoc) {
2124 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
2125
2126 QualType t = Context.getPointerType(Context.CharTy);
2127 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
2128}
Steve Naroff708391a2007-09-17 21:01:15 +00002129
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002130Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
2131 SourceLocation AtLoc,
Fariborz Jahanian2a35fa92007-10-16 23:21:02 +00002132 SourceLocation SelLoc,
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002133 SourceLocation LParenLoc,
2134 SourceLocation RParenLoc) {
Steve Naroff8ee529b2007-10-31 18:42:27 +00002135 QualType t = Context.getObjcSelType();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002136 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
2137}
2138
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002139Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
2140 SourceLocation AtLoc,
2141 SourceLocation ProtoLoc,
2142 SourceLocation LParenLoc,
2143 SourceLocation RParenLoc) {
2144 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
2145 if (!PDecl) {
2146 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
2147 return true;
2148 }
2149
Fariborz Jahanian66c5dfc2007-12-07 00:18:54 +00002150 QualType t = Context.getObjcProtoType();
Fariborz Jahanian3e27aa12007-10-18 22:59:23 +00002151 if (t.isNull())
2152 return true;
Fariborz Jahanian66c5dfc2007-12-07 00:18:54 +00002153 t = Context.getPointerType(t);
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002154 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
2155}
Steve Naroff81bfde92007-10-16 23:12:48 +00002156
2157bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2158 ObjcMethodDecl *Method) {
2159 bool anyIncompatibleArgs = false;
2160
2161 for (unsigned i = 0; i < NumArgs; i++) {
2162 Expr *argExpr = Args[i];
2163 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2164
2165 QualType lhsType = Method->getParamDecl(i)->getType();
2166 QualType rhsType = argExpr->getType();
2167
2168 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2169 if (const ArrayType *ary = lhsType->getAsArrayType())
2170 lhsType = Context.getPointerType(ary->getElementType());
2171 else if (lhsType->isFunctionType())
2172 lhsType = Context.getPointerType(lhsType);
2173
2174 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2175 argExpr);
2176 if (Args[i] != argExpr) // The expression was converted.
2177 Args[i] = argExpr; // Make sure we store the converted expression.
2178 SourceLocation l = argExpr->getLocStart();
2179
2180 // decode the result (notice that AST's are still created for extensions).
2181 switch (result) {
2182 case Compatible:
2183 break;
2184 case PointerFromInt:
Steve Naroff529a4ad2007-11-27 17:58:44 +00002185 Diag(l, diag::ext_typecheck_sending_pointer_int,
2186 lhsType.getAsString(), rhsType.getAsString(),
2187 argExpr->getSourceRange());
Steve Naroff81bfde92007-10-16 23:12:48 +00002188 break;
2189 case IntFromPointer:
2190 Diag(l, diag::ext_typecheck_sending_pointer_int,
2191 lhsType.getAsString(), rhsType.getAsString(),
2192 argExpr->getSourceRange());
2193 break;
2194 case IncompatiblePointer:
2195 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2196 rhsType.getAsString(), lhsType.getAsString(),
2197 argExpr->getSourceRange());
2198 break;
2199 case CompatiblePointerDiscardsQualifiers:
2200 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2201 rhsType.getAsString(), lhsType.getAsString(),
2202 argExpr->getSourceRange());
2203 break;
2204 case Incompatible:
2205 Diag(l, diag::err_typecheck_sending_incompatible,
2206 rhsType.getAsString(), lhsType.getAsString(),
2207 argExpr->getSourceRange());
2208 anyIncompatibleArgs = true;
2209 }
2210 }
2211 return anyIncompatibleArgs;
2212}
2213
Steve Naroff68d331a2007-09-27 14:38:14 +00002214// ActOnClassMessage - used for both unary and keyword messages.
2215// ArgExprs is optional - if it is present, the number of expressions
2216// is obtained from Sel.getNumArgs().
2217Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002218 Scope *S,
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002219 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff49f109c2007-11-15 13:05:42 +00002220 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff708391a2007-09-17 21:01:15 +00002221{
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002222 assert(receiverName && "missing receiver class name");
Steve Naroff563477d2007-09-18 23:55:05 +00002223
Steve Naroff81bfde92007-10-16 23:12:48 +00002224 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002225 ObjcInterfaceDecl* ClassDecl = 0;
2226 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2227 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahaniancffff842007-11-12 20:20:37 +00002228 if (ClassDecl && CurMethodDecl->isInstance()) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002229 // Synthesize a cast to the super class. This hack allows us to loosely
2230 // represent super without creating a special expression node.
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002231 IdentifierInfo &II = Context.Idents.get("self");
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002232 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II, false);
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002233 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2234 superTy = Context.getPointerType(superTy);
2235 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2236 SourceLocation(), ReceiverExpr.Val);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002237 // We are really in an instance method, redirect.
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002238 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
Steve Naroff49f109c2007-11-15 13:05:42 +00002239 Args, NumArgs);
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002240 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002241 // We are sending a message to 'super' within a class method. Do nothing,
2242 // the receiver will pass through as 'super' (how convenient:-).
2243 } else
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002244 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002245
2246 // FIXME: can ClassDecl ever be null?
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002247 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff983df5b2007-10-16 20:39:36 +00002248 QualType returnType;
Steve Naroff945c0a82007-11-05 15:27:52 +00002249
2250 // Before we give up, check if the selector is an instance method.
2251 if (!Method)
2252 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff983df5b2007-10-16 20:39:36 +00002253 if (!Method) {
2254 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2255 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002256 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002257 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002258 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002259 if (Sel.getNumArgs()) {
2260 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2261 return true;
2262 }
Steve Naroff983df5b2007-10-16 20:39:36 +00002263 }
Steve Naroffdb611d52007-11-03 16:37:59 +00002264 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
Steve Naroff49f109c2007-11-15 13:05:42 +00002265 lbrac, rbrac, ArgExprs, NumArgs);
Steve Naroff708391a2007-09-17 21:01:15 +00002266}
2267
Steve Naroff68d331a2007-09-27 14:38:14 +00002268// ActOnInstanceMessage - used for both unary and keyword messages.
2269// ArgExprs is optional - if it is present, the number of expressions
2270// is obtained from Sel.getNumArgs().
2271Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroffbcfb06a2007-09-28 22:22:11 +00002272 ExprTy *receiver, Selector Sel,
Steve Naroff49f109c2007-11-15 13:05:42 +00002273 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff68d331a2007-09-27 14:38:14 +00002274{
Steve Naroff563477d2007-09-18 23:55:05 +00002275 assert(receiver && "missing receiver expression");
2276
Steve Naroff81bfde92007-10-16 23:12:48 +00002277 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroff563477d2007-09-18 23:55:05 +00002278 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002279 QualType receiverType = RExpr->getType();
Steve Naroff3b950172007-10-10 21:53:07 +00002280 QualType returnType;
Steve Naroffdb611d52007-11-03 16:37:59 +00002281 ObjcMethodDecl *Method;
Steve Naroff3b950172007-10-10 21:53:07 +00002282
Steve Naroff7c249152007-11-11 17:52:25 +00002283 if (receiverType == Context.getObjcIdType() ||
2284 receiverType == Context.getObjcClassType()) {
Steve Naroffdb611d52007-11-03 16:37:59 +00002285 Method = InstanceMethodPool[Sel].Method;
Steve Naroffa56f6162007-12-18 01:30:32 +00002286 if (!Method)
2287 Method = FactoryMethodPool[Sel].Method;
Steve Naroff983df5b2007-10-16 20:39:36 +00002288 if (!Method) {
2289 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2290 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002291 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002292 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002293 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002294 if (Sel.getNumArgs())
2295 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2296 return true;
Steve Naroff983df5b2007-10-16 20:39:36 +00002297 }
Steve Naroff3b950172007-10-10 21:53:07 +00002298 } else {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002299 bool receiverIsQualId =
2300 dyn_cast<ObjcQualifiedIdType>(RExpr->getType()) != 0;
Chris Lattner22b73ba2007-10-10 23:42:28 +00002301 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2302 // revisited. how do we get the ClassDecl from the receiver expression?
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002303 if (!receiverIsQualId)
2304 while (receiverType->isPointerType()) {
2305 PointerType *pointerType =
2306 static_cast<PointerType*>(receiverType.getTypePtr());
2307 receiverType = pointerType->getPointeeType();
2308 }
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002309 ObjcInterfaceDecl* ClassDecl;
2310 if (ObjcQualifiedInterfaceType *QIT =
2311 dyn_cast<ObjcQualifiedInterfaceType>(receiverType)) {
Fariborz Jahanian06cef252007-12-13 20:47:42 +00002312 ClassDecl = QIT->getDecl();
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002313 Method = ClassDecl->lookupInstanceMethod(Sel);
2314 if (!Method) {
2315 // search protocols
2316 for (unsigned i = 0; i < QIT->getNumProtocols(); i++) {
2317 ObjcProtocolDecl *PDecl = QIT->getProtocols(i);
2318 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
2319 break;
2320 }
2321 }
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002322 if (!Method)
2323 Diag(lbrac, diag::warn_method_not_found_in_protocol,
2324 std::string("-"), Sel.getName(),
2325 SourceRange(lbrac, rbrac));
2326 }
2327 else if (ObjcQualifiedIdType *QIT =
2328 dyn_cast<ObjcQualifiedIdType>(receiverType)) {
2329 // search protocols
2330 for (unsigned i = 0; i < QIT->getNumProtocols(); i++) {
2331 ObjcProtocolDecl *PDecl = QIT->getProtocols(i);
2332 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
2333 break;
2334 }
2335 if (!Method)
2336 Diag(lbrac, diag::warn_method_not_found_in_protocol,
2337 std::string("-"), Sel.getName(),
2338 SourceRange(lbrac, rbrac));
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002339 }
2340 else {
2341 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2342 "bad receiver type");
2343 ClassDecl = static_cast<ObjcInterfaceType*>(
2344 receiverType.getTypePtr())->getDecl();
2345 // FIXME: consider using InstanceMethodPool, since it will be faster
2346 // than the following method (which can do *many* linear searches). The
2347 // idea is to add class info to InstanceMethodPool...
2348 Method = ClassDecl->lookupInstanceMethod(Sel);
2349 }
Steve Naroff983df5b2007-10-16 20:39:36 +00002350 if (!Method) {
Steve Naroffc43d8682007-11-11 00:10:47 +00002351 // If we have an implementation in scope, check "private" methods.
2352 if (ObjcImplementationDecl *ImpDecl =
2353 ObjcImplementations[ClassDecl->getIdentifier()])
Steve Naroff94a5c332007-12-19 22:27:04 +00002354 Method = ImpDecl->getInstanceMethod(Sel);
Steve Naroff9a4ad372007-12-11 03:38:03 +00002355 // If we still haven't found a method, look in the global pool. This
2356 // behavior isn't very desirable, however we need it for GCC compatibility.
Steve Naroff9feba022007-12-07 20:41:14 +00002357 if (!Method)
2358 Method = InstanceMethodPool[Sel].Method;
Steve Naroffc43d8682007-11-11 00:10:47 +00002359 }
2360 if (!Method) {
Steve Naroff983df5b2007-10-16 20:39:36 +00002361 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2362 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002363 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002364 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002365 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002366 if (Sel.getNumArgs())
2367 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2368 return true;
Steve Naroff983df5b2007-10-16 20:39:36 +00002369 }
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002370 }
Steve Naroffdb611d52007-11-03 16:37:59 +00002371 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
Steve Naroff49f109c2007-11-15 13:05:42 +00002372 ArgExprs, NumArgs);
Steve Naroff708391a2007-09-17 21:01:15 +00002373}