blob: 1d8b883435384999f5861460d670974700979f1d [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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"
27#include "llvm/ADT/SmallString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000028#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30
Steve Narofff69936d2007-09-16 03:34:24 +000031/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +000032/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
33/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
34/// multiple tokens. However, the common case is that StringToks points to one
35/// string.
36///
37Action::ExprResult
Steve Narofff69936d2007-09-16 03:34:24 +000038Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +000039 assert(NumStringToks && "Must have at least one string!");
40
41 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
42 if (Literal.hadError)
43 return ExprResult(true);
44
45 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
46 for (unsigned i = 0; i != NumStringToks; ++i)
47 StringTokLocs.push_back(StringToks[i].getLocation());
48
49 // FIXME: handle wchar_t
Anders Carlssonee98ac52007-10-15 02:50:23 +000050 QualType t;
51
52 if (Literal.Pascal)
53 t = Context.getPointerType(Context.UnsignedCharTy);
54 else
55 t = Context.getPointerType(Context.CharTy);
56
57 if (Literal.Pascal && Literal.GetStringLength() > 256)
58 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
59 SourceRange(StringToks[0].getLocation(),
60 StringToks[NumStringToks-1].getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +000061
62 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
63 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlssonee98ac52007-10-15 02:50:23 +000064 Literal.AnyWide, t,
65 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +000066 StringToks[NumStringToks-1].getLocation());
67}
68
69
Steve Naroff08d92e42007-09-15 18:49:24 +000070/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +000071/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
72/// identifier is used in an function call context.
Steve Naroff08d92e42007-09-15 18:49:24 +000073Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +000074 IdentifierInfo &II,
75 bool HasTrailingLParen) {
76 // Could be enum-constant or decl.
Steve Naroff8c9f13e2007-09-16 16:16:00 +000077 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Reid Spencer5f016e22007-07-11 17:01:13 +000078 if (D == 0) {
79 // Otherwise, this could be an implicitly declared function reference (legal
80 // in C90, extension in C99).
81 if (HasTrailingLParen &&
82 // Not in C++.
83 !getLangOptions().CPlusPlus)
84 D = ImplicitlyDefineFunction(Loc, II, S);
85 else {
Steve Naroff7779db42007-11-12 14:29:37 +000086 if (CurMethodDecl) {
87 ObjcInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
88 ObjcInterfaceDecl *clsDeclared;
Steve Naroff7e3411b2007-11-15 02:58:25 +000089 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
90 IdentifierInfo &II = Context.Idents.get("self");
91 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
92 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
93 static_cast<Expr*>(SelfExpr.Val), true, true);
94 }
Steve Naroff7779db42007-11-12 14:29:37 +000095 }
Reid Spencer5f016e22007-07-11 17:01:13 +000096 // If this name wasn't predeclared and if this is not a function call,
97 // diagnose the problem.
98 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
99 }
100 }
Steve Naroffe1223f72007-08-28 03:03:08 +0000101 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroff53a32342007-08-28 18:45:29 +0000102 // Only create DeclRefExpr's for valid Decl's.
Steve Naroff5912a352007-08-28 20:14:24 +0000103 if (VD->isInvalidDecl())
Steve Naroffe1223f72007-08-28 03:03:08 +0000104 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000105 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroffe1223f72007-08-28 03:03:08 +0000106 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 if (isa<TypedefDecl>(D))
108 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Fariborz Jahanian5ef404f2007-12-05 18:16:33 +0000109 if (isa<ObjcInterfaceDecl>(D))
110 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000111
112 assert(0 && "Invalid decl");
Chris Lattnereddbe032007-07-21 04:57:45 +0000113 abort();
Reid Spencer5f016e22007-07-11 17:01:13 +0000114}
115
Steve Narofff69936d2007-09-16 03:34:24 +0000116Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000117 tok::TokenKind Kind) {
118 PreDefinedExpr::IdentType IT;
119
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 switch (Kind) {
121 default:
122 assert(0 && "Unknown simple primary expr!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
Anders Carlsson22742662007-07-21 05:21:51 +0000124 IT = PreDefinedExpr::Func;
125 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000126 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000127 IT = PreDefinedExpr::Function;
128 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000129 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000130 IT = PreDefinedExpr::PrettyFunction;
131 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 }
Anders Carlsson22742662007-07-21 05:21:51 +0000133
134 // Pre-defined identifiers are always of type char *.
135 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000136}
137
Steve Narofff69936d2007-09-16 03:34:24 +0000138Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000139 llvm::SmallString<16> CharBuffer;
140 CharBuffer.resize(Tok.getLength());
141 const char *ThisTokBegin = &CharBuffer[0];
142 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
143
144 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
145 Tok.getLocation(), PP);
146 if (Literal.hadError())
147 return ExprResult(true);
148 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
149 Tok.getLocation());
150}
151
Steve Narofff69936d2007-09-16 03:34:24 +0000152Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 // fast path for a single digit (which is quite common). A single digit
154 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
155 if (Tok.getLength() == 1) {
156 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
157
Chris Lattner701e5eb2007-09-04 02:45:27 +0000158 unsigned IntSize = static_cast<unsigned>(
159 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000160 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
161 Context.IntTy,
162 Tok.getLocation()));
163 }
164 llvm::SmallString<512> IntegerBuffer;
165 IntegerBuffer.resize(Tok.getLength());
166 const char *ThisTokBegin = &IntegerBuffer[0];
167
168 // Get the spelling of the token, which eliminates trigraphs, etc.
169 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
170 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
171 Tok.getLocation(), PP);
172 if (Literal.hadError)
173 return ExprResult(true);
174
Chris Lattner5d661452007-08-26 03:42:43 +0000175 Expr *Res;
176
177 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000178 QualType Ty;
179 const llvm::fltSemantics *Format;
180 uint64_t Size; unsigned Align;
181
182 if (Literal.isFloat) {
183 Ty = Context.FloatTy;
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000184 Context.Target.getFloatInfo(Size, Align, Format,
185 Context.getFullLoc(Tok.getLocation()));
186
Chris Lattner525a0502007-09-22 18:29:59 +0000187 } else if (Literal.isLong) {
188 Ty = Context.LongDoubleTy;
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000189 Context.Target.getLongDoubleInfo(Size, Align, Format,
190 Context.getFullLoc(Tok.getLocation()));
Chris Lattner525a0502007-09-22 18:29:59 +0000191 } else {
192 Ty = Context.DoubleTy;
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000193 Context.Target.getDoubleInfo(Size, Align, Format,
194 Context.getFullLoc(Tok.getLocation()));
Chris Lattner525a0502007-09-22 18:29:59 +0000195 }
196
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000197 // isExact will be set by GetFloatValue().
198 bool isExact = false;
199
200 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
201 Ty, Tok.getLocation());
202
Chris Lattner5d661452007-08-26 03:42:43 +0000203 } else if (!Literal.isIntegerLiteral()) {
204 return ExprResult(true);
205 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 QualType t;
207
Neil Boothb9449512007-08-29 22:00:19 +0000208 // long long is a C99 feature.
209 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000210 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000211 Diag(Tok.getLocation(), diag::ext_longlong);
212
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 // Get the value in the widest-possible width.
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000214 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(
215 Context.getFullLoc(Tok.getLocation())), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000216
217 if (Literal.GetIntegerValue(ResultVal)) {
218 // If this value didn't fit into uintmax_t, warn and force to ull.
219 Diag(Tok.getLocation(), diag::warn_integer_too_large);
220 t = Context.UnsignedLongLongTy;
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000221 assert(Context.getTypeSize(t, Tok.getLocation()) ==
Reid Spencer5f016e22007-07-11 17:01:13 +0000222 ResultVal.getBitWidth() && "long long is not intmax_t?");
223 } else {
224 // If this value fits into a ULL, try to figure out what else it fits into
225 // according to the rules of C99 6.4.4.1p5.
226
227 // Octal, Hexadecimal, and integers with a U suffix are allowed to
228 // be an unsigned int.
229 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
230
231 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner97c51562007-08-23 21:58:08 +0000232 if (!Literal.isLong && !Literal.isLongLong) {
233 // Are int/unsigned possibilities?
Chris Lattner701e5eb2007-09-04 02:45:27 +0000234 unsigned IntSize = static_cast<unsigned>(
235 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000236 // Does it fit in a unsigned int?
237 if (ResultVal.isIntN(IntSize)) {
238 // Does it fit in a signed int?
239 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
240 t = Context.IntTy;
241 else if (AllowUnsigned)
242 t = Context.UnsignedIntTy;
243 }
244
245 if (!t.isNull())
246 ResultVal.trunc(IntSize);
247 }
248
249 // Are long/unsigned long possibilities?
250 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner701e5eb2007-09-04 02:45:27 +0000251 unsigned LongSize = static_cast<unsigned>(
252 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000253
254 // Does it fit in a unsigned long?
255 if (ResultVal.isIntN(LongSize)) {
256 // Does it fit in a signed long?
257 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
258 t = Context.LongTy;
259 else if (AllowUnsigned)
260 t = Context.UnsignedLongTy;
261 }
262 if (!t.isNull())
263 ResultVal.trunc(LongSize);
264 }
265
266 // Finally, check long long if needed.
267 if (t.isNull()) {
Chris Lattner701e5eb2007-09-04 02:45:27 +0000268 unsigned LongLongSize = static_cast<unsigned>(
269 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000270
271 // Does it fit in a unsigned long long?
272 if (ResultVal.isIntN(LongLongSize)) {
273 // Does it fit in a signed long long?
274 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
275 t = Context.LongLongTy;
276 else if (AllowUnsigned)
277 t = Context.UnsignedLongLongTy;
278 }
279 }
280
281 // If we still couldn't decide a type, we probably have something that
282 // does not fit in a signed long long, but has no U suffix.
283 if (t.isNull()) {
284 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
285 t = Context.UnsignedLongLongTy;
286 }
287 }
288
Chris Lattner5d661452007-08-26 03:42:43 +0000289 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000290 }
Chris Lattner5d661452007-08-26 03:42:43 +0000291
292 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
293 if (Literal.isImaginary)
294 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
295
296 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000297}
298
Steve Narofff69936d2007-09-16 03:34:24 +0000299Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 ExprTy *Val) {
301 Expr *e = (Expr *)Val;
Steve Narofff69936d2007-09-16 03:34:24 +0000302 assert((e != 0) && "ActOnParenExpr() missing expr");
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 return new ParenExpr(L, R, e);
304}
305
306/// The UsualUnaryConversions() function is *not* called by this routine.
307/// See C99 6.3.2.1p[2-4] for more details.
308QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
309 SourceLocation OpLoc, bool isSizeof) {
310 // C99 6.5.3.4p1:
311 if (isa<FunctionType>(exprType) && isSizeof)
312 // alignof(function) is allowed.
313 Diag(OpLoc, diag::ext_sizeof_function_type);
314 else if (exprType->isVoidType())
315 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
316 else if (exprType->isIncompleteType()) {
317 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
318 diag::err_alignof_incomplete_type,
319 exprType.getAsString());
320 return QualType(); // error
321 }
322 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
323 return Context.getSizeType();
324}
325
326Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000327ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +0000328 SourceLocation LPLoc, TypeTy *Ty,
329 SourceLocation RPLoc) {
330 // If error parsing type, ignore.
331 if (Ty == 0) return true;
332
333 // Verify that this is a valid expression.
334 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
335
336 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
337
338 if (resultType.isNull())
339 return true;
340 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
341}
342
Chris Lattner5d794252007-08-24 21:41:10 +0000343QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000344 DefaultFunctionArrayConversion(V);
345
Chris Lattnercc26ed72007-08-26 05:39:26 +0000346 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000347 if (const ComplexType *CT = V->getType()->getAsComplexType())
348 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000349
350 // Otherwise they pass through real integer and floating point types here.
351 if (V->getType()->isArithmeticType())
352 return V->getType();
353
354 // Reject anything else.
355 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
356 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000357}
358
359
Reid Spencer5f016e22007-07-11 17:01:13 +0000360
Steve Narofff69936d2007-09-16 03:34:24 +0000361Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 tok::TokenKind Kind,
363 ExprTy *Input) {
364 UnaryOperator::Opcode Opc;
365 switch (Kind) {
366 default: assert(0 && "Unknown unary op!");
367 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
368 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
369 }
370 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
371 if (result.isNull())
372 return true;
373 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
374}
375
376Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000377ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000379 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000380
381 // Perform default conversions.
382 DefaultFunctionArrayConversion(LHSExp);
383 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000384
Chris Lattner12d9ff62007-07-16 00:14:47 +0000385 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000386
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000388 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 // in the subscript position. As a result, we need to derive the array base
390 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000391 Expr *BaseExpr, *IndexExpr;
392 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000393 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000394 BaseExpr = LHSExp;
395 IndexExpr = RHSExp;
396 // FIXME: need to deal with const...
397 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000398 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000399 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000400 BaseExpr = RHSExp;
401 IndexExpr = LHSExp;
402 // FIXME: need to deal with const...
403 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000404 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
405 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000406 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000407
408 // Component access limited to variables (reject vec4.rg[1]).
409 if (!isa<DeclRefExpr>(BaseExpr))
410 return Diag(LLoc, diag::err_ocuvector_component_access,
411 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000412 // FIXME: need to deal with const...
413 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000415 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
416 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 }
418 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000419 if (!IndexExpr->getType()->isIntegerType())
420 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
421 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000422
Chris Lattner12d9ff62007-07-16 00:14:47 +0000423 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
424 // the following check catches trying to index a pointer to a function (e.g.
425 // void (*)(int)). Functions are not objects in C99.
426 if (!ResultType->isObjectType())
427 return Diag(BaseExpr->getLocStart(),
428 diag::err_typecheck_subscript_not_object,
429 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
430
431 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000432}
433
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000434QualType Sema::
435CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
436 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnerc8629632007-07-31 19:29:30 +0000437 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000438
439 // The vector accessor can't exceed the number of elements.
440 const char *compStr = CompName.getName();
441 if (strlen(compStr) > vecType->getNumElements()) {
442 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
443 baseType.getAsString(), SourceRange(CompLoc));
444 return QualType();
445 }
446 // The component names must come from the same set.
Chris Lattner88dca042007-08-02 22:33:49 +0000447 if (vecType->getPointAccessorIdx(*compStr) != -1) {
448 do
449 compStr++;
450 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
451 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
452 do
453 compStr++;
454 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
455 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
456 do
457 compStr++;
458 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
459 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000460
461 if (*compStr) {
462 // We didn't get to the end of the string. This means the component names
463 // didn't come from the same set *or* we encountered an illegal name.
464 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
465 std::string(compStr,compStr+1), SourceRange(CompLoc));
466 return QualType();
467 }
468 // Each component accessor can't exceed the vector type.
469 compStr = CompName.getName();
470 while (*compStr) {
471 if (vecType->isAccessorWithinNumElements(*compStr))
472 compStr++;
473 else
474 break;
475 }
476 if (*compStr) {
477 // We didn't get to the end of the string. This means a component accessor
478 // exceeds the number of elements in the vector.
479 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
480 baseType.getAsString(), SourceRange(CompLoc));
481 return QualType();
482 }
483 // The component accessor looks fine - now we need to compute the actual type.
484 // The vector type is implied by the component accessor. For example,
485 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
486 unsigned CompSize = strlen(CompName.getName());
487 if (CompSize == 1)
488 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000489
490 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
491 // Now look up the TypeDefDecl from the vector type. Without this,
492 // diagostics look bad. We want OCU vector types to appear built-in.
493 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
494 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
495 return Context.getTypedefType(OCUVectorDecls[i]);
496 }
497 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000498}
499
Reid Spencer5f016e22007-07-11 17:01:13 +0000500Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000501ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000502 tok::TokenKind OpKind, SourceLocation MemberLoc,
503 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000504 Expr *BaseExpr = static_cast<Expr *>(Base);
505 assert(BaseExpr && "no record expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000506
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000507 QualType BaseType = BaseExpr->getType();
508 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000509
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000511 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000512 BaseType = PT->getPointeeType();
513 else
514 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
515 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000516 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000517 // The base type is either a record or an OCUVectorType.
Chris Lattnerc8629632007-07-31 19:29:30 +0000518 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000519 RecordDecl *RDecl = RTy->getDecl();
520 if (RTy->isIncompleteType())
521 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
522 BaseExpr->getSourceRange());
523 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000524 FieldDecl *MemberDecl = RDecl->getMember(&Member);
525 if (!MemberDecl)
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000526 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
527 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000528 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
529 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff608e0ee2007-08-03 22:40:33 +0000530 // Component access limited to variables (reject vec4.rg.g).
531 if (!isa<DeclRefExpr>(BaseExpr))
532 return Diag(OpLoc, diag::err_ocuvector_component_access,
533 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000534 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
535 if (ret.isNull())
536 return true;
Chris Lattner6481a572007-08-03 17:31:20 +0000537 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000538 } else if (BaseType->isObjcInterfaceType()) {
539 ObjcInterfaceDecl *IFace;
540 if (isa<ObjcInterfaceType>(BaseType.getCanonicalType()))
541 IFace = dyn_cast<ObjcInterfaceType>(BaseType)->getDecl();
542 else
Fariborz Jahanian06cef252007-12-13 20:47:42 +0000543 IFace = dyn_cast<ObjcQualifiedInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000544 ObjcInterfaceDecl *clsDeclared;
545 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
546 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
547 OpKind==tok::arrow);
548 }
549 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
550 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000551}
552
Steve Narofff69936d2007-09-16 03:34:24 +0000553/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +0000554/// This provides the location of the left/right parens and a list of comma
555/// locations.
556Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000557ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner74c469f2007-07-21 03:03:59 +0000558 ExprTy **args, unsigned NumArgsInCall,
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000560 Expr *Fn = static_cast<Expr *>(fn);
561 Expr **Args = reinterpret_cast<Expr**>(args);
562 assert(Fn && "no function call expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000563
Chris Lattner74c469f2007-07-21 03:03:59 +0000564 UsualUnaryConversions(Fn);
565 QualType funcType = Fn->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000566
567 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
568 // type pointer to function".
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000569 const PointerType *PT = funcType->getAsPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000570 if (PT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000571 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
572 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000573
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000574 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000575 if (funcT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000576 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
577 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000578
579 // If a prototype isn't declared, the parser implicitly defines a func decl
580 QualType resultType = funcT->getResultType();
581
582 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
583 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
584 // assignment, to the types of the corresponding parameter, ...
585
586 unsigned NumArgsInProto = proto->getNumArgs();
587 unsigned NumArgsToCheck = NumArgsInCall;
588
589 if (NumArgsInCall < NumArgsInProto)
590 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
Chris Lattner74c469f2007-07-21 03:03:59 +0000591 Fn->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000592 else if (NumArgsInCall > NumArgsInProto) {
593 if (!proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +0000594 Diag(Args[NumArgsInProto]->getLocStart(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000595 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +0000596 SourceRange(Args[NumArgsInProto]->getLocStart(),
597 Args[NumArgsInCall-1]->getLocEnd()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000598 }
599 NumArgsToCheck = NumArgsInProto;
600 }
601 // Continue to check argument types (even if we have too few/many args).
602 for (unsigned i = 0; i < NumArgsToCheck; i++) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000603 Expr *argExpr = Args[i];
Steve Narofff69936d2007-09-16 03:34:24 +0000604 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000605
606 QualType lhsType = proto->getArgType(i);
607 QualType rhsType = argExpr->getType();
Steve Naroff700204c2007-07-24 21:46:40 +0000608
Steve Naroff82c7e6d2007-07-25 20:45:33 +0000609 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnerc8629632007-07-31 19:29:30 +0000610 if (const ArrayType *ary = lhsType->getAsArrayType())
Steve Naroff700204c2007-07-24 21:46:40 +0000611 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff82c7e6d2007-07-25 20:45:33 +0000612 else if (lhsType->isFunctionType())
Steve Naroff700204c2007-07-24 21:46:40 +0000613 lhsType = Context.getPointerType(lhsType);
614
Steve Naroff90045e82007-07-13 23:32:42 +0000615 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
616 argExpr);
Steve Narofff1120de2007-08-24 22:33:52 +0000617 if (Args[i] != argExpr) // The expression was converted.
618 Args[i] = argExpr; // Make sure we store the converted expression.
Reid Spencer5f016e22007-07-11 17:01:13 +0000619 SourceLocation l = argExpr->getLocStart();
620
621 // decode the result (notice that AST's are still created for extensions).
622 switch (result) {
623 case Compatible:
624 break;
625 case PointerFromInt:
Steve Naroff529a4ad2007-11-27 17:58:44 +0000626 Diag(l, diag::ext_typecheck_passing_pointer_int,
627 lhsType.getAsString(), rhsType.getAsString(),
628 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000629 break;
630 case IntFromPointer:
631 Diag(l, diag::ext_typecheck_passing_pointer_int,
632 lhsType.getAsString(), rhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000633 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000634 break;
635 case IncompatiblePointer:
636 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
637 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000638 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000639 break;
640 case CompatiblePointerDiscardsQualifiers:
641 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
642 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000643 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000644 break;
645 case Incompatible:
646 return Diag(l, diag::err_typecheck_passing_incompatible,
647 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000648 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000649 }
650 }
Steve Naroffb291ab62007-08-28 23:30:39 +0000651 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
652 // Promote the arguments (C99 6.5.2.2p7).
653 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
654 Expr *argExpr = Args[i];
Steve Narofff69936d2007-09-16 03:34:24 +0000655 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffb291ab62007-08-28 23:30:39 +0000656
657 DefaultArgumentPromotion(argExpr);
658 if (Args[i] != argExpr) // The expression was converted.
659 Args[i] = argExpr; // Make sure we store the converted expression.
660 }
661 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
662 // Even if the types checked, bail if the number of arguments don't match.
Reid Spencer5f016e22007-07-11 17:01:13 +0000663 return true;
Steve Naroffb291ab62007-08-28 23:30:39 +0000664 }
665 } else if (isa<FunctionTypeNoProto>(funcT)) {
666 // Promote the arguments (C99 6.5.2.2p6).
667 for (unsigned i = 0; i < NumArgsInCall; i++) {
668 Expr *argExpr = Args[i];
Steve Narofff69936d2007-09-16 03:34:24 +0000669 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffb291ab62007-08-28 23:30:39 +0000670
671 DefaultArgumentPromotion(argExpr);
672 if (Args[i] != argExpr) // The expression was converted.
673 Args[i] = argExpr; // Make sure we store the converted expression.
674 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000675 }
Chris Lattner59907c42007-08-10 20:18:51 +0000676 // Do special checking on direct calls to functions.
677 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
678 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
679 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000680 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
681 NumArgsInCall))
Anders Carlsson71993dd2007-08-17 05:31:46 +0000682 return true;
Chris Lattner59907c42007-08-10 20:18:51 +0000683
Chris Lattner74c469f2007-07-21 03:03:59 +0000684 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000685}
686
687Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000688ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +0000689 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +0000690 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +0000691 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +0000692 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +0000693 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +0000694 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +0000695
Steve Naroff2fdc3742007-12-10 22:44:33 +0000696 // FIXME: add more semantic analysis (C99 6.5.2.5).
697 if (CheckInitializer(literalExpr, literalType, false))
698 return 0;
Anders Carlssond35c8322007-12-05 07:24:19 +0000699
Steve Naroffaff1edd2007-07-19 21:32:11 +0000700 return new CompoundLiteralExpr(literalType, literalExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000701}
702
703Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000704ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000705 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +0000706 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000707
Steve Naroff08d92e42007-09-15 18:49:24 +0000708 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +0000709 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000710
Steve Naroff38374b02007-09-02 20:30:18 +0000711 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
712 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
713 return e;
Steve Naroff4aa88f82007-07-19 01:06:55 +0000714}
715
Anders Carlssona64db8f2007-11-27 05:51:55 +0000716bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty)
717{
718 assert(VectorTy->isVectorType() && "Not a vector type!");
719
720 if (Ty->isVectorType() || Ty->isIntegerType()) {
721 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
722 Context.getTypeSize(Ty, SourceLocation()))
723 return Diag(R.getBegin(),
724 Ty->isVectorType() ?
725 diag::err_invalid_conversion_between_vectors :
726 diag::err_invalid_conversion_between_vector_and_integer,
727 VectorTy.getAsString().c_str(),
728 Ty.getAsString().c_str(), R);
729 } else
730 return Diag(R.getBegin(),
731 diag::err_invalid_conversion_between_vector_and_scalar,
732 VectorTy.getAsString().c_str(),
733 Ty.getAsString().c_str(), R);
734
735 return false;
736}
737
Steve Naroff4aa88f82007-07-19 01:06:55 +0000738Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000739ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +0000740 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +0000741 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +0000742
743 Expr *castExpr = static_cast<Expr*>(Op);
744 QualType castType = QualType::getFromOpaquePtr(Ty);
745
Steve Naroff711602b2007-08-31 00:32:44 +0000746 UsualUnaryConversions(castExpr);
747
Chris Lattner75af4802007-07-18 16:00:06 +0000748 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
749 // type needs to be scalar.
Chris Lattner3da2db42007-10-29 04:26:44 +0000750 if (!castType->isVoidType()) { // Cast to void allows any expr type.
751 if (!castType->isScalarType())
752 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
753 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Anders Carlssona64db8f2007-11-27 05:51:55 +0000754 if (!castExpr->getType()->isScalarType())
Chris Lattner3da2db42007-10-29 04:26:44 +0000755 return Diag(castExpr->getLocStart(),
756 diag::err_typecheck_expect_scalar_operand,
757 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssona64db8f2007-11-27 05:51:55 +0000758
759 if (castExpr->getType()->isVectorType()) {
760 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
761 castExpr->getType(), castType))
762 return true;
763 } else if (castType->isVectorType()) {
764 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
765 castType, castExpr->getType()))
766 return true;
Chris Lattner3da2db42007-10-29 04:26:44 +0000767 }
Steve Naroff16beff82007-07-16 23:25:18 +0000768 }
769 return new CastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000770}
771
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000772// promoteExprToType - a helper function to ensure we create exactly one
773// ImplicitCastExpr.
774static void promoteExprToType(Expr *&expr, QualType type) {
775 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
776 impCast->setType(type);
777 else
778 expr = new ImplicitCastExpr(type, expr);
779 return;
780}
781
Chris Lattnera21ddb32007-11-26 01:40:58 +0000782/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
783/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +0000784inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +0000785 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000786 UsualUnaryConversions(cond);
787 UsualUnaryConversions(lex);
788 UsualUnaryConversions(rex);
789 QualType condT = cond->getType();
790 QualType lexT = lex->getType();
791 QualType rexT = rex->getType();
792
Reid Spencer5f016e22007-07-11 17:01:13 +0000793 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +0000794 if (!condT->isScalarType()) { // C99 6.5.15p2
795 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
796 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +0000797 return QualType();
798 }
799 // now check the two expressions.
Steve Naroffa4332e22007-07-17 00:58:39 +0000800 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
801 UsualArithmeticConversions(lex, rex);
802 return lex->getType();
803 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000804 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
805 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
Chris Lattnera21ddb32007-11-26 01:40:58 +0000806 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000807 return lexT;
808
Reid Spencer5f016e22007-07-11 17:01:13 +0000809 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000810 lexT.getAsString(), rexT.getAsString(),
811 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000812 return QualType();
813 }
814 }
Chris Lattner590b6642007-07-15 23:26:56 +0000815 // C99 6.5.15p3
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000816 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
817 promoteExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff49b45262007-07-13 16:58:59 +0000818 return lexT;
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000819 }
820 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
821 promoteExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff49b45262007-07-13 16:58:59 +0000822 return rexT;
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000823 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000824 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
825 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
826 // get the "pointed to" types
827 QualType lhptee = LHSPT->getPointeeType();
828 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000829
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000830 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
831 if (lhptee->isVoidType() &&
832 (rhptee->isObjectType() || rhptee->isIncompleteType()))
833 return lexT;
834 if (rhptee->isVoidType() &&
835 (lhptee->isObjectType() || lhptee->isIncompleteType()))
836 return rexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000837
Steve Naroffec0550f2007-10-15 20:41:53 +0000838 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
839 rhptee.getUnqualifiedType())) {
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000840 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
841 lexT.getAsString(), rexT.getAsString(),
842 lex->getSourceRange(), rex->getSourceRange());
843 return lexT; // FIXME: this is an _ext - is this return o.k?
844 }
845 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000846 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
847 // differently qualified versions of compatible types, the result type is
848 // a pointer to an appropriately qualified version of the *composite*
849 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000850 return lexT; // FIXME: Need to return the composite type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000851 }
852 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000853
Steve Naroff49b45262007-07-13 16:58:59 +0000854 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
855 return lexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000856
857 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000858 lexT.getAsString(), rexT.getAsString(),
859 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000860 return QualType();
861}
862
Steve Narofff69936d2007-09-16 03:34:24 +0000863/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +0000864/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +0000865Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000866 SourceLocation ColonLoc,
867 ExprTy *Cond, ExprTy *LHS,
868 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +0000869 Expr *CondExpr = (Expr *) Cond;
870 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +0000871
872 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
873 // was the condition.
874 bool isLHSNull = LHSExpr == 0;
875 if (isLHSNull)
876 LHSExpr = CondExpr;
877
Chris Lattner26824902007-07-16 21:39:03 +0000878 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
879 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000880 if (result.isNull())
881 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +0000882 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
883 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000884}
885
Steve Naroffb291ab62007-08-28 23:30:39 +0000886/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
887/// do not have a prototype. Integer promotions are performed on each
888/// argument, and arguments that have type float are promoted to double.
889void Sema::DefaultArgumentPromotion(Expr *&expr) {
890 QualType t = expr->getType();
891 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
892
893 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
894 promoteExprToType(expr, Context.IntTy);
895 if (t == Context.FloatTy)
896 promoteExprToType(expr, Context.DoubleTy);
897}
898
Steve Narofffa2eaab2007-07-15 02:02:06 +0000899/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000900void Sema::DefaultFunctionArrayConversion(Expr *&e) {
Steve Narofffa2eaab2007-07-15 02:02:06 +0000901 QualType t = e->getType();
Steve Naroff90045e82007-07-13 23:32:42 +0000902 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
Bill Wendling08ad47c2007-07-17 03:52:31 +0000903
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000904 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000905 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
906 t = e->getType();
907 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000908 if (t->isFunctionType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000909 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnerc8629632007-07-31 19:29:30 +0000910 else if (const ArrayType *ary = t->getAsArrayType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000911 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000912}
913
914/// UsualUnaryConversion - Performs various conversions that are common to most
915/// operators (C99 6.3). The conversions of array and function types are
916/// sometimes surpressed. For example, the array->pointer conversion doesn't
917/// apply if the array is an argument to the sizeof or address (&) operators.
918/// In these instances, this routine should *not* be called.
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000919void Sema::UsualUnaryConversions(Expr *&expr) {
Steve Naroff49b45262007-07-13 16:58:59 +0000920 QualType t = expr->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000921 assert(!t.isNull() && "UsualUnaryConversions - missing type");
922
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000923 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000924 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
925 t = expr->getType();
926 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000927 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000928 promoteExprToType(expr, Context.IntTy);
929 else
930 DefaultFunctionArrayConversion(expr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000931}
932
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000933/// UsualArithmeticConversions - Performs various conversions that are common to
Reid Spencer5f016e22007-07-11 17:01:13 +0000934/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
935/// routine returns the first non-arithmetic type found. The client is
936/// responsible for emitting appropriate error diagnostics.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000937QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
938 bool isCompAssign) {
Steve Naroff8702a0f2007-08-25 19:54:59 +0000939 if (!isCompAssign) {
940 UsualUnaryConversions(lhsExpr);
941 UsualUnaryConversions(rhsExpr);
942 }
Steve Naroff3187e202007-10-18 18:55:53 +0000943 // For conversion purposes, we ignore any qualifiers.
944 // For example, "const float" and "float" are equivalent.
Steve Narofff68a63f2007-11-10 19:45:54 +0000945 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
946 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000947
948 // If both types are identical, no conversion is needed.
Steve Naroff3187e202007-10-18 18:55:53 +0000949 if (lhs == rhs)
950 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000951
952 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
953 // The caller can deal with this (e.g. pointer + int).
Steve Naroffa4332e22007-07-17 00:58:39 +0000954 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000955 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000956
957 // At this point, we have two different arithmetic types.
958
959 // Handle complex types first (C99 6.3.1.8p1).
960 if (lhs->isComplexType() || rhs->isComplexType()) {
961 // if we have an integer operand, the result is the complex type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000962 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000963 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
964 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000965 }
966 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000967 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
968 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000969 }
Steve Narofff1448a02007-08-27 01:27:54 +0000970 // This handles complex/complex, complex/float, or float/complex.
971 // When both operands are complex, the shorter operand is converted to the
972 // type of the longer, and that is the type of the result. This corresponds
973 // to what is done when combining two real floating-point operands.
974 // The fun begins when size promotion occur across type domains.
975 // From H&S 6.3.4: When one operand is complex and the other is a real
976 // floating-point type, the less precise type is converted, within it's
977 // real or complex domain, to the precision of the other type. For example,
978 // when combining a "long double" with a "double _Complex", the
979 // "double _Complex" is promoted to "long double _Complex".
Steve Narofffb0d4962007-08-27 15:30:22 +0000980 int result = Context.compareFloatingType(lhs, rhs);
981
982 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff55fe4552007-08-27 21:32:55 +0000983 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
984 if (!isCompAssign)
985 promoteExprToType(rhsExpr, rhs);
986 } else if (result < 0) { // The right side is bigger, convert lhs.
987 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
988 if (!isCompAssign)
989 promoteExprToType(lhsExpr, lhs);
990 }
991 // At this point, lhs and rhs have the same rank/size. Now, make sure the
992 // domains match. This is a requirement for our implementation, C99
993 // does not require this promotion.
994 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
995 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff29960362007-08-27 21:43:43 +0000996 if (!isCompAssign)
997 promoteExprToType(lhsExpr, rhs);
998 return rhs;
Steve Naroff55fe4552007-08-27 21:32:55 +0000999 } else { // handle "_Complex double, double".
Steve Naroff29960362007-08-27 21:43:43 +00001000 if (!isCompAssign)
1001 promoteExprToType(rhsExpr, lhs);
1002 return lhs;
Steve Naroff55fe4552007-08-27 21:32:55 +00001003 }
Steve Naroffa4332e22007-07-17 00:58:39 +00001004 }
Steve Naroff29960362007-08-27 21:43:43 +00001005 return lhs; // The domain/size match exactly.
Reid Spencer5f016e22007-07-11 17:01:13 +00001006 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001007 // Now handle "real" floating types (i.e. float, double, long double).
1008 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1009 // if we have an integer operand, the result is the real floating type.
Steve Naroffa4332e22007-07-17 00:58:39 +00001010 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001011 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1012 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001013 }
1014 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001015 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
1016 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001017 }
Steve Narofffa2eaab2007-07-15 02:02:06 +00001018 // We have two real floating types, float/complex combos were handled above.
1019 // Convert the smaller operand to the bigger result.
Steve Narofffb0d4962007-08-27 15:30:22 +00001020 int result = Context.compareFloatingType(lhs, rhs);
1021
1022 if (result > 0) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001023 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1024 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001025 }
Steve Narofffb0d4962007-08-27 15:30:22 +00001026 if (result < 0) { // convert the lhs
1027 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1028 return rhs;
1029 }
1030 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Reid Spencer5f016e22007-07-11 17:01:13 +00001031 }
Steve Narofffa2eaab2007-07-15 02:02:06 +00001032 // Finally, we have two differing integer types.
Steve Naroffa4332e22007-07-17 00:58:39 +00001033 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001034 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1035 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001036 }
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001037 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1038 return rhs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001039}
1040
1041// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1042// being closely modeled after the C99 spec:-). The odd characteristic of this
1043// routine is it effectively iqnores the qualifiers on the top level pointee.
1044// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1045// FIXME: add a couple examples in this comment.
1046Sema::AssignmentCheckResult
1047Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1048 QualType lhptee, rhptee;
1049
1050 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001051 lhptee = lhsType->getAsPointerType()->getPointeeType();
1052 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001053
1054 // make sure we operate on the canonical type
1055 lhptee = lhptee.getCanonicalType();
1056 rhptee = rhptee.getCanonicalType();
1057
1058 AssignmentCheckResult r = Compatible;
1059
1060 // C99 6.5.16.1p1: This following citation is common to constraints
1061 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1062 // qualifiers of the type *pointed to* by the right;
1063 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1064 rhptee.getQualifiers())
1065 r = CompatiblePointerDiscardsQualifiers;
1066
1067 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1068 // incomplete type and the other is a pointer to a qualified or unqualified
1069 // version of void...
1070 if (lhptee.getUnqualifiedType()->isVoidType() &&
1071 (rhptee->isObjectType() || rhptee->isIncompleteType()))
1072 ;
1073 else if (rhptee.getUnqualifiedType()->isVoidType() &&
1074 (lhptee->isObjectType() || lhptee->isIncompleteType()))
1075 ;
1076 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1077 // unqualified versions of compatible types, ...
Steve Naroffec0550f2007-10-15 20:41:53 +00001078 else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1079 rhptee.getUnqualifiedType()))
Reid Spencer5f016e22007-07-11 17:01:13 +00001080 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1081 return r;
1082}
1083
1084/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1085/// has code to accommodate several GCC extensions when type checking
1086/// pointers. Here are some objectionable examples that GCC considers warnings:
1087///
1088/// int a, *pint;
1089/// short *pshort;
1090/// struct foo *pfoo;
1091///
1092/// pint = pshort; // warning: assignment from incompatible pointer type
1093/// a = pint; // warning: assignment makes integer from pointer without a cast
1094/// pint = a; // warning: assignment makes pointer from integer without a cast
1095/// pint = pfoo; // warning: assignment from incompatible pointer type
1096///
1097/// As a result, the code for dealing with pointers is more complex than the
1098/// C99 spec dictates.
1099/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1100///
1101Sema::AssignmentCheckResult
1102Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Steve Naroff8eabdff2007-11-13 00:31:42 +00001103 if (lhsType.getCanonicalType().getUnqualifiedType() ==
1104 rhsType.getCanonicalType().getUnqualifiedType())
Chris Lattner84d35ce2007-10-29 05:15:40 +00001105 return Compatible; // common case, fast path...
Steve Naroff700204c2007-07-24 21:46:40 +00001106
Anders Carlsson793680e2007-10-12 23:56:29 +00001107 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroffec0550f2007-10-15 20:41:53 +00001108 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001109 return Compatible;
1110 } else if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001111 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Anders Carlsson695dbb62007-11-30 04:21:22 +00001112 if (!getLangOptions().LaxVectorConversions) {
1113 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1114 return Incompatible;
1115 } else {
1116 if (lhsType->isVectorType() && rhsType->isVectorType()) {
1117 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1118 (lhsType->isRealFloatingType() &&
1119 rhsType->isRealFloatingType())) {
1120 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1121 Context.getTypeSize(rhsType, SourceLocation()))
1122 return Compatible;
1123 }
1124 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001125 return Incompatible;
Anders Carlsson695dbb62007-11-30 04:21:22 +00001126 }
1127 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001128 return Compatible;
1129 } else if (lhsType->isPointerType()) {
1130 if (rhsType->isIntegerType())
1131 return PointerFromInt;
1132
1133 if (rhsType->isPointerType())
1134 return CheckPointerTypesForAssignment(lhsType, rhsType);
1135 } else if (rhsType->isPointerType()) {
1136 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1137 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1138 return IntFromPointer;
1139
1140 if (lhsType->isPointerType())
1141 return CheckPointerTypesForAssignment(lhsType, rhsType);
1142 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroffec0550f2007-10-15 20:41:53 +00001143 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001144 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 }
1146 return Incompatible;
1147}
1148
Steve Naroff90045e82007-07-13 23:32:42 +00001149Sema::AssignmentCheckResult
1150Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroff529a4ad2007-11-27 17:58:44 +00001151 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1152 // a null pointer constant.
1153 if (lhsType->isPointerType() && rExpr->isNullPointerConstant(Context)) {
1154 promoteExprToType(rExpr, lhsType);
1155 return Compatible;
1156 }
Chris Lattner943140e2007-10-16 02:55:40 +00001157 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001158 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001159 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001160 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001161 //
1162 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1163 // are better understood.
1164 if (!lhsType->isReferenceType())
1165 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001166
1167 Sema::AssignmentCheckResult result;
Steve Naroff90045e82007-07-13 23:32:42 +00001168
Steve Narofff1120de2007-08-24 22:33:52 +00001169 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1170
1171 // C99 6.5.16.1p2: The value of the right operand is converted to the
1172 // type of the assignment expression.
1173 if (rExpr->getType() != lhsType)
1174 promoteExprToType(rExpr, lhsType);
1175 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001176}
1177
1178Sema::AssignmentCheckResult
1179Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1180 return CheckAssignmentConstraints(lhsType, rhsType);
1181}
1182
Chris Lattnerca5eede2007-12-12 05:47:28 +00001183QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001184 Diag(loc, diag::err_typecheck_invalid_operands,
1185 lex->getType().getAsString(), rex->getType().getAsString(),
1186 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerca5eede2007-12-12 05:47:28 +00001187 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001188}
1189
Steve Naroff49b45262007-07-13 16:58:59 +00001190inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1191 Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001192 QualType lhsType = lex->getType(), rhsType = rex->getType();
1193
1194 // make sure the vector types are identical.
1195 if (lhsType == rhsType)
1196 return lhsType;
1197 // You cannot convert between vector values of different size.
1198 Diag(loc, diag::err_typecheck_vector_not_convertable,
1199 lex->getType().getAsString(), rex->getType().getAsString(),
1200 lex->getSourceRange(), rex->getSourceRange());
1201 return QualType();
1202}
1203
1204inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001205 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001206{
Steve Naroff90045e82007-07-13 23:32:42 +00001207 QualType lhsType = lex->getType(), rhsType = rex->getType();
1208
1209 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001210 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001211
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001212 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001213
Steve Naroffa4332e22007-07-17 00:58:39 +00001214 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001215 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001216 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001217}
1218
1219inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001220 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001221{
Steve Naroff90045e82007-07-13 23:32:42 +00001222 QualType lhsType = lex->getType(), rhsType = rex->getType();
1223
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001224 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001225
Steve Naroffa4332e22007-07-17 00:58:39 +00001226 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001227 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001228 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001229}
1230
1231inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001232 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001233{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001234 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001235 return CheckVectorOperands(loc, lex, rex);
1236
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001237 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Steve Naroff3e5e5562007-07-16 22:23:01 +00001238
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001240 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001241 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001242
Steve Naroffa4332e22007-07-17 00:58:39 +00001243 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1244 return lex->getType();
1245 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1246 return rex->getType();
Chris Lattnerca5eede2007-12-12 05:47:28 +00001247 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001248}
1249
1250inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001251 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001252{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001253 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001255
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001256 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001257
Chris Lattner6e4ab612007-12-09 21:53:25 +00001258 // Enforce type constraints: C99 6.5.6p3.
1259
1260 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001261 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001262 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001263
1264 // Either ptr - int or ptr - ptr.
1265 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1266 // The LHS must be an object type, not incomplete, function, etc.
1267 if (!LHSPTy->getPointeeType()->isObjectType()) {
1268 // Handle the GNU void* extension.
1269 if (LHSPTy->getPointeeType()->isVoidType()) {
1270 Diag(loc, diag::ext_gnu_void_ptr,
1271 lex->getSourceRange(), rex->getSourceRange());
1272 } else {
1273 Diag(loc, diag::err_typecheck_sub_ptr_object,
1274 lex->getType().getAsString(), lex->getSourceRange());
1275 return QualType();
1276 }
1277 }
1278
1279 // The result type of a pointer-int computation is the pointer type.
1280 if (rex->getType()->isIntegerType())
1281 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001282
Chris Lattner6e4ab612007-12-09 21:53:25 +00001283 // Handle pointer-pointer subtractions.
1284 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1285 // RHS must be an object type, unless void (GNU).
1286 if (!RHSPTy->getPointeeType()->isObjectType()) {
1287 // Handle the GNU void* extension.
1288 if (RHSPTy->getPointeeType()->isVoidType()) {
1289 if (!LHSPTy->getPointeeType()->isVoidType())
1290 Diag(loc, diag::ext_gnu_void_ptr,
1291 lex->getSourceRange(), rex->getSourceRange());
1292 } else {
1293 Diag(loc, diag::err_typecheck_sub_ptr_object,
1294 rex->getType().getAsString(), rex->getSourceRange());
1295 return QualType();
1296 }
1297 }
1298
1299 // Pointee types must be compatible.
1300 if (!Context.typesAreCompatible(LHSPTy->getPointeeType(),
1301 RHSPTy->getPointeeType())) {
1302 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1303 lex->getType().getAsString(), rex->getType().getAsString(),
1304 lex->getSourceRange(), rex->getSourceRange());
1305 return QualType();
1306 }
1307
1308 return Context.getPointerDiffType();
1309 }
1310 }
1311
Chris Lattnerca5eede2007-12-12 05:47:28 +00001312 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001313}
1314
1315inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Chris Lattnerca5eede2007-12-12 05:47:28 +00001316 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1317 // C99 6.5.7p2: Each of the operands shall have integer type.
1318 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1319 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001320
Chris Lattnerca5eede2007-12-12 05:47:28 +00001321 // Shifts don't perform usual arithmetic conversions, they just do integer
1322 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00001323 if (!isCompAssign)
1324 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00001325 UsualUnaryConversions(rex);
1326
1327 // "The type of the result is that of the promoted left operand."
1328 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001329}
1330
Chris Lattnera5937dd2007-08-26 01:18:55 +00001331inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1332 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Reid Spencer5f016e22007-07-11 17:01:13 +00001333{
Chris Lattnera5937dd2007-08-26 01:18:55 +00001334 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00001335 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1336 UsualArithmeticConversions(lex, rex);
1337 else {
1338 UsualUnaryConversions(lex);
1339 UsualUnaryConversions(rex);
1340 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001341 QualType lType = lex->getType();
1342 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001343
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001344 // For non-floating point types, check for self-comparisons of the form
1345 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1346 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001347 if (!lType->isFloatingType()) {
1348 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1349 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1350 if (DRL->getDecl() == DRR->getDecl())
1351 Diag(loc, diag::warn_selfcomparison);
1352 }
1353
Chris Lattnera5937dd2007-08-26 01:18:55 +00001354 if (isRelational) {
1355 if (lType->isRealType() && rType->isRealType())
1356 return Context.IntTy;
1357 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001358 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001359 if (lType->isFloatingType()) {
1360 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001361 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00001362 }
1363
Chris Lattnera5937dd2007-08-26 01:18:55 +00001364 if (lType->isArithmeticType() && rType->isArithmeticType())
1365 return Context.IntTy;
1366 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001367
Chris Lattnerd28f8152007-08-26 01:10:14 +00001368 bool LHSIsNull = lex->isNullPointerConstant(Context);
1369 bool RHSIsNull = rex->isNullPointerConstant(Context);
1370
Chris Lattnera5937dd2007-08-26 01:18:55 +00001371 // All of the following pointer related warnings are GCC extensions, except
1372 // when handling null pointer constants. One day, we can consider making them
1373 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00001374 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff66296cb2007-11-13 14:57:38 +00001375
1376 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1377 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1378 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroffec0550f2007-10-15 20:41:53 +00001379 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1380 rType.getUnqualifiedType())) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001381 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1382 lType.getAsString(), rType.getAsString(),
1383 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001384 }
Chris Lattnerd28f8152007-08-26 01:10:14 +00001385 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001386 return Context.IntTy;
1387 }
1388 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001389 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001390 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1391 lType.getAsString(), rType.getAsString(),
1392 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001393 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001394 return Context.IntTy;
1395 }
1396 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001397 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001398 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1399 lType.getAsString(), rType.getAsString(),
1400 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001401 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001402 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001403 }
Chris Lattnerca5eede2007-12-12 05:47:28 +00001404 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001405}
1406
Reid Spencer5f016e22007-07-11 17:01:13 +00001407inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001408 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001409{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001410 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001411 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001412
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001413 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001414
Steve Naroffa4332e22007-07-17 00:58:39 +00001415 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001416 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001417 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001418}
1419
1420inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00001421 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001422{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001423 UsualUnaryConversions(lex);
1424 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001425
Steve Naroffa4332e22007-07-17 00:58:39 +00001426 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001427 return Context.IntTy;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001428 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001429}
1430
1431inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00001432 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001433{
1434 QualType lhsType = lex->getType();
1435 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1436 bool hadError = false;
1437 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1438
1439 switch (mlval) { // C99 6.5.16p2
1440 case Expr::MLV_Valid:
1441 break;
1442 case Expr::MLV_ConstQualified:
1443 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1444 hadError = true;
1445 break;
1446 case Expr::MLV_ArrayType:
1447 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1448 lhsType.getAsString(), lex->getSourceRange());
1449 return QualType();
1450 case Expr::MLV_NotObjectType:
1451 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1452 lhsType.getAsString(), lex->getSourceRange());
1453 return QualType();
1454 case Expr::MLV_InvalidExpression:
1455 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1456 lex->getSourceRange());
1457 return QualType();
1458 case Expr::MLV_IncompleteType:
1459 case Expr::MLV_IncompleteVoidType:
1460 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1461 lhsType.getAsString(), lex->getSourceRange());
1462 return QualType();
Steve Narofffec0b492007-07-30 03:29:09 +00001463 case Expr::MLV_DuplicateVectorComponents:
1464 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1465 lex->getSourceRange());
1466 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 }
Steve Naroff90045e82007-07-13 23:32:42 +00001468 AssignmentCheckResult result;
1469
1470 if (compoundType.isNull())
1471 result = CheckSingleAssignmentConstraints(lhsType, rex);
1472 else
1473 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001474
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 // decode the result (notice that extensions still return a type).
1476 switch (result) {
1477 case Compatible:
1478 break;
1479 case Incompatible:
1480 Diag(loc, diag::err_typecheck_assign_incompatible,
1481 lhsType.getAsString(), rhsType.getAsString(),
1482 lex->getSourceRange(), rex->getSourceRange());
1483 hadError = true;
1484 break;
1485 case PointerFromInt:
Steve Naroff529a4ad2007-11-27 17:58:44 +00001486 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1487 lhsType.getAsString(), rhsType.getAsString(),
1488 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 break;
1490 case IntFromPointer:
1491 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1492 lhsType.getAsString(), rhsType.getAsString(),
1493 lex->getSourceRange(), rex->getSourceRange());
1494 break;
1495 case IncompatiblePointer:
1496 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1497 lhsType.getAsString(), rhsType.getAsString(),
1498 lex->getSourceRange(), rex->getSourceRange());
1499 break;
1500 case CompatiblePointerDiscardsQualifiers:
1501 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1502 lhsType.getAsString(), rhsType.getAsString(),
1503 lex->getSourceRange(), rex->getSourceRange());
1504 break;
1505 }
1506 // C99 6.5.16p3: The type of an assignment expression is the type of the
1507 // left operand unless the left operand has qualified type, in which case
1508 // it is the unqualified version of the type of the left operand.
1509 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1510 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001511 // C++ 5.17p1: the type of the assignment expression is that of its left
1512 // oprdu.
Reid Spencer5f016e22007-07-11 17:01:13 +00001513 return hadError ? QualType() : lhsType.getUnqualifiedType();
1514}
1515
1516inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00001517 Expr *&lex, Expr *&rex, SourceLocation loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001518 UsualUnaryConversions(rex);
1519 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001520}
1521
Steve Naroff49b45262007-07-13 16:58:59 +00001522/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1523/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00001524QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00001525 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 assert(!resType.isNull() && "no type for increment/decrement expression");
1527
Steve Naroff084f9ed2007-08-24 17:20:07 +00001528 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00001529 if (const PointerType *pt = resType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1531 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1532 resType.getAsString(), op->getSourceRange());
1533 return QualType();
1534 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00001535 } else if (!resType->isRealType()) {
1536 if (resType->isComplexType())
1537 // C99 does not support ++/-- on complex types.
1538 Diag(OpLoc, diag::ext_integer_increment_complex,
1539 resType.getAsString(), op->getSourceRange());
1540 else {
1541 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1542 resType.getAsString(), op->getSourceRange());
1543 return QualType();
1544 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001545 }
Steve Naroffdd10e022007-08-23 21:37:33 +00001546 // At this point, we know we have a real, complex or pointer type.
1547 // Now make sure the operand is a modifiable lvalue.
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1549 if (mlval != Expr::MLV_Valid) {
1550 // FIXME: emit a more precise diagnostic...
1551 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1552 op->getSourceRange());
1553 return QualType();
1554 }
1555 return resType;
1556}
1557
1558/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1559/// This routine allows us to typecheck complex/recursive expressions
1560/// where the declaration is needed for type checking. Here are some
1561/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1562static Decl *getPrimaryDeclaration(Expr *e) {
1563 switch (e->getStmtClass()) {
1564 case Stmt::DeclRefExprClass:
1565 return cast<DeclRefExpr>(e)->getDecl();
1566 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00001567 // Fields cannot be declared with a 'register' storage class.
1568 // &X->f is always ok, even if X is declared register.
1569 if (cast<MemberExpr>(e)->isArrow())
1570 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1572 case Stmt::ArraySubscriptExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00001573 // &X[4] and &4[X] is invalid if X is invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 case Stmt::UnaryOperatorClass:
1576 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1577 case Stmt::ParenExprClass:
1578 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00001579 case Stmt::ImplicitCastExprClass:
1580 // &X[4] when X is an array, has an implicit cast from array to pointer.
1581 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 default:
1583 return 0;
1584 }
1585}
1586
1587/// CheckAddressOfOperand - The operand of & must be either a function
1588/// designator or an lvalue designating an object. If it is an lvalue, the
1589/// object cannot be declared with storage class register or be a bit field.
1590/// Note: The usual conversions are *not* applied to the operand of the &
1591/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1592QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1593 Decl *dcl = getPrimaryDeclaration(op);
1594 Expr::isLvalueResult lval = op->isLvalue();
1595
1596 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00001597 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1598 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1600 op->getSourceRange());
1601 return QualType();
1602 }
1603 } else if (dcl) {
1604 // We have an lvalue with a decl. Make sure the decl is not declared
1605 // with the register storage-class specifier.
1606 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1607 if (vd->getStorageClass() == VarDecl::Register) {
1608 Diag(OpLoc, diag::err_typecheck_address_of_register,
1609 op->getSourceRange());
1610 return QualType();
1611 }
1612 } else
1613 assert(0 && "Unknown/unexpected decl type");
1614
1615 // FIXME: add check for bitfields!
1616 }
1617 // If the operand has type "type", the result has type "pointer to type".
1618 return Context.getPointerType(op->getType());
1619}
1620
1621QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001622 UsualUnaryConversions(op);
1623 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001624
Chris Lattnerbefee482007-07-31 16:53:04 +00001625 if (const PointerType *PT = qType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 QualType ptype = PT->getPointeeType();
1627 // C99 6.5.3.2p4. "if it points to an object,...".
1628 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1629 // GCC compat: special case 'void *' (treat as warning).
1630 if (ptype->isVoidType()) {
1631 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1632 qType.getAsString(), op->getSourceRange());
1633 } else {
1634 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1635 ptype.getAsString(), op->getSourceRange());
1636 return QualType();
1637 }
1638 }
1639 return ptype;
1640 }
1641 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1642 qType.getAsString(), op->getSourceRange());
1643 return QualType();
1644}
1645
1646static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1647 tok::TokenKind Kind) {
1648 BinaryOperator::Opcode Opc;
1649 switch (Kind) {
1650 default: assert(0 && "Unknown binop!");
1651 case tok::star: Opc = BinaryOperator::Mul; break;
1652 case tok::slash: Opc = BinaryOperator::Div; break;
1653 case tok::percent: Opc = BinaryOperator::Rem; break;
1654 case tok::plus: Opc = BinaryOperator::Add; break;
1655 case tok::minus: Opc = BinaryOperator::Sub; break;
1656 case tok::lessless: Opc = BinaryOperator::Shl; break;
1657 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1658 case tok::lessequal: Opc = BinaryOperator::LE; break;
1659 case tok::less: Opc = BinaryOperator::LT; break;
1660 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1661 case tok::greater: Opc = BinaryOperator::GT; break;
1662 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1663 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1664 case tok::amp: Opc = BinaryOperator::And; break;
1665 case tok::caret: Opc = BinaryOperator::Xor; break;
1666 case tok::pipe: Opc = BinaryOperator::Or; break;
1667 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1668 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1669 case tok::equal: Opc = BinaryOperator::Assign; break;
1670 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1671 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1672 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1673 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1674 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1675 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1676 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1677 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1678 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1679 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1680 case tok::comma: Opc = BinaryOperator::Comma; break;
1681 }
1682 return Opc;
1683}
1684
1685static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1686 tok::TokenKind Kind) {
1687 UnaryOperator::Opcode Opc;
1688 switch (Kind) {
1689 default: assert(0 && "Unknown unary op!");
1690 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1691 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1692 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1693 case tok::star: Opc = UnaryOperator::Deref; break;
1694 case tok::plus: Opc = UnaryOperator::Plus; break;
1695 case tok::minus: Opc = UnaryOperator::Minus; break;
1696 case tok::tilde: Opc = UnaryOperator::Not; break;
1697 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1698 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1699 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1700 case tok::kw___real: Opc = UnaryOperator::Real; break;
1701 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1702 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1703 }
1704 return Opc;
1705}
1706
1707// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001708Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00001709 ExprTy *LHS, ExprTy *RHS) {
1710 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1711 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1712
Steve Narofff69936d2007-09-16 03:34:24 +00001713 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1714 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00001715
1716 QualType ResultTy; // Result type of the binary operator.
1717 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1718
1719 switch (Opc) {
1720 default:
1721 assert(0 && "Unknown binary expr!");
1722 case BinaryOperator::Assign:
1723 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1724 break;
1725 case BinaryOperator::Mul:
1726 case BinaryOperator::Div:
1727 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1728 break;
1729 case BinaryOperator::Rem:
1730 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1731 break;
1732 case BinaryOperator::Add:
1733 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1734 break;
1735 case BinaryOperator::Sub:
1736 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1737 break;
1738 case BinaryOperator::Shl:
1739 case BinaryOperator::Shr:
1740 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1741 break;
1742 case BinaryOperator::LE:
1743 case BinaryOperator::LT:
1744 case BinaryOperator::GE:
1745 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001746 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 break;
1748 case BinaryOperator::EQ:
1749 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001750 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001751 break;
1752 case BinaryOperator::And:
1753 case BinaryOperator::Xor:
1754 case BinaryOperator::Or:
1755 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1756 break;
1757 case BinaryOperator::LAnd:
1758 case BinaryOperator::LOr:
1759 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1760 break;
1761 case BinaryOperator::MulAssign:
1762 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001763 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001764 if (!CompTy.isNull())
1765 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1766 break;
1767 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001768 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 if (!CompTy.isNull())
1770 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1771 break;
1772 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001773 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001774 if (!CompTy.isNull())
1775 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1776 break;
1777 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001778 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 if (!CompTy.isNull())
1780 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1781 break;
1782 case BinaryOperator::ShlAssign:
1783 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001784 CompTy = CheckShiftOperands(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::AndAssign:
1789 case BinaryOperator::XorAssign:
1790 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001791 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001792 if (!CompTy.isNull())
1793 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1794 break;
1795 case BinaryOperator::Comma:
1796 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1797 break;
1798 }
1799 if (ResultTy.isNull())
1800 return true;
1801 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001802 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001803 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001804 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001805}
1806
1807// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001808Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00001809 ExprTy *input) {
1810 Expr *Input = (Expr*)input;
1811 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1812 QualType resultType;
1813 switch (Opc) {
1814 default:
1815 assert(0 && "Unimplemented unary expr!");
1816 case UnaryOperator::PreInc:
1817 case UnaryOperator::PreDec:
1818 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1819 break;
1820 case UnaryOperator::AddrOf:
1821 resultType = CheckAddressOfOperand(Input, OpLoc);
1822 break;
1823 case UnaryOperator::Deref:
1824 resultType = CheckIndirectionOperand(Input, OpLoc);
1825 break;
1826 case UnaryOperator::Plus:
1827 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001828 UsualUnaryConversions(Input);
1829 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001830 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1831 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1832 resultType.getAsString());
1833 break;
1834 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001835 UsualUnaryConversions(Input);
1836 resultType = Input->getType();
Steve Naroff084f9ed2007-08-24 17:20:07 +00001837 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1838 if (!resultType->isIntegerType()) {
1839 if (resultType->isComplexType())
1840 // C99 does not support '~' for complex conjugation.
1841 Diag(OpLoc, diag::ext_integer_complement_complex,
1842 resultType.getAsString());
1843 else
1844 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1845 resultType.getAsString());
1846 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001847 break;
1848 case UnaryOperator::LNot: // logical negation
1849 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001850 DefaultFunctionArrayConversion(Input);
1851 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001852 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1853 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1854 resultType.getAsString());
1855 // LNot always has type int. C99 6.5.3.3p5.
1856 resultType = Context.IntTy;
1857 break;
1858 case UnaryOperator::SizeOf:
1859 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1860 break;
1861 case UnaryOperator::AlignOf:
1862 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1863 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00001864 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00001865 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00001866 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00001867 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001868 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00001869 resultType = Input->getType();
1870 break;
1871 }
1872 if (resultType.isNull())
1873 return true;
1874 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1875}
1876
Steve Naroff1b273c42007-09-16 14:56:35 +00001877/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1878Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001879 SourceLocation LabLoc,
1880 IdentifierInfo *LabelII) {
1881 // Look up the record for this label identifier.
1882 LabelStmt *&LabelDecl = LabelMap[LabelII];
1883
1884 // If we haven't seen this label yet, create a forward reference.
1885 if (LabelDecl == 0)
1886 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1887
1888 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00001889 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1890 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001891}
1892
Steve Naroff1b273c42007-09-16 14:56:35 +00001893Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001894 SourceLocation RPLoc) { // "({..})"
1895 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1896 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1897 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1898
1899 // FIXME: there are a variety of strange constraints to enforce here, for
1900 // example, it is not possible to goto into a stmt expression apparently.
1901 // More semantic analysis is needed.
1902
1903 // FIXME: the last statement in the compount stmt has its value used. We
1904 // should not warn about it being unused.
1905
1906 // If there are sub stmts in the compound stmt, take the type of the last one
1907 // as the type of the stmtexpr.
1908 QualType Ty = Context.VoidTy;
1909
1910 if (!Compound->body_empty())
1911 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1912 Ty = LastExpr->getType();
1913
1914 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1915}
Steve Naroffd34e9152007-08-01 22:05:33 +00001916
Steve Naroff1b273c42007-09-16 14:56:35 +00001917Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001918 SourceLocation TypeLoc,
1919 TypeTy *argty,
1920 OffsetOfComponent *CompPtr,
1921 unsigned NumComponents,
1922 SourceLocation RPLoc) {
1923 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1924 assert(!ArgTy.isNull() && "Missing type argument!");
1925
1926 // We must have at least one component that refers to the type, and the first
1927 // one is known to be a field designator. Verify that the ArgTy represents
1928 // a struct/union/class.
1929 if (!ArgTy->isRecordType())
1930 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1931
1932 // Otherwise, create a compound literal expression as the base, and
1933 // iteratively process the offsetof designators.
1934 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1935
Chris Lattner9e2b75c2007-08-31 21:49:13 +00001936 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1937 // GCC extension, diagnose them.
1938 if (NumComponents != 1)
1939 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1940 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1941
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001942 for (unsigned i = 0; i != NumComponents; ++i) {
1943 const OffsetOfComponent &OC = CompPtr[i];
1944 if (OC.isBrackets) {
1945 // Offset of an array sub-field. TODO: Should we allow vector elements?
1946 const ArrayType *AT = Res->getType()->getAsArrayType();
1947 if (!AT) {
1948 delete Res;
1949 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1950 Res->getType().getAsString());
1951 }
1952
Chris Lattner704fe352007-08-30 17:59:59 +00001953 // FIXME: C++: Verify that operator[] isn't overloaded.
1954
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001955 // C99 6.5.2.1p1
1956 Expr *Idx = static_cast<Expr*>(OC.U.E);
1957 if (!Idx->getType()->isIntegerType())
1958 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1959 Idx->getSourceRange());
1960
1961 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1962 continue;
1963 }
1964
1965 const RecordType *RC = Res->getType()->getAsRecordType();
1966 if (!RC) {
1967 delete Res;
1968 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1969 Res->getType().getAsString());
1970 }
1971
1972 // Get the decl corresponding to this.
1973 RecordDecl *RD = RC->getDecl();
1974 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1975 if (!MemberDecl)
1976 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1977 OC.U.IdentInfo->getName(),
1978 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00001979
1980 // FIXME: C++: Verify that MemberDecl isn't a static field.
1981 // FIXME: Verify that MemberDecl isn't a bitfield.
1982
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001983 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1984 }
1985
1986 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1987 BuiltinLoc);
1988}
1989
1990
Steve Naroff1b273c42007-09-16 14:56:35 +00001991Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00001992 TypeTy *arg1, TypeTy *arg2,
1993 SourceLocation RPLoc) {
1994 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1995 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1996
1997 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1998
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001999 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00002000}
2001
Steve Naroff1b273c42007-09-16 14:56:35 +00002002Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00002003 ExprTy *expr1, ExprTy *expr2,
2004 SourceLocation RPLoc) {
2005 Expr *CondExpr = static_cast<Expr*>(cond);
2006 Expr *LHSExpr = static_cast<Expr*>(expr1);
2007 Expr *RHSExpr = static_cast<Expr*>(expr2);
2008
2009 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2010
2011 // The conditional expression is required to be a constant expression.
2012 llvm::APSInt condEval(32);
2013 SourceLocation ExpLoc;
2014 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2015 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2016 CondExpr->getSourceRange());
2017
2018 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2019 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2020 RHSExpr->getType();
2021 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2022}
2023
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002024Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2025 ExprTy *expr, TypeTy *type,
2026 SourceLocation RPLoc)
2027{
2028 Expr *E = static_cast<Expr*>(expr);
2029 QualType T = QualType::getFromOpaquePtr(type);
2030
2031 InitBuiltinVaListType();
2032
2033 Sema::AssignmentCheckResult result;
2034
2035 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
2036 E->getType());
2037 if (result != Compatible)
2038 return Diag(E->getLocStart(),
2039 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2040 E->getType().getAsString(),
2041 E->getSourceRange());
2042
2043 // FIXME: Warn if a non-POD type is passed in.
2044
2045 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2046}
2047
Anders Carlsson55085182007-08-21 17:43:55 +00002048// TODO: Move this to SemaObjC.cpp
Chris Lattnerb3a99cd2007-12-12 01:04:12 +00002049Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
2050 ExprTy **Strings,
2051 unsigned NumStrings) {
Chris Lattnerb3a99cd2007-12-12 01:04:12 +00002052 SourceLocation AtLoc = AtLocs[0];
2053 StringLiteral* S = static_cast<StringLiteral *>(Strings[0]);
Fariborz Jahanian79a99f22007-12-12 23:55:49 +00002054 if (NumStrings > 1) {
2055 // Concatenate objc strings.
2056 StringLiteral* ES = static_cast<StringLiteral *>(Strings[NumStrings-1]);
2057 SourceLocation EndLoc = ES->getSourceRange().getEnd();
2058 unsigned Length = 0;
2059 for (unsigned i = 0; i < NumStrings; i++)
2060 Length += static_cast<StringLiteral *>(Strings[i])->getByteLength();
2061 char *strBuf = new char [Length];
2062 char *p = strBuf;
2063 bool isWide = false;
2064 for (unsigned i = 0; i < NumStrings; i++) {
2065 S = static_cast<StringLiteral *>(Strings[i]);
2066 if (S->isWide())
2067 isWide = true;
2068 memcpy(p, S->getStrData(), S->getByteLength());
2069 p += S->getByteLength();
2070 delete S;
2071 }
2072 S = new StringLiteral(strBuf, Length,
2073 isWide, Context.getPointerType(Context.CharTy),
2074 AtLoc, EndLoc);
2075 }
Anders Carlsson55085182007-08-21 17:43:55 +00002076
2077 if (CheckBuiltinCFStringArgument(S))
2078 return true;
2079
Steve Naroff21988912007-10-15 23:35:17 +00002080 if (Context.getObjcConstantStringInterface().isNull()) {
2081 // Initialize the constant string interface lazily. This assumes
2082 // the NSConstantString interface is seen in this translation unit.
2083 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
2084 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
2085 SourceLocation(), TUScope);
Steve Naroffa1fe1172007-10-16 00:00:18 +00002086 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff806a4eb2007-10-18 23:53:51 +00002087 if (!strIFace)
2088 return Diag(S->getLocStart(), diag::err_undef_interface,
2089 NSIdent->getName());
Steve Naroffa1fe1172007-10-16 00:00:18 +00002090 Context.setObjcConstantStringInterface(strIFace);
Steve Naroff21988912007-10-15 23:35:17 +00002091 }
2092 QualType t = Context.getObjcConstantStringInterface();
Anders Carlsson55085182007-08-21 17:43:55 +00002093 t = Context.getPointerType(t);
Steve Naroffbeaf2992007-11-03 11:27:19 +00002094 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlsson55085182007-08-21 17:43:55 +00002095}
Anders Carlssonf9bcf012007-08-22 15:14:15 +00002096
2097Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattner674af952007-10-16 22:51:17 +00002098 SourceLocation EncodeLoc,
Anders Carlssonf9bcf012007-08-22 15:14:15 +00002099 SourceLocation LParenLoc,
2100 TypeTy *Ty,
2101 SourceLocation RParenLoc) {
2102 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
2103
2104 QualType t = Context.getPointerType(Context.CharTy);
2105 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
2106}
Steve Naroff708391a2007-09-17 21:01:15 +00002107
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002108Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
2109 SourceLocation AtLoc,
Fariborz Jahanian2a35fa92007-10-16 23:21:02 +00002110 SourceLocation SelLoc,
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002111 SourceLocation LParenLoc,
2112 SourceLocation RParenLoc) {
Steve Naroff8ee529b2007-10-31 18:42:27 +00002113 QualType t = Context.getObjcSelType();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002114 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
2115}
2116
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002117Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
2118 SourceLocation AtLoc,
2119 SourceLocation ProtoLoc,
2120 SourceLocation LParenLoc,
2121 SourceLocation RParenLoc) {
2122 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
2123 if (!PDecl) {
2124 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
2125 return true;
2126 }
2127
Fariborz Jahanian66c5dfc2007-12-07 00:18:54 +00002128 QualType t = Context.getObjcProtoType();
Fariborz Jahanian3e27aa12007-10-18 22:59:23 +00002129 if (t.isNull())
2130 return true;
Fariborz Jahanian66c5dfc2007-12-07 00:18:54 +00002131 t = Context.getPointerType(t);
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002132 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
2133}
Steve Naroff81bfde92007-10-16 23:12:48 +00002134
2135bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2136 ObjcMethodDecl *Method) {
2137 bool anyIncompatibleArgs = false;
2138
2139 for (unsigned i = 0; i < NumArgs; i++) {
2140 Expr *argExpr = Args[i];
2141 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2142
2143 QualType lhsType = Method->getParamDecl(i)->getType();
2144 QualType rhsType = argExpr->getType();
2145
2146 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2147 if (const ArrayType *ary = lhsType->getAsArrayType())
2148 lhsType = Context.getPointerType(ary->getElementType());
2149 else if (lhsType->isFunctionType())
2150 lhsType = Context.getPointerType(lhsType);
2151
2152 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2153 argExpr);
2154 if (Args[i] != argExpr) // The expression was converted.
2155 Args[i] = argExpr; // Make sure we store the converted expression.
2156 SourceLocation l = argExpr->getLocStart();
2157
2158 // decode the result (notice that AST's are still created for extensions).
2159 switch (result) {
2160 case Compatible:
2161 break;
2162 case PointerFromInt:
Steve Naroff529a4ad2007-11-27 17:58:44 +00002163 Diag(l, diag::ext_typecheck_sending_pointer_int,
2164 lhsType.getAsString(), rhsType.getAsString(),
2165 argExpr->getSourceRange());
Steve Naroff81bfde92007-10-16 23:12:48 +00002166 break;
2167 case IntFromPointer:
2168 Diag(l, diag::ext_typecheck_sending_pointer_int,
2169 lhsType.getAsString(), rhsType.getAsString(),
2170 argExpr->getSourceRange());
2171 break;
2172 case IncompatiblePointer:
2173 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2174 rhsType.getAsString(), lhsType.getAsString(),
2175 argExpr->getSourceRange());
2176 break;
2177 case CompatiblePointerDiscardsQualifiers:
2178 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2179 rhsType.getAsString(), lhsType.getAsString(),
2180 argExpr->getSourceRange());
2181 break;
2182 case Incompatible:
2183 Diag(l, diag::err_typecheck_sending_incompatible,
2184 rhsType.getAsString(), lhsType.getAsString(),
2185 argExpr->getSourceRange());
2186 anyIncompatibleArgs = true;
2187 }
2188 }
2189 return anyIncompatibleArgs;
2190}
2191
Steve Naroff68d331a2007-09-27 14:38:14 +00002192// ActOnClassMessage - used for both unary and keyword messages.
2193// ArgExprs is optional - if it is present, the number of expressions
2194// is obtained from Sel.getNumArgs().
2195Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002196 Scope *S,
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002197 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff49f109c2007-11-15 13:05:42 +00002198 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff708391a2007-09-17 21:01:15 +00002199{
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002200 assert(receiverName && "missing receiver class name");
Steve Naroff563477d2007-09-18 23:55:05 +00002201
Steve Naroff81bfde92007-10-16 23:12:48 +00002202 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002203 ObjcInterfaceDecl* ClassDecl = 0;
2204 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2205 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahaniancffff842007-11-12 20:20:37 +00002206 if (ClassDecl && CurMethodDecl->isInstance()) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002207 // Synthesize a cast to the super class. This hack allows us to loosely
2208 // represent super without creating a special expression node.
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002209 IdentifierInfo &II = Context.Idents.get("self");
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002210 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II, false);
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002211 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2212 superTy = Context.getPointerType(superTy);
2213 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2214 SourceLocation(), ReceiverExpr.Val);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002215 // We are really in an instance method, redirect.
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002216 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
Steve Naroff49f109c2007-11-15 13:05:42 +00002217 Args, NumArgs);
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002218 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002219 // We are sending a message to 'super' within a class method. Do nothing,
2220 // the receiver will pass through as 'super' (how convenient:-).
2221 } else
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002222 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002223
2224 // FIXME: can ClassDecl ever be null?
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002225 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff983df5b2007-10-16 20:39:36 +00002226 QualType returnType;
Steve Naroff945c0a82007-11-05 15:27:52 +00002227
2228 // Before we give up, check if the selector is an instance method.
2229 if (!Method)
2230 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff983df5b2007-10-16 20:39:36 +00002231 if (!Method) {
2232 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2233 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002234 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002235 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002236 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002237 if (Sel.getNumArgs()) {
2238 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2239 return true;
2240 }
Steve Naroff983df5b2007-10-16 20:39:36 +00002241 }
Steve Naroffdb611d52007-11-03 16:37:59 +00002242 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
Steve Naroff49f109c2007-11-15 13:05:42 +00002243 lbrac, rbrac, ArgExprs, NumArgs);
Steve Naroff708391a2007-09-17 21:01:15 +00002244}
2245
Steve Naroff68d331a2007-09-27 14:38:14 +00002246// ActOnInstanceMessage - used for both unary and keyword messages.
2247// ArgExprs is optional - if it is present, the number of expressions
2248// is obtained from Sel.getNumArgs().
2249Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroffbcfb06a2007-09-28 22:22:11 +00002250 ExprTy *receiver, Selector Sel,
Steve Naroff49f109c2007-11-15 13:05:42 +00002251 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff68d331a2007-09-27 14:38:14 +00002252{
Steve Naroff563477d2007-09-18 23:55:05 +00002253 assert(receiver && "missing receiver expression");
2254
Steve Naroff81bfde92007-10-16 23:12:48 +00002255 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroff563477d2007-09-18 23:55:05 +00002256 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002257 QualType receiverType = RExpr->getType();
Steve Naroff3b950172007-10-10 21:53:07 +00002258 QualType returnType;
Steve Naroffdb611d52007-11-03 16:37:59 +00002259 ObjcMethodDecl *Method;
Steve Naroff3b950172007-10-10 21:53:07 +00002260
Steve Naroff7c249152007-11-11 17:52:25 +00002261 if (receiverType == Context.getObjcIdType() ||
2262 receiverType == Context.getObjcClassType()) {
Steve Naroffdb611d52007-11-03 16:37:59 +00002263 Method = InstanceMethodPool[Sel].Method;
Steve Naroff817da7c2007-11-13 04:10:18 +00002264 // If we didn't find an public method, look for a private one.
2265 if (!Method && CurMethodDecl) {
2266 NamedDecl *impCxt = CurMethodDecl->getMethodContext();
2267 if (ObjcImplementationDecl *IMD =
2268 dyn_cast<ObjcImplementationDecl>(impCxt)) {
2269 if (receiverType == Context.getObjcIdType())
2270 Method = IMD->lookupInstanceMethod(Sel);
2271 else
2272 Method = IMD->lookupClassMethod(Sel);
2273 } else if (ObjcCategoryImplDecl *CID =
2274 dyn_cast<ObjcCategoryImplDecl>(impCxt)) {
2275 if (receiverType == Context.getObjcIdType())
2276 Method = CID->lookupInstanceMethod(Sel);
2277 else
2278 Method = CID->lookupClassMethod(Sel);
2279 }
2280 }
Steve Naroff983df5b2007-10-16 20:39:36 +00002281 if (!Method) {
2282 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2283 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002284 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002285 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002286 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002287 if (Sel.getNumArgs())
2288 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2289 return true;
Steve Naroff983df5b2007-10-16 20:39:36 +00002290 }
Steve Naroff3b950172007-10-10 21:53:07 +00002291 } else {
Chris Lattner22b73ba2007-10-10 23:42:28 +00002292 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2293 // revisited. how do we get the ClassDecl from the receiver expression?
Steve Naroff3b950172007-10-10 21:53:07 +00002294 while (receiverType->isPointerType()) {
Chris Lattner22b73ba2007-10-10 23:42:28 +00002295 PointerType *pointerType =
2296 static_cast<PointerType*>(receiverType.getTypePtr());
Steve Naroff3b950172007-10-10 21:53:07 +00002297 receiverType = pointerType->getPointeeType();
2298 }
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002299 ObjcInterfaceDecl* ClassDecl;
2300 if (ObjcQualifiedInterfaceType *QIT =
2301 dyn_cast<ObjcQualifiedInterfaceType>(receiverType)) {
Fariborz Jahanian06cef252007-12-13 20:47:42 +00002302 ClassDecl = QIT->getDecl();
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002303 Method = ClassDecl->lookupInstanceMethod(Sel);
2304 if (!Method) {
2305 // search protocols
2306 for (unsigned i = 0; i < QIT->getNumProtocols(); i++) {
2307 ObjcProtocolDecl *PDecl = QIT->getProtocols(i);
2308 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
2309 break;
2310 }
2311 }
2312 }
2313 else {
2314 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2315 "bad receiver type");
2316 ClassDecl = static_cast<ObjcInterfaceType*>(
2317 receiverType.getTypePtr())->getDecl();
2318 // FIXME: consider using InstanceMethodPool, since it will be faster
2319 // than the following method (which can do *many* linear searches). The
2320 // idea is to add class info to InstanceMethodPool...
2321 Method = ClassDecl->lookupInstanceMethod(Sel);
2322 }
Steve Naroff983df5b2007-10-16 20:39:36 +00002323 if (!Method) {
Steve Naroffc43d8682007-11-11 00:10:47 +00002324 // If we have an implementation in scope, check "private" methods.
2325 if (ObjcImplementationDecl *ImpDecl =
2326 ObjcImplementations[ClassDecl->getIdentifier()])
2327 Method = ImpDecl->lookupInstanceMethod(Sel);
Steve Naroff9a4ad372007-12-11 03:38:03 +00002328 // If we still haven't found a method, look in the global pool. This
2329 // behavior isn't very desirable, however we need it for GCC compatibility.
Steve Naroff9feba022007-12-07 20:41:14 +00002330 if (!Method)
2331 Method = InstanceMethodPool[Sel].Method;
Steve Naroffc43d8682007-11-11 00:10:47 +00002332 }
2333 if (!Method) {
Steve Naroff983df5b2007-10-16 20:39:36 +00002334 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2335 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002336 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002337 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002338 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002339 if (Sel.getNumArgs())
2340 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2341 return true;
Steve Naroff983df5b2007-10-16 20:39:36 +00002342 }
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002343 }
Steve Naroffdb611d52007-11-03 16:37:59 +00002344 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
Steve Naroff49f109c2007-11-15 13:05:42 +00002345 ArgExprs, NumArgs);
Steve Naroff708391a2007-09-17 21:01:15 +00002346}