blob: 68c301afd82dce0b68ad073b27f415b76beab790 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Ted Kremenek30c66752007-11-25 00:58:00 +000015#include "SemaUtil.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
Steve Narofffa465d12007-10-02 20:01:56 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/AST/Expr.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000020#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Lex/Preprocessor.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Basic/SourceManager.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/TargetInfo.h"
Chris Lattner83bd5eb2007-12-28 05:29:59 +000027#include "llvm/ADT/OwningPtr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000029#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000030using namespace clang;
31
Steve Naroff87d58b42007-09-16 03:34:24 +000032/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000033/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
34/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
35/// multiple tokens. However, the common case is that StringToks points to one
36/// string.
37///
38Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000039Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000040 assert(NumStringToks && "Must have at least one string!");
41
42 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
43 if (Literal.hadError)
44 return ExprResult(true);
45
46 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
47 for (unsigned i = 0; i != NumStringToks; ++i)
48 StringTokLocs.push_back(StringToks[i].getLocation());
49
50 // FIXME: handle wchar_t
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000051 QualType t;
52
53 if (Literal.Pascal)
54 t = Context.getPointerType(Context.UnsignedCharTy);
55 else
56 t = Context.getPointerType(Context.CharTy);
57
58 if (Literal.Pascal && Literal.GetStringLength() > 256)
59 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
60 SourceRange(StringToks[0].getLocation(),
61 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000062
63 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
64 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000065 Literal.AnyWide, t,
66 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000067 StringToks[NumStringToks-1].getLocation());
68}
69
70
Steve Naroff0acc9c92007-09-15 18:49:24 +000071/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000072/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
73/// identifier is used in an function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000074Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000075 IdentifierInfo &II,
76 bool HasTrailingLParen) {
77 // Could be enum-constant or decl.
Steve Narofff0c31dd2007-09-16 16:16:00 +000078 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Chris Lattner4b009652007-07-25 00:24:17 +000079 if (D == 0) {
80 // Otherwise, this could be an implicitly declared function reference (legal
81 // in C90, extension in C99).
82 if (HasTrailingLParen &&
83 // Not in C++.
84 !getLangOptions().CPlusPlus)
85 D = ImplicitlyDefineFunction(Loc, II, S);
86 else {
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000087 if (CurMethodDecl) {
88 ObjcInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
89 ObjcInterfaceDecl *clsDeclared;
Steve Naroff6b759ce2007-11-15 02:58:25 +000090 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
91 IdentifierInfo &II = Context.Idents.get("self");
92 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
93 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
94 static_cast<Expr*>(SelfExpr.Val), true, true);
95 }
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000096 }
Chris Lattner4b009652007-07-25 00:24:17 +000097 // If this name wasn't predeclared and if this is not a function call,
98 // diagnose the problem.
99 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
100 }
101 }
Steve Naroff91b03f72007-08-28 03:03:08 +0000102 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroffcae537d2007-08-28 18:45:29 +0000103 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000104 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000105 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000106 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000107 }
Chris Lattner4b009652007-07-25 00:24:17 +0000108 if (isa<TypedefDecl>(D))
109 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000110 if (isa<ObjcInterfaceDecl>(D))
111 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000112
113 assert(0 && "Invalid decl");
114 abort();
115}
116
Steve Naroff87d58b42007-09-16 03:34:24 +0000117Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000118 tok::TokenKind Kind) {
119 PreDefinedExpr::IdentType IT;
120
121 switch (Kind) {
122 default:
123 assert(0 && "Unknown simple primary expr!");
124 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
125 IT = PreDefinedExpr::Func;
126 break;
127 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
128 IT = PreDefinedExpr::Function;
129 break;
130 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
131 IT = PreDefinedExpr::PrettyFunction;
132 break;
133 }
134
135 // Pre-defined identifiers are always of type char *.
136 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
137}
138
Steve Naroff87d58b42007-09-16 03:34:24 +0000139Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000140 llvm::SmallString<16> CharBuffer;
141 CharBuffer.resize(Tok.getLength());
142 const char *ThisTokBegin = &CharBuffer[0];
143 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
144
145 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
146 Tok.getLocation(), PP);
147 if (Literal.hadError())
148 return ExprResult(true);
149 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
150 Tok.getLocation());
151}
152
Steve Naroff87d58b42007-09-16 03:34:24 +0000153Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000154 // fast path for a single digit (which is quite common). A single digit
155 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
156 if (Tok.getLength() == 1) {
157 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
158
Chris Lattner3496d522007-09-04 02:45:27 +0000159 unsigned IntSize = static_cast<unsigned>(
160 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000161 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
162 Context.IntTy,
163 Tok.getLocation()));
164 }
165 llvm::SmallString<512> IntegerBuffer;
166 IntegerBuffer.resize(Tok.getLength());
167 const char *ThisTokBegin = &IntegerBuffer[0];
168
169 // Get the spelling of the token, which eliminates trigraphs, etc.
170 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
171 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
172 Tok.getLocation(), PP);
173 if (Literal.hadError)
174 return ExprResult(true);
175
Chris Lattner1de66eb2007-08-26 03:42:43 +0000176 Expr *Res;
177
178 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000179 QualType Ty;
180 const llvm::fltSemantics *Format;
181 uint64_t Size; unsigned Align;
182
183 if (Literal.isFloat) {
184 Ty = Context.FloatTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000185 Context.Target.getFloatInfo(Size, Align, Format,
186 Context.getFullLoc(Tok.getLocation()));
187
Chris Lattner858eece2007-09-22 18:29:59 +0000188 } else if (Literal.isLong) {
189 Ty = Context.LongDoubleTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000190 Context.Target.getLongDoubleInfo(Size, Align, Format,
191 Context.getFullLoc(Tok.getLocation()));
Chris Lattner858eece2007-09-22 18:29:59 +0000192 } else {
193 Ty = Context.DoubleTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000194 Context.Target.getDoubleInfo(Size, Align, Format,
195 Context.getFullLoc(Tok.getLocation()));
Chris Lattner858eece2007-09-22 18:29:59 +0000196 }
197
Ted Kremenekddedbe22007-11-29 00:56:49 +0000198 // isExact will be set by GetFloatValue().
199 bool isExact = false;
200
201 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
202 Ty, Tok.getLocation());
203
Chris Lattner1de66eb2007-08-26 03:42:43 +0000204 } else if (!Literal.isIntegerLiteral()) {
205 return ExprResult(true);
206 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000207 QualType t;
208
Neil Booth7421e9c2007-08-29 22:00:19 +0000209 // long long is a C99 feature.
210 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000211 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000212 Diag(Tok.getLocation(), diag::ext_longlong);
213
Chris Lattner4b009652007-07-25 00:24:17 +0000214 // Get the value in the widest-possible width.
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000215 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(
216 Context.getFullLoc(Tok.getLocation())), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000217
218 if (Literal.GetIntegerValue(ResultVal)) {
219 // If this value didn't fit into uintmax_t, warn and force to ull.
220 Diag(Tok.getLocation(), diag::warn_integer_too_large);
221 t = Context.UnsignedLongLongTy;
222 assert(Context.getTypeSize(t, Tok.getLocation()) ==
223 ResultVal.getBitWidth() && "long long is not intmax_t?");
224 } else {
225 // If this value fits into a ULL, try to figure out what else it fits into
226 // according to the rules of C99 6.4.4.1p5.
227
228 // Octal, Hexadecimal, and integers with a U suffix are allowed to
229 // be an unsigned int.
230 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
231
232 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000233 if (!Literal.isLong && !Literal.isLongLong) {
234 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000235 unsigned IntSize = static_cast<unsigned>(
236 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000237 // Does it fit in a unsigned int?
238 if (ResultVal.isIntN(IntSize)) {
239 // Does it fit in a signed int?
240 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
241 t = Context.IntTy;
242 else if (AllowUnsigned)
243 t = Context.UnsignedIntTy;
244 }
245
246 if (!t.isNull())
247 ResultVal.trunc(IntSize);
248 }
249
250 // Are long/unsigned long possibilities?
251 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000252 unsigned LongSize = static_cast<unsigned>(
253 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000254
255 // Does it fit in a unsigned long?
256 if (ResultVal.isIntN(LongSize)) {
257 // Does it fit in a signed long?
258 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
259 t = Context.LongTy;
260 else if (AllowUnsigned)
261 t = Context.UnsignedLongTy;
262 }
263 if (!t.isNull())
264 ResultVal.trunc(LongSize);
265 }
266
267 // Finally, check long long if needed.
268 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000269 unsigned LongLongSize = static_cast<unsigned>(
270 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000271
272 // Does it fit in a unsigned long long?
273 if (ResultVal.isIntN(LongLongSize)) {
274 // Does it fit in a signed long long?
275 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
276 t = Context.LongLongTy;
277 else if (AllowUnsigned)
278 t = Context.UnsignedLongLongTy;
279 }
280 }
281
282 // If we still couldn't decide a type, we probably have something that
283 // does not fit in a signed long long, but has no U suffix.
284 if (t.isNull()) {
285 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
286 t = Context.UnsignedLongLongTy;
287 }
288 }
289
Chris Lattner1de66eb2007-08-26 03:42:43 +0000290 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000291 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000292
293 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
294 if (Literal.isImaginary)
295 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
296
297 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000298}
299
Steve Naroff87d58b42007-09-16 03:34:24 +0000300Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000301 ExprTy *Val) {
302 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000303 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000304 return new ParenExpr(L, R, e);
305}
306
307/// The UsualUnaryConversions() function is *not* called by this routine.
308/// See C99 6.3.2.1p[2-4] for more details.
309QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
310 SourceLocation OpLoc, bool isSizeof) {
311 // C99 6.5.3.4p1:
312 if (isa<FunctionType>(exprType) && isSizeof)
313 // alignof(function) is allowed.
314 Diag(OpLoc, diag::ext_sizeof_function_type);
315 else if (exprType->isVoidType())
316 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
317 else if (exprType->isIncompleteType()) {
318 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
319 diag::err_alignof_incomplete_type,
320 exprType.getAsString());
321 return QualType(); // error
322 }
323 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
324 return Context.getSizeType();
325}
326
327Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000328ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000329 SourceLocation LPLoc, TypeTy *Ty,
330 SourceLocation RPLoc) {
331 // If error parsing type, ignore.
332 if (Ty == 0) return true;
333
334 // Verify that this is a valid expression.
335 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
336
337 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
338
339 if (resultType.isNull())
340 return true;
341 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
342}
343
Chris Lattner5110ad52007-08-24 21:41:10 +0000344QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000345 DefaultFunctionArrayConversion(V);
346
Chris Lattnera16e42d2007-08-26 05:39:26 +0000347 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000348 if (const ComplexType *CT = V->getType()->getAsComplexType())
349 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000350
351 // Otherwise they pass through real integer and floating point types here.
352 if (V->getType()->isArithmeticType())
353 return V->getType();
354
355 // Reject anything else.
356 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
357 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000358}
359
360
Chris Lattner4b009652007-07-25 00:24:17 +0000361
Steve Naroff87d58b42007-09-16 03:34:24 +0000362Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000363 tok::TokenKind Kind,
364 ExprTy *Input) {
365 UnaryOperator::Opcode Opc;
366 switch (Kind) {
367 default: assert(0 && "Unknown unary op!");
368 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
369 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
370 }
371 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
372 if (result.isNull())
373 return true;
374 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
375}
376
377Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000378ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000379 ExprTy *Idx, SourceLocation RLoc) {
380 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
381
382 // Perform default conversions.
383 DefaultFunctionArrayConversion(LHSExp);
384 DefaultFunctionArrayConversion(RHSExp);
385
386 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
387
388 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000389 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000390 // in the subscript position. As a result, we need to derive the array base
391 // and index from the expression types.
392 Expr *BaseExpr, *IndexExpr;
393 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000394 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000395 BaseExpr = LHSExp;
396 IndexExpr = RHSExp;
397 // FIXME: need to deal with const...
398 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000399 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000400 // Handle the uncommon case of "123[Ptr]".
401 BaseExpr = RHSExp;
402 IndexExpr = LHSExp;
403 // FIXME: need to deal with const...
404 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000405 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
406 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000407 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000408
409 // Component access limited to variables (reject vec4.rg[1]).
410 if (!isa<DeclRefExpr>(BaseExpr))
411 return Diag(LLoc, diag::err_ocuvector_component_access,
412 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000413 // FIXME: need to deal with const...
414 ResultType = VTy->getElementType();
415 } else {
416 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
417 RHSExp->getSourceRange());
418 }
419 // C99 6.5.2.1p1
420 if (!IndexExpr->getType()->isIntegerType())
421 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
422 IndexExpr->getSourceRange());
423
424 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
425 // the following check catches trying to index a pointer to a function (e.g.
426 // void (*)(int)). Functions are not objects in C99.
427 if (!ResultType->isObjectType())
428 return Diag(BaseExpr->getLocStart(),
429 diag::err_typecheck_subscript_not_object,
430 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
431
432 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
433}
434
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000435QualType Sema::
436CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
437 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000438 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000439
440 // The vector accessor can't exceed the number of elements.
441 const char *compStr = CompName.getName();
442 if (strlen(compStr) > vecType->getNumElements()) {
443 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
444 baseType.getAsString(), SourceRange(CompLoc));
445 return QualType();
446 }
447 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000448 if (vecType->getPointAccessorIdx(*compStr) != -1) {
449 do
450 compStr++;
451 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
452 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
453 do
454 compStr++;
455 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
456 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
457 do
458 compStr++;
459 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
460 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000461
462 if (*compStr) {
463 // We didn't get to the end of the string. This means the component names
464 // didn't come from the same set *or* we encountered an illegal name.
465 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
466 std::string(compStr,compStr+1), SourceRange(CompLoc));
467 return QualType();
468 }
469 // Each component accessor can't exceed the vector type.
470 compStr = CompName.getName();
471 while (*compStr) {
472 if (vecType->isAccessorWithinNumElements(*compStr))
473 compStr++;
474 else
475 break;
476 }
477 if (*compStr) {
478 // We didn't get to the end of the string. This means a component accessor
479 // exceeds the number of elements in the vector.
480 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
481 baseType.getAsString(), SourceRange(CompLoc));
482 return QualType();
483 }
484 // The component accessor looks fine - now we need to compute the actual type.
485 // The vector type is implied by the component accessor. For example,
486 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
487 unsigned CompSize = strlen(CompName.getName());
488 if (CompSize == 1)
489 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000490
491 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
492 // Now look up the TypeDefDecl from the vector type. Without this,
493 // diagostics look bad. We want OCU vector types to appear built-in.
494 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
495 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
496 return Context.getTypedefType(OCUVectorDecls[i]);
497 }
498 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000499}
500
Chris Lattner4b009652007-07-25 00:24:17 +0000501Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000502ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000503 tok::TokenKind OpKind, SourceLocation MemberLoc,
504 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000505 Expr *BaseExpr = static_cast<Expr *>(Base);
506 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000507
508 // Perform default conversions.
509 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000510
Steve Naroff2cb66382007-07-26 03:11:44 +0000511 QualType BaseType = BaseExpr->getType();
512 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000513
Chris Lattner4b009652007-07-25 00:24:17 +0000514 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000515 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000516 BaseType = PT->getPointeeType();
517 else
518 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
519 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000520 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000521 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000522 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000523 RecordDecl *RDecl = RTy->getDecl();
524 if (RTy->isIncompleteType())
525 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
526 BaseExpr->getSourceRange());
527 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000528 FieldDecl *MemberDecl = RDecl->getMember(&Member);
529 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000530 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
531 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000532 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
533 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000534 // Component access limited to variables (reject vec4.rg.g).
535 if (!isa<DeclRefExpr>(BaseExpr))
536 return Diag(OpLoc, diag::err_ocuvector_component_access,
537 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000538 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
539 if (ret.isNull())
540 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000541 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000542 } else if (BaseType->isObjcInterfaceType()) {
543 ObjcInterfaceDecl *IFace;
544 if (isa<ObjcInterfaceType>(BaseType.getCanonicalType()))
545 IFace = dyn_cast<ObjcInterfaceType>(BaseType)->getDecl();
546 else
Fariborz Jahanian0c2f2142007-12-13 20:47:42 +0000547 IFace = dyn_cast<ObjcQualifiedInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000548 ObjcInterfaceDecl *clsDeclared;
549 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
550 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
551 OpKind==tok::arrow);
552 }
553 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
554 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000555}
556
Steve Naroff87d58b42007-09-16 03:34:24 +0000557/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000558/// This provides the location of the left/right parens and a list of comma
559/// locations.
560Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000561ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000562 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000563 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
564 Expr *Fn = static_cast<Expr *>(fn);
565 Expr **Args = reinterpret_cast<Expr**>(args);
566 assert(Fn && "no function call expression");
567
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000568 // Make the call expr early, before semantic checks. This guarantees cleanup
569 // of arguments and function on error.
570 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
571 Context.BoolTy, RParenLoc));
572
573 // Promote the function operand.
574 TheCall->setCallee(UsualUnaryConversions(Fn));
575
Chris Lattner4b009652007-07-25 00:24:17 +0000576 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
577 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000578 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000579 if (PT == 0)
580 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
581 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000582 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
583 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000584 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
585 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000586
587 // We know the result type of the call, set it.
588 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000589
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000590 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000591 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
592 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000593 unsigned NumArgsInProto = Proto->getNumArgs();
594 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000595
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000596 // If too few arguments are available, don't make the call.
597 if (NumArgs < NumArgsInProto)
598 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
599 Fn->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000600
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000601 // If too many are passed and not variadic, error on the extras and drop
602 // them.
603 if (NumArgs > NumArgsInProto) {
604 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000605 Diag(Args[NumArgsInProto]->getLocStart(),
606 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
607 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000608 Args[NumArgs-1]->getLocEnd()));
609 // This deletes the extra arguments.
610 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000611 }
612 NumArgsToCheck = NumArgsInProto;
613 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000614
Chris Lattner4b009652007-07-25 00:24:17 +0000615 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000616 for (unsigned i = 0; i != NumArgsToCheck; i++) {
617 Expr *Arg = Args[i];
618 QualType LHSType = Proto->getArgType(i);
619 QualType RHSType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000620
Steve Naroff75644062007-07-25 20:45:33 +0000621 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000622 if (const ArrayType *AT = LHSType->getAsArrayType())
623 LHSType = Context.getPointerType(AT->getElementType());
624 else if (LHSType->isFunctionType())
625 LHSType = Context.getPointerType(LHSType);
Chris Lattner4b009652007-07-25 00:24:17 +0000626
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000627 // Compute implicit casts from the operand to the formal argument type.
628 AssignmentCheckResult Result =
629 CheckSingleAssignmentConstraints(LHSType, Arg);
630 TheCall->setArg(i, Arg);
631
632 // Decode the result (notice that AST's are still created for extensions).
633 SourceLocation Loc = Arg->getLocStart();
634 switch (Result) {
Chris Lattner4b009652007-07-25 00:24:17 +0000635 case Compatible:
636 break;
637 case PointerFromInt:
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000638 Diag(Loc, diag::ext_typecheck_passing_pointer_int,
639 LHSType.getAsString(), RHSType.getAsString(),
640 Fn->getSourceRange(), Arg->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000641 break;
642 case IntFromPointer:
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000643 Diag(Loc, diag::ext_typecheck_passing_pointer_int,
644 LHSType.getAsString(), RHSType.getAsString(),
645 Fn->getSourceRange(), Arg->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000646 break;
Chris Lattner4ca3d772008-01-03 22:56:36 +0000647 case FunctionVoidPointer:
648 Diag(Loc, diag::ext_typecheck_passing_pointer_void_func,
649 LHSType.getAsString(), RHSType.getAsString(),
650 Fn->getSourceRange(), Arg->getSourceRange());
651 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000652 case IncompatiblePointer:
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000653 Diag(Loc, diag::ext_typecheck_passing_incompatible_pointer,
654 RHSType.getAsString(), LHSType.getAsString(),
655 Fn->getSourceRange(), Arg->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000656 break;
657 case CompatiblePointerDiscardsQualifiers:
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000658 Diag(Loc, diag::ext_typecheck_passing_discards_qualifiers,
659 RHSType.getAsString(), LHSType.getAsString(),
660 Fn->getSourceRange(), Arg->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000661 break;
662 case Incompatible:
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000663 return Diag(Loc, diag::err_typecheck_passing_incompatible,
664 RHSType.getAsString(), LHSType.getAsString(),
665 Fn->getSourceRange(), Arg->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000666 }
667 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000668
669 // If this is a variadic call, handle args passed through "...".
670 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +0000671 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000672 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
673 Expr *Arg = Args[i];
674 DefaultArgumentPromotion(Arg);
675 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000676 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000677 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000678 } else {
679 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
680
Steve Naroffdb65e052007-08-28 23:30:39 +0000681 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000682 for (unsigned i = 0; i != NumArgs; i++) {
683 Expr *Arg = Args[i];
684 DefaultArgumentPromotion(Arg);
685 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000686 }
Chris Lattner4b009652007-07-25 00:24:17 +0000687 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000688
Chris Lattner2e64c072007-08-10 20:18:51 +0000689 // Do special checking on direct calls to functions.
690 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
691 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
692 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000693 if (CheckFunctionCall(FDecl, TheCall.get()))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000694 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000695
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000696 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000697}
698
699Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000700ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000701 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000702 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000703 QualType literalType = QualType::getFromOpaquePtr(Ty);
704 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000705 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000706 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000707
Steve Naroffcb69fb72007-12-10 22:44:33 +0000708 // FIXME: add more semantic analysis (C99 6.5.2.5).
709 if (CheckInitializer(literalExpr, literalType, false))
710 return 0;
Anders Carlsson9374b852007-12-05 07:24:19 +0000711
Chris Lattner386ab8a2008-01-02 21:46:24 +0000712 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000713}
714
715Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000716ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000717 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000718 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000719
Steve Naroff0acc9c92007-09-15 18:49:24 +0000720 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000721 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000722
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000723 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
724 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
725 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000726}
727
Chris Lattnerd1f26b32007-12-20 00:44:32 +0000728bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000729 assert(VectorTy->isVectorType() && "Not a vector type!");
730
731 if (Ty->isVectorType() || Ty->isIntegerType()) {
732 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
733 Context.getTypeSize(Ty, SourceLocation()))
734 return Diag(R.getBegin(),
735 Ty->isVectorType() ?
736 diag::err_invalid_conversion_between_vectors :
737 diag::err_invalid_conversion_between_vector_and_integer,
738 VectorTy.getAsString().c_str(),
739 Ty.getAsString().c_str(), R);
740 } else
741 return Diag(R.getBegin(),
742 diag::err_invalid_conversion_between_vector_and_scalar,
743 VectorTy.getAsString().c_str(),
744 Ty.getAsString().c_str(), R);
745
746 return false;
747}
748
Chris Lattner4b009652007-07-25 00:24:17 +0000749Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000750ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000751 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000752 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000753
754 Expr *castExpr = static_cast<Expr*>(Op);
755 QualType castType = QualType::getFromOpaquePtr(Ty);
756
Steve Naroff68adb482007-08-31 00:32:44 +0000757 UsualUnaryConversions(castExpr);
758
Chris Lattner4b009652007-07-25 00:24:17 +0000759 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
760 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000761 if (!castType->isVoidType()) { // Cast to void allows any expr type.
762 if (!castType->isScalarType())
763 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
764 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000765 if (!castExpr->getType()->isScalarType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000766 return Diag(castExpr->getLocStart(),
767 diag::err_typecheck_expect_scalar_operand,
768 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000769
770 if (castExpr->getType()->isVectorType()) {
771 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
772 castExpr->getType(), castType))
773 return true;
774 } else if (castType->isVectorType()) {
775 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
776 castType, castExpr->getType()))
777 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000778 }
Chris Lattner4b009652007-07-25 00:24:17 +0000779 }
780 return new CastExpr(castType, castExpr, LParenLoc);
781}
782
Steve Naroff144667e2007-10-18 05:13:08 +0000783// promoteExprToType - a helper function to ensure we create exactly one
784// ImplicitCastExpr.
785static void promoteExprToType(Expr *&expr, QualType type) {
786 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
787 impCast->setType(type);
788 else
789 expr = new ImplicitCastExpr(type, expr);
790 return;
791}
792
Chris Lattner98a425c2007-11-26 01:40:58 +0000793/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
794/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000795inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
796 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
797 UsualUnaryConversions(cond);
798 UsualUnaryConversions(lex);
799 UsualUnaryConversions(rex);
800 QualType condT = cond->getType();
801 QualType lexT = lex->getType();
802 QualType rexT = rex->getType();
803
804 // first, check the condition.
805 if (!condT->isScalarType()) { // C99 6.5.15p2
806 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
807 condT.getAsString());
808 return QualType();
809 }
810 // now check the two expressions.
811 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
812 UsualArithmeticConversions(lex, rex);
813 return lex->getType();
814 }
Chris Lattner71225142007-07-31 21:27:01 +0000815 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
816 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
Chris Lattner98a425c2007-11-26 01:40:58 +0000817 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner71225142007-07-31 21:27:01 +0000818 return lexT;
819
Chris Lattner4b009652007-07-25 00:24:17 +0000820 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
821 lexT.getAsString(), rexT.getAsString(),
822 lex->getSourceRange(), rex->getSourceRange());
823 return QualType();
824 }
825 }
826 // C99 6.5.15p3
Steve Naroff144667e2007-10-18 05:13:08 +0000827 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
828 promoteExprToType(rex, lexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000829 return lexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000830 }
831 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
832 promoteExprToType(lex, rexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000833 return rexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000834 }
Chris Lattner71225142007-07-31 21:27:01 +0000835 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
836 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
837 // get the "pointed to" types
838 QualType lhptee = LHSPT->getPointeeType();
839 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000840
Chris Lattner71225142007-07-31 21:27:01 +0000841 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
842 if (lhptee->isVoidType() &&
843 (rhptee->isObjectType() || rhptee->isIncompleteType()))
844 return lexT;
845 if (rhptee->isVoidType() &&
846 (lhptee->isObjectType() || lhptee->isIncompleteType()))
847 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000848
Steve Naroff85f0dc52007-10-15 20:41:53 +0000849 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
850 rhptee.getUnqualifiedType())) {
Chris Lattner71225142007-07-31 21:27:01 +0000851 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
852 lexT.getAsString(), rexT.getAsString(),
853 lex->getSourceRange(), rex->getSourceRange());
854 return lexT; // FIXME: this is an _ext - is this return o.k?
855 }
856 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000857 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
858 // differently qualified versions of compatible types, the result type is
859 // a pointer to an appropriately qualified version of the *composite*
860 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000861 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000862 }
Chris Lattner4b009652007-07-25 00:24:17 +0000863 }
Chris Lattner71225142007-07-31 21:27:01 +0000864
Chris Lattner4b009652007-07-25 00:24:17 +0000865 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
866 return lexT;
867
868 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
869 lexT.getAsString(), rexT.getAsString(),
870 lex->getSourceRange(), rex->getSourceRange());
871 return QualType();
872}
873
Steve Naroff87d58b42007-09-16 03:34:24 +0000874/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000875/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000876Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000877 SourceLocation ColonLoc,
878 ExprTy *Cond, ExprTy *LHS,
879 ExprTy *RHS) {
880 Expr *CondExpr = (Expr *) Cond;
881 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000882
883 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
884 // was the condition.
885 bool isLHSNull = LHSExpr == 0;
886 if (isLHSNull)
887 LHSExpr = CondExpr;
888
Chris Lattner4b009652007-07-25 00:24:17 +0000889 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
890 RHSExpr, QuestionLoc);
891 if (result.isNull())
892 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000893 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
894 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000895}
896
Steve Naroffdb65e052007-08-28 23:30:39 +0000897/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
898/// do not have a prototype. Integer promotions are performed on each
899/// argument, and arguments that have type float are promoted to double.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000900void Sema::DefaultArgumentPromotion(Expr *&Expr) {
901 QualType Ty = Expr->getType();
902 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffdb65e052007-08-28 23:30:39 +0000903
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000904 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
905 promoteExprToType(Expr, Context.IntTy);
906 if (Ty == Context.FloatTy)
907 promoteExprToType(Expr, Context.DoubleTy);
Steve Naroffdb65e052007-08-28 23:30:39 +0000908}
909
Chris Lattner4b009652007-07-25 00:24:17 +0000910/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
911void Sema::DefaultFunctionArrayConversion(Expr *&e) {
912 QualType t = e->getType();
913 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
914
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000915 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000916 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
917 t = e->getType();
918 }
919 if (t->isFunctionType())
920 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000921 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000922 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
923}
924
925/// UsualUnaryConversion - Performs various conversions that are common to most
926/// operators (C99 6.3). The conversions of array and function types are
927/// sometimes surpressed. For example, the array->pointer conversion doesn't
928/// apply if the array is an argument to the sizeof or address (&) operators.
929/// In these instances, this routine should *not* be called.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000930Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
931 QualType Ty = Expr->getType();
932 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000933
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000934 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
935 promoteExprToType(Expr, Ref->getReferenceeType()); // C++ [expr]
936 Ty = Expr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000937 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000938 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
939 promoteExprToType(Expr, Context.IntTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000940 else
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000941 DefaultFunctionArrayConversion(Expr);
942
943 return Expr;
Chris Lattner4b009652007-07-25 00:24:17 +0000944}
945
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000946/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000947/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
948/// routine returns the first non-arithmetic type found. The client is
949/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000950QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
951 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000952 if (!isCompAssign) {
953 UsualUnaryConversions(lhsExpr);
954 UsualUnaryConversions(rhsExpr);
955 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000956 // For conversion purposes, we ignore any qualifiers.
957 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000958 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
959 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000960
961 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000962 if (lhs == rhs)
963 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000964
965 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
966 // The caller can deal with this (e.g. pointer + int).
967 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000968 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000969
970 // At this point, we have two different arithmetic types.
971
972 // Handle complex types first (C99 6.3.1.8p1).
973 if (lhs->isComplexType() || rhs->isComplexType()) {
974 // if we have an integer operand, the result is the complex type.
975 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000976 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
977 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000978 }
979 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000980 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
981 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000982 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000983 // This handles complex/complex, complex/float, or float/complex.
984 // When both operands are complex, the shorter operand is converted to the
985 // type of the longer, and that is the type of the result. This corresponds
986 // to what is done when combining two real floating-point operands.
987 // The fun begins when size promotion occur across type domains.
988 // From H&S 6.3.4: When one operand is complex and the other is a real
989 // floating-point type, the less precise type is converted, within it's
990 // real or complex domain, to the precision of the other type. For example,
991 // when combining a "long double" with a "double _Complex", the
992 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000993 int result = Context.compareFloatingType(lhs, rhs);
994
995 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000996 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
997 if (!isCompAssign)
998 promoteExprToType(rhsExpr, rhs);
999 } else if (result < 0) { // The right side is bigger, convert lhs.
1000 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
1001 if (!isCompAssign)
1002 promoteExprToType(lhsExpr, lhs);
1003 }
1004 // At this point, lhs and rhs have the same rank/size. Now, make sure the
1005 // domains match. This is a requirement for our implementation, C99
1006 // does not require this promotion.
1007 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1008 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001009 if (!isCompAssign)
1010 promoteExprToType(lhsExpr, rhs);
1011 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001012 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001013 if (!isCompAssign)
1014 promoteExprToType(rhsExpr, lhs);
1015 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001016 }
Chris Lattner4b009652007-07-25 00:24:17 +00001017 }
Steve Naroff3b6157f2007-08-27 21:43:43 +00001018 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +00001019 }
1020 // Now handle "real" floating types (i.e. float, double, long double).
1021 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1022 // if we have an integer operand, the result is the real floating type.
1023 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001024 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1025 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001026 }
1027 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001028 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
1029 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001030 }
1031 // We have two real floating types, float/complex combos were handled above.
1032 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +00001033 int result = Context.compareFloatingType(lhs, rhs);
1034
1035 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001036 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1037 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001038 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001039 if (result < 0) { // convert the lhs
1040 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1041 return rhs;
1042 }
1043 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001044 }
1045 // Finally, we have two differing integer types.
1046 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001047 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1048 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001049 }
Steve Naroff8f708362007-08-24 19:07:16 +00001050 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1051 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001052}
1053
1054// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1055// being closely modeled after the C99 spec:-). The odd characteristic of this
1056// routine is it effectively iqnores the qualifiers on the top level pointee.
1057// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1058// FIXME: add a couple examples in this comment.
1059Sema::AssignmentCheckResult
1060Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1061 QualType lhptee, rhptee;
1062
1063 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001064 lhptee = lhsType->getAsPointerType()->getPointeeType();
1065 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001066
1067 // make sure we operate on the canonical type
1068 lhptee = lhptee.getCanonicalType();
1069 rhptee = rhptee.getCanonicalType();
1070
1071 AssignmentCheckResult r = Compatible;
1072
1073 // C99 6.5.16.1p1: This following citation is common to constraints
1074 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1075 // qualifiers of the type *pointed to* by the right;
1076 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1077 rhptee.getQualifiers())
1078 r = CompatiblePointerDiscardsQualifiers;
1079
1080 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1081 // incomplete type and the other is a pointer to a qualified or unqualified
1082 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001083 if (lhptee->isVoidType()) {
1084 if (rhptee->isObjectType() || rhptee->isIncompleteType())
1085 return r;
1086
1087 // As an extension, we allow cast to/from void* to function pointer.
1088 if (rhptee->isFunctionType())
1089 return FunctionVoidPointer;
1090 }
1091
1092 if (rhptee->isVoidType()) {
1093 if (lhptee->isObjectType() || lhptee->isIncompleteType())
1094 return r;
1095
1096 // As an extension, we allow cast to/from void* to function pointer.
1097 if (lhptee->isFunctionType())
1098 return FunctionVoidPointer;
1099 }
1100
Chris Lattner4b009652007-07-25 00:24:17 +00001101 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1102 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001103 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1104 rhptee.getUnqualifiedType()))
1105 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner4b009652007-07-25 00:24:17 +00001106 return r;
1107}
1108
1109/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1110/// has code to accommodate several GCC extensions when type checking
1111/// pointers. Here are some objectionable examples that GCC considers warnings:
1112///
1113/// int a, *pint;
1114/// short *pshort;
1115/// struct foo *pfoo;
1116///
1117/// pint = pshort; // warning: assignment from incompatible pointer type
1118/// a = pint; // warning: assignment makes integer from pointer without a cast
1119/// pint = a; // warning: assignment makes pointer from integer without a cast
1120/// pint = pfoo; // warning: assignment from incompatible pointer type
1121///
1122/// As a result, the code for dealing with pointers is more complex than the
1123/// C99 spec dictates.
1124/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1125///
1126Sema::AssignmentCheckResult
1127Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001128
1129
Steve Naroffeed76842007-11-13 00:31:42 +00001130 if (lhsType.getCanonicalType().getUnqualifiedType() ==
1131 rhsType.getCanonicalType().getUnqualifiedType())
Chris Lattnera703c2e2007-10-29 05:15:40 +00001132 return Compatible; // common case, fast path...
Chris Lattner4b009652007-07-25 00:24:17 +00001133
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001134 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001135 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001136 return Compatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001137 }
1138 else if (lhsType->isObjcQualifiedIdType()
1139 || rhsType->isObjcQualifiedIdType()) {
1140 if (Context.ObjcQualifiedIdTypesAreCompatible(lhsType, rhsType))
1141 return Compatible;
1142 }
1143 else if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001144 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001145 // For OCUVector, allow vector splats; float -> <n x float>
1146 if (const OCUVectorType *LV = lhsType->getAsOCUVectorType()) {
1147 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1148 return Compatible;
1149 }
Anders Carlssone87cd982007-11-30 04:21:22 +00001150 if (!getLangOptions().LaxVectorConversions) {
1151 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1152 return Incompatible;
1153 } else {
1154 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemana6a1bc02007-12-30 01:45:55 +00001155 // If LHS and RHS are both integer or both floating point types, and
1156 // the total vector length is the same, allow the conversion. This is
1157 // a bitcast; no bits are changed but the result type is different.
Anders Carlssone87cd982007-11-30 04:21:22 +00001158 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1159 (lhsType->isRealFloatingType() &&
1160 rhsType->isRealFloatingType())) {
1161 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1162 Context.getTypeSize(rhsType, SourceLocation()))
1163 return Compatible;
1164 }
1165 }
Chris Lattner4b009652007-07-25 00:24:17 +00001166 return Incompatible;
Anders Carlssone87cd982007-11-30 04:21:22 +00001167 }
1168 }
Chris Lattner4b009652007-07-25 00:24:17 +00001169 return Compatible;
1170 } else if (lhsType->isPointerType()) {
1171 if (rhsType->isIntegerType())
1172 return PointerFromInt;
1173
1174 if (rhsType->isPointerType())
1175 return CheckPointerTypesForAssignment(lhsType, rhsType);
1176 } else if (rhsType->isPointerType()) {
1177 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1178 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1179 return IntFromPointer;
1180
1181 if (lhsType->isPointerType())
1182 return CheckPointerTypesForAssignment(lhsType, rhsType);
1183 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001184 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001185 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001186 }
1187 return Incompatible;
1188}
1189
1190Sema::AssignmentCheckResult
1191Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001192 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1193 // a null pointer constant.
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001194 if ((lhsType->isPointerType() || lhsType->isObjcQualifiedIdType())
1195 && rExpr->isNullPointerConstant(Context)) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001196 promoteExprToType(rExpr, lhsType);
1197 return Compatible;
1198 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001199 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001200 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001201 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001202 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001203 //
1204 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1205 // are better understood.
1206 if (!lhsType->isReferenceType())
1207 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001208
1209 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +00001210
Steve Naroff0f32f432007-08-24 22:33:52 +00001211 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1212
1213 // C99 6.5.16.1p2: The value of the right operand is converted to the
1214 // type of the assignment expression.
1215 if (rExpr->getType() != lhsType)
1216 promoteExprToType(rExpr, lhsType);
1217 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001218}
1219
1220Sema::AssignmentCheckResult
1221Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1222 return CheckAssignmentConstraints(lhsType, rhsType);
1223}
1224
Chris Lattner2c8bff72007-12-12 05:47:28 +00001225QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001226 Diag(loc, diag::err_typecheck_invalid_operands,
1227 lex->getType().getAsString(), rex->getType().getAsString(),
1228 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001229 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001230}
1231
1232inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1233 Expr *&rex) {
1234 QualType lhsType = lex->getType(), rhsType = rex->getType();
1235
1236 // make sure the vector types are identical.
1237 if (lhsType == rhsType)
1238 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001239
1240 // if the lhs is an ocu vector and the rhs is a scalar of the same type,
1241 // promote the rhs to the vector type.
1242 if (const OCUVectorType *V = lhsType->getAsOCUVectorType()) {
1243 if (V->getElementType().getCanonicalType().getTypePtr()
1244 == rhsType.getCanonicalType().getTypePtr()) {
1245 promoteExprToType(rex, lhsType);
1246 return lhsType;
1247 }
1248 }
1249
1250 // if the rhs is an ocu vector and the lhs is a scalar of the same type,
1251 // promote the lhs to the vector type.
1252 if (const OCUVectorType *V = rhsType->getAsOCUVectorType()) {
1253 if (V->getElementType().getCanonicalType().getTypePtr()
1254 == lhsType.getCanonicalType().getTypePtr()) {
1255 promoteExprToType(lex, rhsType);
1256 return rhsType;
1257 }
1258 }
1259
Chris Lattner4b009652007-07-25 00:24:17 +00001260 // You cannot convert between vector values of different size.
1261 Diag(loc, diag::err_typecheck_vector_not_convertable,
1262 lex->getType().getAsString(), rex->getType().getAsString(),
1263 lex->getSourceRange(), rex->getSourceRange());
1264 return QualType();
1265}
1266
1267inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001268 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001269{
1270 QualType lhsType = lex->getType(), rhsType = rex->getType();
1271
1272 if (lhsType->isVectorType() || rhsType->isVectorType())
1273 return CheckVectorOperands(loc, lex, rex);
1274
Steve Naroff8f708362007-08-24 19:07:16 +00001275 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001276
Chris Lattner4b009652007-07-25 00:24:17 +00001277 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001278 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001279 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001280}
1281
1282inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001283 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001284{
1285 QualType lhsType = lex->getType(), rhsType = rex->getType();
1286
Steve Naroff8f708362007-08-24 19:07:16 +00001287 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001288
Chris Lattner4b009652007-07-25 00:24:17 +00001289 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001290 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001291 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001292}
1293
1294inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001295 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001296{
1297 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1298 return CheckVectorOperands(loc, lex, rex);
1299
Steve Naroff8f708362007-08-24 19:07:16 +00001300 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001301
1302 // handle the common case first (both operands are arithmetic).
1303 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001304 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001305
1306 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1307 return lex->getType();
1308 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1309 return rex->getType();
Chris Lattner2c8bff72007-12-12 05:47:28 +00001310 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001311}
1312
1313inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001314 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001315{
1316 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1317 return CheckVectorOperands(loc, lex, rex);
1318
Steve Naroff8f708362007-08-24 19:07:16 +00001319 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001320
Chris Lattnerf6da2912007-12-09 21:53:25 +00001321 // Enforce type constraints: C99 6.5.6p3.
1322
1323 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001324 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001325 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001326
1327 // Either ptr - int or ptr - ptr.
1328 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1329 // The LHS must be an object type, not incomplete, function, etc.
1330 if (!LHSPTy->getPointeeType()->isObjectType()) {
1331 // Handle the GNU void* extension.
1332 if (LHSPTy->getPointeeType()->isVoidType()) {
1333 Diag(loc, diag::ext_gnu_void_ptr,
1334 lex->getSourceRange(), rex->getSourceRange());
1335 } else {
1336 Diag(loc, diag::err_typecheck_sub_ptr_object,
1337 lex->getType().getAsString(), lex->getSourceRange());
1338 return QualType();
1339 }
1340 }
1341
1342 // The result type of a pointer-int computation is the pointer type.
1343 if (rex->getType()->isIntegerType())
1344 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001345
Chris Lattnerf6da2912007-12-09 21:53:25 +00001346 // Handle pointer-pointer subtractions.
1347 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1348 // RHS must be an object type, unless void (GNU).
1349 if (!RHSPTy->getPointeeType()->isObjectType()) {
1350 // Handle the GNU void* extension.
1351 if (RHSPTy->getPointeeType()->isVoidType()) {
1352 if (!LHSPTy->getPointeeType()->isVoidType())
1353 Diag(loc, diag::ext_gnu_void_ptr,
1354 lex->getSourceRange(), rex->getSourceRange());
1355 } else {
1356 Diag(loc, diag::err_typecheck_sub_ptr_object,
1357 rex->getType().getAsString(), rex->getSourceRange());
1358 return QualType();
1359 }
1360 }
1361
1362 // Pointee types must be compatible.
1363 if (!Context.typesAreCompatible(LHSPTy->getPointeeType(),
1364 RHSPTy->getPointeeType())) {
1365 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1366 lex->getType().getAsString(), rex->getType().getAsString(),
1367 lex->getSourceRange(), rex->getSourceRange());
1368 return QualType();
1369 }
1370
1371 return Context.getPointerDiffType();
1372 }
1373 }
1374
Chris Lattner2c8bff72007-12-12 05:47:28 +00001375 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001376}
1377
1378inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Chris Lattner2c8bff72007-12-12 05:47:28 +00001379 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1380 // C99 6.5.7p2: Each of the operands shall have integer type.
1381 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1382 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001383
Chris Lattner2c8bff72007-12-12 05:47:28 +00001384 // Shifts don't perform usual arithmetic conversions, they just do integer
1385 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001386 if (!isCompAssign)
1387 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001388 UsualUnaryConversions(rex);
1389
1390 // "The type of the result is that of the promoted left operand."
1391 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001392}
1393
Chris Lattner254f3bc2007-08-26 01:18:55 +00001394inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1395 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001396{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001397 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001398 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1399 UsualArithmeticConversions(lex, rex);
1400 else {
1401 UsualUnaryConversions(lex);
1402 UsualUnaryConversions(rex);
1403 }
Chris Lattner4b009652007-07-25 00:24:17 +00001404 QualType lType = lex->getType();
1405 QualType rType = rex->getType();
1406
Ted Kremenek486509e2007-10-29 17:13:39 +00001407 // For non-floating point types, check for self-comparisons of the form
1408 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1409 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001410 if (!lType->isFloatingType()) {
1411 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1412 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1413 if (DRL->getDecl() == DRR->getDecl())
1414 Diag(loc, diag::warn_selfcomparison);
1415 }
1416
Chris Lattner254f3bc2007-08-26 01:18:55 +00001417 if (isRelational) {
1418 if (lType->isRealType() && rType->isRealType())
1419 return Context.IntTy;
1420 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001421 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001422 if (lType->isFloatingType()) {
1423 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001424 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001425 }
1426
Chris Lattner254f3bc2007-08-26 01:18:55 +00001427 if (lType->isArithmeticType() && rType->isArithmeticType())
1428 return Context.IntTy;
1429 }
Chris Lattner4b009652007-07-25 00:24:17 +00001430
Chris Lattner22be8422007-08-26 01:10:14 +00001431 bool LHSIsNull = lex->isNullPointerConstant(Context);
1432 bool RHSIsNull = rex->isNullPointerConstant(Context);
1433
Chris Lattner254f3bc2007-08-26 01:18:55 +00001434 // All of the following pointer related warnings are GCC extensions, except
1435 // when handling null pointer constants. One day, we can consider making them
1436 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001437 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff3b435622007-11-13 14:57:38 +00001438
1439 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1440 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1441 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroff85f0dc52007-10-15 20:41:53 +00001442 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1443 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001444 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1445 lType.getAsString(), rType.getAsString(),
1446 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001447 }
Chris Lattner22be8422007-08-26 01:10:14 +00001448 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001449 return Context.IntTy;
1450 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001451 if ((lType->isObjcQualifiedIdType() || rType->isObjcQualifiedIdType())
Fariborz Jahaniancd71bf42007-12-21 00:33:59 +00001452 && Context.ObjcQualifiedIdTypesAreCompatible(lType, rType, true)) {
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001453 promoteExprToType(rex, lType);
1454 return Context.IntTy;
1455 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001456 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001457 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001458 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1459 lType.getAsString(), rType.getAsString(),
1460 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001461 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001462 return Context.IntTy;
1463 }
1464 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001465 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001466 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1467 lType.getAsString(), rType.getAsString(),
1468 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001469 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001470 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001471 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001472 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001473}
1474
Chris Lattner4b009652007-07-25 00:24:17 +00001475inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001476 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001477{
1478 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1479 return CheckVectorOperands(loc, lex, rex);
1480
Steve Naroff8f708362007-08-24 19:07:16 +00001481 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001482
1483 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001484 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001485 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001486}
1487
1488inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1489 Expr *&lex, Expr *&rex, SourceLocation loc)
1490{
1491 UsualUnaryConversions(lex);
1492 UsualUnaryConversions(rex);
1493
1494 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1495 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001496 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001497}
1498
1499inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001500 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001501{
1502 QualType lhsType = lex->getType();
1503 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1504 bool hadError = false;
1505 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1506
1507 switch (mlval) { // C99 6.5.16p2
1508 case Expr::MLV_Valid:
1509 break;
1510 case Expr::MLV_ConstQualified:
1511 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1512 hadError = true;
1513 break;
1514 case Expr::MLV_ArrayType:
1515 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1516 lhsType.getAsString(), lex->getSourceRange());
1517 return QualType();
1518 case Expr::MLV_NotObjectType:
1519 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1520 lhsType.getAsString(), lex->getSourceRange());
1521 return QualType();
1522 case Expr::MLV_InvalidExpression:
1523 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1524 lex->getSourceRange());
1525 return QualType();
1526 case Expr::MLV_IncompleteType:
1527 case Expr::MLV_IncompleteVoidType:
1528 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1529 lhsType.getAsString(), lex->getSourceRange());
1530 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001531 case Expr::MLV_DuplicateVectorComponents:
1532 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1533 lex->getSourceRange());
1534 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001535 }
1536 AssignmentCheckResult result;
1537
1538 if (compoundType.isNull())
1539 result = CheckSingleAssignmentConstraints(lhsType, rex);
1540 else
1541 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001542
Chris Lattner4b009652007-07-25 00:24:17 +00001543 // decode the result (notice that extensions still return a type).
1544 switch (result) {
1545 case Compatible:
1546 break;
1547 case Incompatible:
1548 Diag(loc, diag::err_typecheck_assign_incompatible,
1549 lhsType.getAsString(), rhsType.getAsString(),
1550 lex->getSourceRange(), rex->getSourceRange());
1551 hadError = true;
1552 break;
1553 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +00001554 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1555 lhsType.getAsString(), rhsType.getAsString(),
1556 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001557 break;
1558 case IntFromPointer:
1559 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1560 lhsType.getAsString(), rhsType.getAsString(),
1561 lex->getSourceRange(), rex->getSourceRange());
1562 break;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001563 case FunctionVoidPointer:
1564 Diag(loc, diag::ext_typecheck_assign_pointer_void_func,
1565 lhsType.getAsString(), rhsType.getAsString(),
1566 lex->getSourceRange(), rex->getSourceRange());
1567 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001568 case IncompatiblePointer:
1569 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1570 lhsType.getAsString(), rhsType.getAsString(),
1571 lex->getSourceRange(), rex->getSourceRange());
1572 break;
1573 case CompatiblePointerDiscardsQualifiers:
1574 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1575 lhsType.getAsString(), rhsType.getAsString(),
1576 lex->getSourceRange(), rex->getSourceRange());
1577 break;
1578 }
1579 // C99 6.5.16p3: The type of an assignment expression is the type of the
1580 // left operand unless the left operand has qualified type, in which case
1581 // it is the unqualified version of the type of the left operand.
1582 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1583 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001584 // C++ 5.17p1: the type of the assignment expression is that of its left
1585 // oprdu.
Chris Lattner4b009652007-07-25 00:24:17 +00001586 return hadError ? QualType() : lhsType.getUnqualifiedType();
1587}
1588
1589inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1590 Expr *&lex, Expr *&rex, SourceLocation loc) {
1591 UsualUnaryConversions(rex);
1592 return rex->getType();
1593}
1594
1595/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1596/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1597QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1598 QualType resType = op->getType();
1599 assert(!resType.isNull() && "no type for increment/decrement expression");
1600
Steve Naroffd30e1932007-08-24 17:20:07 +00001601 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001602 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001603 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1604 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1605 resType.getAsString(), op->getSourceRange());
1606 return QualType();
1607 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001608 } else if (!resType->isRealType()) {
1609 if (resType->isComplexType())
1610 // C99 does not support ++/-- on complex types.
1611 Diag(OpLoc, diag::ext_integer_increment_complex,
1612 resType.getAsString(), op->getSourceRange());
1613 else {
1614 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1615 resType.getAsString(), op->getSourceRange());
1616 return QualType();
1617 }
Chris Lattner4b009652007-07-25 00:24:17 +00001618 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001619 // At this point, we know we have a real, complex or pointer type.
1620 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001621 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1622 if (mlval != Expr::MLV_Valid) {
1623 // FIXME: emit a more precise diagnostic...
1624 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1625 op->getSourceRange());
1626 return QualType();
1627 }
1628 return resType;
1629}
1630
1631/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1632/// This routine allows us to typecheck complex/recursive expressions
1633/// where the declaration is needed for type checking. Here are some
1634/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1635static Decl *getPrimaryDeclaration(Expr *e) {
1636 switch (e->getStmtClass()) {
1637 case Stmt::DeclRefExprClass:
1638 return cast<DeclRefExpr>(e)->getDecl();
1639 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001640 // Fields cannot be declared with a 'register' storage class.
1641 // &X->f is always ok, even if X is declared register.
1642 if (cast<MemberExpr>(e)->isArrow())
1643 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001644 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1645 case Stmt::ArraySubscriptExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001646 // &X[4] and &4[X] is invalid if X is invalid.
Chris Lattner4b009652007-07-25 00:24:17 +00001647 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +00001648 case Stmt::UnaryOperatorClass:
1649 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1650 case Stmt::ParenExprClass:
1651 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001652 case Stmt::ImplicitCastExprClass:
1653 // &X[4] when X is an array, has an implicit cast from array to pointer.
1654 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001655 default:
1656 return 0;
1657 }
1658}
1659
1660/// CheckAddressOfOperand - The operand of & must be either a function
1661/// designator or an lvalue designating an object. If it is an lvalue, the
1662/// object cannot be declared with storage class register or be a bit field.
1663/// Note: The usual conversions are *not* applied to the operand of the &
1664/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1665QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1666 Decl *dcl = getPrimaryDeclaration(op);
1667 Expr::isLvalueResult lval = op->isLvalue();
1668
1669 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001670 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1671 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001672 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1673 op->getSourceRange());
1674 return QualType();
1675 }
1676 } else if (dcl) {
1677 // We have an lvalue with a decl. Make sure the decl is not declared
1678 // with the register storage-class specifier.
1679 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1680 if (vd->getStorageClass() == VarDecl::Register) {
1681 Diag(OpLoc, diag::err_typecheck_address_of_register,
1682 op->getSourceRange());
1683 return QualType();
1684 }
1685 } else
1686 assert(0 && "Unknown/unexpected decl type");
1687
1688 // FIXME: add check for bitfields!
1689 }
1690 // If the operand has type "type", the result has type "pointer to type".
1691 return Context.getPointerType(op->getType());
1692}
1693
1694QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1695 UsualUnaryConversions(op);
1696 QualType qType = op->getType();
1697
Chris Lattner7931f4a2007-07-31 16:53:04 +00001698 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001699 QualType ptype = PT->getPointeeType();
1700 // C99 6.5.3.2p4. "if it points to an object,...".
1701 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1702 // GCC compat: special case 'void *' (treat as warning).
1703 if (ptype->isVoidType()) {
1704 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1705 qType.getAsString(), op->getSourceRange());
1706 } else {
1707 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1708 ptype.getAsString(), op->getSourceRange());
1709 return QualType();
1710 }
1711 }
1712 return ptype;
1713 }
1714 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1715 qType.getAsString(), op->getSourceRange());
1716 return QualType();
1717}
1718
1719static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1720 tok::TokenKind Kind) {
1721 BinaryOperator::Opcode Opc;
1722 switch (Kind) {
1723 default: assert(0 && "Unknown binop!");
1724 case tok::star: Opc = BinaryOperator::Mul; break;
1725 case tok::slash: Opc = BinaryOperator::Div; break;
1726 case tok::percent: Opc = BinaryOperator::Rem; break;
1727 case tok::plus: Opc = BinaryOperator::Add; break;
1728 case tok::minus: Opc = BinaryOperator::Sub; break;
1729 case tok::lessless: Opc = BinaryOperator::Shl; break;
1730 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1731 case tok::lessequal: Opc = BinaryOperator::LE; break;
1732 case tok::less: Opc = BinaryOperator::LT; break;
1733 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1734 case tok::greater: Opc = BinaryOperator::GT; break;
1735 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1736 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1737 case tok::amp: Opc = BinaryOperator::And; break;
1738 case tok::caret: Opc = BinaryOperator::Xor; break;
1739 case tok::pipe: Opc = BinaryOperator::Or; break;
1740 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1741 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1742 case tok::equal: Opc = BinaryOperator::Assign; break;
1743 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1744 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1745 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1746 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1747 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1748 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1749 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1750 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1751 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1752 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1753 case tok::comma: Opc = BinaryOperator::Comma; break;
1754 }
1755 return Opc;
1756}
1757
1758static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1759 tok::TokenKind Kind) {
1760 UnaryOperator::Opcode Opc;
1761 switch (Kind) {
1762 default: assert(0 && "Unknown unary op!");
1763 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1764 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1765 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1766 case tok::star: Opc = UnaryOperator::Deref; break;
1767 case tok::plus: Opc = UnaryOperator::Plus; break;
1768 case tok::minus: Opc = UnaryOperator::Minus; break;
1769 case tok::tilde: Opc = UnaryOperator::Not; break;
1770 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1771 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1772 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1773 case tok::kw___real: Opc = UnaryOperator::Real; break;
1774 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1775 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1776 }
1777 return Opc;
1778}
1779
1780// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001781Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001782 ExprTy *LHS, ExprTy *RHS) {
1783 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1784 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1785
Steve Naroff87d58b42007-09-16 03:34:24 +00001786 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1787 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001788
1789 QualType ResultTy; // Result type of the binary operator.
1790 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1791
1792 switch (Opc) {
1793 default:
1794 assert(0 && "Unknown binary expr!");
1795 case BinaryOperator::Assign:
1796 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1797 break;
1798 case BinaryOperator::Mul:
1799 case BinaryOperator::Div:
1800 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1801 break;
1802 case BinaryOperator::Rem:
1803 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1804 break;
1805 case BinaryOperator::Add:
1806 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1807 break;
1808 case BinaryOperator::Sub:
1809 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1810 break;
1811 case BinaryOperator::Shl:
1812 case BinaryOperator::Shr:
1813 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1814 break;
1815 case BinaryOperator::LE:
1816 case BinaryOperator::LT:
1817 case BinaryOperator::GE:
1818 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001819 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001820 break;
1821 case BinaryOperator::EQ:
1822 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001823 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001824 break;
1825 case BinaryOperator::And:
1826 case BinaryOperator::Xor:
1827 case BinaryOperator::Or:
1828 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1829 break;
1830 case BinaryOperator::LAnd:
1831 case BinaryOperator::LOr:
1832 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1833 break;
1834 case BinaryOperator::MulAssign:
1835 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001836 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001837 if (!CompTy.isNull())
1838 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1839 break;
1840 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001841 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001842 if (!CompTy.isNull())
1843 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1844 break;
1845 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001846 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001847 if (!CompTy.isNull())
1848 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1849 break;
1850 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001851 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001852 if (!CompTy.isNull())
1853 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1854 break;
1855 case BinaryOperator::ShlAssign:
1856 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001857 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001858 if (!CompTy.isNull())
1859 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1860 break;
1861 case BinaryOperator::AndAssign:
1862 case BinaryOperator::XorAssign:
1863 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001864 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001865 if (!CompTy.isNull())
1866 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1867 break;
1868 case BinaryOperator::Comma:
1869 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1870 break;
1871 }
1872 if (ResultTy.isNull())
1873 return true;
1874 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001875 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001876 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001877 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001878}
1879
1880// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001881Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001882 ExprTy *input) {
1883 Expr *Input = (Expr*)input;
1884 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1885 QualType resultType;
1886 switch (Opc) {
1887 default:
1888 assert(0 && "Unimplemented unary expr!");
1889 case UnaryOperator::PreInc:
1890 case UnaryOperator::PreDec:
1891 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1892 break;
1893 case UnaryOperator::AddrOf:
1894 resultType = CheckAddressOfOperand(Input, OpLoc);
1895 break;
1896 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00001897 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00001898 resultType = CheckIndirectionOperand(Input, OpLoc);
1899 break;
1900 case UnaryOperator::Plus:
1901 case UnaryOperator::Minus:
1902 UsualUnaryConversions(Input);
1903 resultType = Input->getType();
1904 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1905 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1906 resultType.getAsString());
1907 break;
1908 case UnaryOperator::Not: // bitwise complement
1909 UsualUnaryConversions(Input);
1910 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001911 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1912 if (!resultType->isIntegerType()) {
1913 if (resultType->isComplexType())
1914 // C99 does not support '~' for complex conjugation.
1915 Diag(OpLoc, diag::ext_integer_complement_complex,
1916 resultType.getAsString());
1917 else
1918 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1919 resultType.getAsString());
1920 }
Chris Lattner4b009652007-07-25 00:24:17 +00001921 break;
1922 case UnaryOperator::LNot: // logical negation
1923 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1924 DefaultFunctionArrayConversion(Input);
1925 resultType = Input->getType();
1926 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1927 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1928 resultType.getAsString());
1929 // LNot always has type int. C99 6.5.3.3p5.
1930 resultType = Context.IntTy;
1931 break;
1932 case UnaryOperator::SizeOf:
1933 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1934 break;
1935 case UnaryOperator::AlignOf:
1936 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1937 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001938 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001939 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001940 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001941 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001942 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001943 resultType = Input->getType();
1944 break;
1945 }
1946 if (resultType.isNull())
1947 return true;
1948 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1949}
1950
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001951/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1952Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001953 SourceLocation LabLoc,
1954 IdentifierInfo *LabelII) {
1955 // Look up the record for this label identifier.
1956 LabelStmt *&LabelDecl = LabelMap[LabelII];
1957
1958 // If we haven't seen this label yet, create a forward reference.
1959 if (LabelDecl == 0)
1960 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1961
1962 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001963 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1964 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001965}
1966
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001967Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00001968 SourceLocation RPLoc) { // "({..})"
1969 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1970 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1971 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1972
1973 // FIXME: there are a variety of strange constraints to enforce here, for
1974 // example, it is not possible to goto into a stmt expression apparently.
1975 // More semantic analysis is needed.
1976
1977 // FIXME: the last statement in the compount stmt has its value used. We
1978 // should not warn about it being unused.
1979
1980 // If there are sub stmts in the compound stmt, take the type of the last one
1981 // as the type of the stmtexpr.
1982 QualType Ty = Context.VoidTy;
1983
1984 if (!Compound->body_empty())
1985 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1986 Ty = LastExpr->getType();
1987
1988 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1989}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001990
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001991Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001992 SourceLocation TypeLoc,
1993 TypeTy *argty,
1994 OffsetOfComponent *CompPtr,
1995 unsigned NumComponents,
1996 SourceLocation RPLoc) {
1997 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1998 assert(!ArgTy.isNull() && "Missing type argument!");
1999
2000 // We must have at least one component that refers to the type, and the first
2001 // one is known to be a field designator. Verify that the ArgTy represents
2002 // a struct/union/class.
2003 if (!ArgTy->isRecordType())
2004 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2005
2006 // Otherwise, create a compound literal expression as the base, and
2007 // iteratively process the offsetof designators.
Chris Lattner386ab8a2008-01-02 21:46:24 +00002008 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002009
Chris Lattnerb37522e2007-08-31 21:49:13 +00002010 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2011 // GCC extension, diagnose them.
2012 if (NumComponents != 1)
2013 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2014 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2015
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002016 for (unsigned i = 0; i != NumComponents; ++i) {
2017 const OffsetOfComponent &OC = CompPtr[i];
2018 if (OC.isBrackets) {
2019 // Offset of an array sub-field. TODO: Should we allow vector elements?
2020 const ArrayType *AT = Res->getType()->getAsArrayType();
2021 if (!AT) {
2022 delete Res;
2023 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2024 Res->getType().getAsString());
2025 }
2026
Chris Lattner2af6a802007-08-30 17:59:59 +00002027 // FIXME: C++: Verify that operator[] isn't overloaded.
2028
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002029 // C99 6.5.2.1p1
2030 Expr *Idx = static_cast<Expr*>(OC.U.E);
2031 if (!Idx->getType()->isIntegerType())
2032 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2033 Idx->getSourceRange());
2034
2035 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2036 continue;
2037 }
2038
2039 const RecordType *RC = Res->getType()->getAsRecordType();
2040 if (!RC) {
2041 delete Res;
2042 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2043 Res->getType().getAsString());
2044 }
2045
2046 // Get the decl corresponding to this.
2047 RecordDecl *RD = RC->getDecl();
2048 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2049 if (!MemberDecl)
2050 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2051 OC.U.IdentInfo->getName(),
2052 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002053
2054 // FIXME: C++: Verify that MemberDecl isn't a static field.
2055 // FIXME: Verify that MemberDecl isn't a bitfield.
2056
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002057 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
2058 }
2059
2060 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2061 BuiltinLoc);
2062}
2063
2064
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002065Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002066 TypeTy *arg1, TypeTy *arg2,
2067 SourceLocation RPLoc) {
2068 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2069 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2070
2071 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2072
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002073 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002074}
2075
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002076Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002077 ExprTy *expr1, ExprTy *expr2,
2078 SourceLocation RPLoc) {
2079 Expr *CondExpr = static_cast<Expr*>(cond);
2080 Expr *LHSExpr = static_cast<Expr*>(expr1);
2081 Expr *RHSExpr = static_cast<Expr*>(expr2);
2082
2083 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2084
2085 // The conditional expression is required to be a constant expression.
2086 llvm::APSInt condEval(32);
2087 SourceLocation ExpLoc;
2088 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2089 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2090 CondExpr->getSourceRange());
2091
2092 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2093 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2094 RHSExpr->getType();
2095 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2096}
2097
Anders Carlsson36760332007-10-15 20:28:48 +00002098Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2099 ExprTy *expr, TypeTy *type,
2100 SourceLocation RPLoc)
2101{
2102 Expr *E = static_cast<Expr*>(expr);
2103 QualType T = QualType::getFromOpaquePtr(type);
2104
2105 InitBuiltinVaListType();
2106
2107 Sema::AssignmentCheckResult result;
2108
2109 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
2110 E->getType());
2111 if (result != Compatible)
2112 return Diag(E->getLocStart(),
2113 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2114 E->getType().getAsString(),
2115 E->getSourceRange());
2116
2117 // FIXME: Warn if a non-POD type is passed in.
2118
2119 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2120}
2121
Anders Carlssona66cad42007-08-21 17:43:55 +00002122// TODO: Move this to SemaObjC.cpp
Chris Lattnerddd3e632007-12-12 01:04:12 +00002123Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
2124 ExprTy **Strings,
2125 unsigned NumStrings) {
Chris Lattnerddd3e632007-12-12 01:04:12 +00002126 SourceLocation AtLoc = AtLocs[0];
2127 StringLiteral* S = static_cast<StringLiteral *>(Strings[0]);
Fariborz Jahanian1a442d32007-12-12 23:55:49 +00002128 if (NumStrings > 1) {
2129 // Concatenate objc strings.
2130 StringLiteral* ES = static_cast<StringLiteral *>(Strings[NumStrings-1]);
2131 SourceLocation EndLoc = ES->getSourceRange().getEnd();
2132 unsigned Length = 0;
2133 for (unsigned i = 0; i < NumStrings; i++)
2134 Length += static_cast<StringLiteral *>(Strings[i])->getByteLength();
2135 char *strBuf = new char [Length];
2136 char *p = strBuf;
2137 bool isWide = false;
2138 for (unsigned i = 0; i < NumStrings; i++) {
2139 S = static_cast<StringLiteral *>(Strings[i]);
2140 if (S->isWide())
2141 isWide = true;
2142 memcpy(p, S->getStrData(), S->getByteLength());
2143 p += S->getByteLength();
2144 delete S;
2145 }
2146 S = new StringLiteral(strBuf, Length,
2147 isWide, Context.getPointerType(Context.CharTy),
2148 AtLoc, EndLoc);
2149 }
Anders Carlssona66cad42007-08-21 17:43:55 +00002150
2151 if (CheckBuiltinCFStringArgument(S))
2152 return true;
2153
Steve Narofff2e30312007-10-15 23:35:17 +00002154 if (Context.getObjcConstantStringInterface().isNull()) {
2155 // Initialize the constant string interface lazily. This assumes
2156 // the NSConstantString interface is seen in this translation unit.
2157 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
2158 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
2159 SourceLocation(), TUScope);
Steve Naroff134c3502007-10-16 00:00:18 +00002160 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff96f136d2007-10-18 23:53:51 +00002161 if (!strIFace)
2162 return Diag(S->getLocStart(), diag::err_undef_interface,
2163 NSIdent->getName());
Steve Naroff134c3502007-10-16 00:00:18 +00002164 Context.setObjcConstantStringInterface(strIFace);
Steve Narofff2e30312007-10-15 23:35:17 +00002165 }
2166 QualType t = Context.getObjcConstantStringInterface();
Anders Carlssona66cad42007-08-21 17:43:55 +00002167 t = Context.getPointerType(t);
Steve Naroff0add5d22007-11-03 11:27:19 +00002168 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlssona66cad42007-08-21 17:43:55 +00002169}
Anders Carlsson8be1d402007-08-22 15:14:15 +00002170
2171Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattnercfd61c82007-10-16 22:51:17 +00002172 SourceLocation EncodeLoc,
Anders Carlsson8be1d402007-08-22 15:14:15 +00002173 SourceLocation LParenLoc,
2174 TypeTy *Ty,
2175 SourceLocation RParenLoc) {
2176 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
2177
2178 QualType t = Context.getPointerType(Context.CharTy);
2179 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
2180}
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002181
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002182Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
2183 SourceLocation AtLoc,
Fariborz Jahanian957448a2007-10-16 23:21:02 +00002184 SourceLocation SelLoc,
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002185 SourceLocation LParenLoc,
2186 SourceLocation RParenLoc) {
Steve Naroffae84af82007-10-31 18:42:27 +00002187 QualType t = Context.getObjcSelType();
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002188 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
2189}
2190
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002191Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
2192 SourceLocation AtLoc,
2193 SourceLocation ProtoLoc,
2194 SourceLocation LParenLoc,
2195 SourceLocation RParenLoc) {
2196 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
2197 if (!PDecl) {
2198 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
2199 return true;
2200 }
2201
Fariborz Jahanianb4452ed2007-12-07 00:18:54 +00002202 QualType t = Context.getObjcProtoType();
Fariborz Jahanian20b40e42007-10-18 22:59:23 +00002203 if (t.isNull())
2204 return true;
Fariborz Jahanianb4452ed2007-12-07 00:18:54 +00002205 t = Context.getPointerType(t);
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002206 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
2207}
Steve Naroff52664182007-10-16 23:12:48 +00002208
2209bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2210 ObjcMethodDecl *Method) {
2211 bool anyIncompatibleArgs = false;
2212
2213 for (unsigned i = 0; i < NumArgs; i++) {
2214 Expr *argExpr = Args[i];
2215 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2216
2217 QualType lhsType = Method->getParamDecl(i)->getType();
2218 QualType rhsType = argExpr->getType();
2219
2220 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2221 if (const ArrayType *ary = lhsType->getAsArrayType())
2222 lhsType = Context.getPointerType(ary->getElementType());
2223 else if (lhsType->isFunctionType())
2224 lhsType = Context.getPointerType(lhsType);
2225
2226 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2227 argExpr);
2228 if (Args[i] != argExpr) // The expression was converted.
2229 Args[i] = argExpr; // Make sure we store the converted expression.
2230 SourceLocation l = argExpr->getLocStart();
2231
2232 // decode the result (notice that AST's are still created for extensions).
2233 switch (result) {
2234 case Compatible:
2235 break;
2236 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +00002237 Diag(l, diag::ext_typecheck_sending_pointer_int,
2238 lhsType.getAsString(), rhsType.getAsString(),
2239 argExpr->getSourceRange());
Steve Naroff52664182007-10-16 23:12:48 +00002240 break;
2241 case IntFromPointer:
2242 Diag(l, diag::ext_typecheck_sending_pointer_int,
2243 lhsType.getAsString(), rhsType.getAsString(),
2244 argExpr->getSourceRange());
2245 break;
2246 case IncompatiblePointer:
2247 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2248 rhsType.getAsString(), lhsType.getAsString(),
2249 argExpr->getSourceRange());
2250 break;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002251 case FunctionVoidPointer:
2252 Diag(l, diag::ext_typecheck_sending_pointer_void_func,
2253 rhsType.getAsString(), lhsType.getAsString(),
2254 argExpr->getSourceRange());
2255 break;
Steve Naroff52664182007-10-16 23:12:48 +00002256 case CompatiblePointerDiscardsQualifiers:
2257 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2258 rhsType.getAsString(), lhsType.getAsString(),
2259 argExpr->getSourceRange());
2260 break;
2261 case Incompatible:
2262 Diag(l, diag::err_typecheck_sending_incompatible,
2263 rhsType.getAsString(), lhsType.getAsString(),
2264 argExpr->getSourceRange());
2265 anyIncompatibleArgs = true;
2266 }
2267 }
2268 return anyIncompatibleArgs;
2269}
2270
Steve Naroff4ed9d662007-09-27 14:38:14 +00002271// ActOnClassMessage - used for both unary and keyword messages.
2272// ArgExprs is optional - if it is present, the number of expressions
2273// is obtained from Sel.getNumArgs().
2274Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002275 Scope *S,
Steve Narofffa465d12007-10-02 20:01:56 +00002276 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002277 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002278{
Steve Narofffa465d12007-10-02 20:01:56 +00002279 assert(receiverName && "missing receiver class name");
Steve Naroffc39ca262007-09-18 23:55:05 +00002280
Steve Naroff52664182007-10-16 23:12:48 +00002281 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002282 ObjcInterfaceDecl* ClassDecl = 0;
2283 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2284 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahanian342f3602007-11-12 20:20:37 +00002285 if (ClassDecl && CurMethodDecl->isInstance()) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002286 // Synthesize a cast to the super class. This hack allows us to loosely
2287 // represent super without creating a special expression node.
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002288 IdentifierInfo &II = Context.Idents.get("self");
Steve Naroff3b1caac2007-12-07 03:50:46 +00002289 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II, false);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002290 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2291 superTy = Context.getPointerType(superTy);
2292 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2293 SourceLocation(), ReceiverExpr.Val);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002294 // We are really in an instance method, redirect.
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002295 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002296 Args, NumArgs);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002297 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00002298 // We are sending a message to 'super' within a class method. Do nothing,
2299 // the receiver will pass through as 'super' (how convenient:-).
2300 } else
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002301 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002302
2303 // FIXME: can ClassDecl ever be null?
Steve Narofffa465d12007-10-02 20:01:56 +00002304 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002305 QualType returnType;
Steve Naroff75c4baf2007-11-05 15:27:52 +00002306
2307 // Before we give up, check if the selector is an instance method.
2308 if (!Method)
2309 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002310 if (!Method) {
2311 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2312 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002313 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002314 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002315 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002316 if (Sel.getNumArgs()) {
2317 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2318 return true;
2319 }
Steve Naroff7e461452007-10-16 20:39:36 +00002320 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002321 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
Steve Naroff9f176d12007-11-15 13:05:42 +00002322 lbrac, rbrac, ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002323}
2324
Steve Naroff4ed9d662007-09-27 14:38:14 +00002325// ActOnInstanceMessage - used for both unary and keyword messages.
2326// ArgExprs is optional - if it is present, the number of expressions
2327// is obtained from Sel.getNumArgs().
2328Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroff6cb1d362007-09-28 22:22:11 +00002329 ExprTy *receiver, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002330 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff4ed9d662007-09-27 14:38:14 +00002331{
Steve Naroffc39ca262007-09-18 23:55:05 +00002332 assert(receiver && "missing receiver expression");
2333
Steve Naroff52664182007-10-16 23:12:48 +00002334 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroffc39ca262007-09-18 23:55:05 +00002335 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Narofffa465d12007-10-02 20:01:56 +00002336 QualType receiverType = RExpr->getType();
Steve Naroffee1de132007-10-10 21:53:07 +00002337 QualType returnType;
Fariborz Jahaniance5528d2008-01-03 20:01:35 +00002338 ObjcMethodDecl *Method = 0;
Steve Naroffee1de132007-10-10 21:53:07 +00002339
Steve Naroff0091d142007-11-11 17:52:25 +00002340 if (receiverType == Context.getObjcIdType() ||
2341 receiverType == Context.getObjcClassType()) {
Steve Naroff1e1c3912007-11-03 16:37:59 +00002342 Method = InstanceMethodPool[Sel].Method;
Steve Narofffe9eb6a2007-12-18 01:30:32 +00002343 if (!Method)
2344 Method = FactoryMethodPool[Sel].Method;
Steve Naroff7e461452007-10-16 20:39:36 +00002345 if (!Method) {
2346 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2347 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002348 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002349 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002350 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002351 if (Sel.getNumArgs())
2352 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2353 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002354 }
Steve Naroffee1de132007-10-10 21:53:07 +00002355 } else {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002356 bool receiverIsQualId =
2357 dyn_cast<ObjcQualifiedIdType>(RExpr->getType()) != 0;
Chris Lattner71c01112007-10-10 23:42:28 +00002358 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2359 // revisited. how do we get the ClassDecl from the receiver expression?
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002360 if (!receiverIsQualId)
2361 while (receiverType->isPointerType()) {
2362 PointerType *pointerType =
2363 static_cast<PointerType*>(receiverType.getTypePtr());
2364 receiverType = pointerType->getPointeeType();
2365 }
Fariborz Jahaniance5528d2008-01-03 20:01:35 +00002366 ObjcInterfaceDecl* ClassDecl = 0;
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002367 if (ObjcQualifiedInterfaceType *QIT =
2368 dyn_cast<ObjcQualifiedInterfaceType>(receiverType)) {
Fariborz Jahanian0c2f2142007-12-13 20:47:42 +00002369 ClassDecl = QIT->getDecl();
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002370 Method = ClassDecl->lookupInstanceMethod(Sel);
2371 if (!Method) {
2372 // search protocols
2373 for (unsigned i = 0; i < QIT->getNumProtocols(); i++) {
2374 ObjcProtocolDecl *PDecl = QIT->getProtocols(i);
2375 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
2376 break;
2377 }
2378 }
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002379 if (!Method)
2380 Diag(lbrac, diag::warn_method_not_found_in_protocol,
2381 std::string("-"), Sel.getName(),
2382 SourceRange(lbrac, rbrac));
2383 }
2384 else if (ObjcQualifiedIdType *QIT =
2385 dyn_cast<ObjcQualifiedIdType>(receiverType)) {
2386 // search protocols
2387 for (unsigned i = 0; i < QIT->getNumProtocols(); i++) {
2388 ObjcProtocolDecl *PDecl = QIT->getProtocols(i);
2389 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
2390 break;
2391 }
2392 if (!Method)
2393 Diag(lbrac, diag::warn_method_not_found_in_protocol,
2394 std::string("-"), Sel.getName(),
2395 SourceRange(lbrac, rbrac));
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002396 }
2397 else {
2398 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2399 "bad receiver type");
2400 ClassDecl = static_cast<ObjcInterfaceType*>(
2401 receiverType.getTypePtr())->getDecl();
2402 // FIXME: consider using InstanceMethodPool, since it will be faster
2403 // than the following method (which can do *many* linear searches). The
2404 // idea is to add class info to InstanceMethodPool...
2405 Method = ClassDecl->lookupInstanceMethod(Sel);
2406 }
Steve Naroff7e461452007-10-16 20:39:36 +00002407 if (!Method) {
Steve Naroffb1c7ad92007-11-11 00:10:47 +00002408 // If we have an implementation in scope, check "private" methods.
Fariborz Jahaniance5528d2008-01-03 20:01:35 +00002409 if (ClassDecl)
2410 if (ObjcImplementationDecl *ImpDecl =
Steve Naroffb1c7ad92007-11-11 00:10:47 +00002411 ObjcImplementations[ClassDecl->getIdentifier()])
Fariborz Jahaniance5528d2008-01-03 20:01:35 +00002412 Method = ImpDecl->getInstanceMethod(Sel);
Steve Naroff20255552007-12-11 03:38:03 +00002413 // If we still haven't found a method, look in the global pool. This
2414 // behavior isn't very desirable, however we need it for GCC compatibility.
Steve Naroffc4793582007-12-07 20:41:14 +00002415 if (!Method)
2416 Method = InstanceMethodPool[Sel].Method;
Steve Naroffb1c7ad92007-11-11 00:10:47 +00002417 }
2418 if (!Method) {
Steve Naroff7e461452007-10-16 20:39:36 +00002419 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2420 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002421 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002422 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002423 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002424 if (Sel.getNumArgs())
2425 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2426 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002427 }
Steve Narofffa465d12007-10-02 20:01:56 +00002428 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002429 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002430 ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002431}