blob: 9ae52551550d8b70698bb26bd082d3be89fc370a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Ted Kremenek588e5eb2007-11-25 00:58:00 +000015#include "SemaUtil.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
Steve Naroff6a8a9a42007-10-02 20:01:56 +000018#include "clang/AST/DeclObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/AST/Expr.h"
Steve Naroff563477d2007-09-18 23:55:05 +000020#include "clang/Parse/DeclSpec.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/Lex/Preprocessor.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Basic/SourceManager.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/TargetInfo.h"
27#include "llvm/ADT/SmallString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000028#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30
Steve Narofff69936d2007-09-16 03:34:24 +000031/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +000032/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
33/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
34/// multiple tokens. However, the common case is that StringToks points to one
35/// string.
36///
37Action::ExprResult
Steve Narofff69936d2007-09-16 03:34:24 +000038Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +000039 assert(NumStringToks && "Must have at least one string!");
40
41 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
42 if (Literal.hadError)
43 return ExprResult(true);
44
45 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
46 for (unsigned i = 0; i != NumStringToks; ++i)
47 StringTokLocs.push_back(StringToks[i].getLocation());
48
49 // FIXME: handle wchar_t
Anders Carlssonee98ac52007-10-15 02:50:23 +000050 QualType t;
51
52 if (Literal.Pascal)
53 t = Context.getPointerType(Context.UnsignedCharTy);
54 else
55 t = Context.getPointerType(Context.CharTy);
56
57 if (Literal.Pascal && Literal.GetStringLength() > 256)
58 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
59 SourceRange(StringToks[0].getLocation(),
60 StringToks[NumStringToks-1].getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +000061
62 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
63 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlssonee98ac52007-10-15 02:50:23 +000064 Literal.AnyWide, t,
65 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +000066 StringToks[NumStringToks-1].getLocation());
67}
68
69
Steve Naroff08d92e42007-09-15 18:49:24 +000070/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +000071/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
72/// identifier is used in an function call context.
Steve Naroff08d92e42007-09-15 18:49:24 +000073Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +000074 IdentifierInfo &II,
75 bool HasTrailingLParen) {
76 // Could be enum-constant or decl.
Steve Naroff8c9f13e2007-09-16 16:16:00 +000077 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Reid Spencer5f016e22007-07-11 17:01:13 +000078 if (D == 0) {
79 // Otherwise, this could be an implicitly declared function reference (legal
80 // in C90, extension in C99).
81 if (HasTrailingLParen &&
82 // Not in C++.
83 !getLangOptions().CPlusPlus)
84 D = ImplicitlyDefineFunction(Loc, II, S);
85 else {
Steve Naroff7779db42007-11-12 14:29:37 +000086 if (CurMethodDecl) {
87 ObjcInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
88 ObjcInterfaceDecl *clsDeclared;
Steve Naroff7e3411b2007-11-15 02:58:25 +000089 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
90 IdentifierInfo &II = Context.Idents.get("self");
91 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
92 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
93 static_cast<Expr*>(SelfExpr.Val), true, true);
94 }
Steve Naroff7779db42007-11-12 14:29:37 +000095 }
Reid Spencer5f016e22007-07-11 17:01:13 +000096 // If this name wasn't predeclared and if this is not a function call,
97 // diagnose the problem.
98 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
99 }
100 }
Steve Naroffe1223f72007-08-28 03:03:08 +0000101 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroff53a32342007-08-28 18:45:29 +0000102 // Only create DeclRefExpr's for valid Decl's.
Steve Naroff5912a352007-08-28 20:14:24 +0000103 if (VD->isInvalidDecl())
Steve Naroffe1223f72007-08-28 03:03:08 +0000104 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000105 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroffe1223f72007-08-28 03:03:08 +0000106 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 if (isa<TypedefDecl>(D))
108 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Fariborz Jahanian5ef404f2007-12-05 18:16:33 +0000109 if (isa<ObjcInterfaceDecl>(D))
110 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000111
112 assert(0 && "Invalid decl");
Chris Lattnereddbe032007-07-21 04:57:45 +0000113 abort();
Reid Spencer5f016e22007-07-11 17:01:13 +0000114}
115
Steve Narofff69936d2007-09-16 03:34:24 +0000116Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000117 tok::TokenKind Kind) {
118 PreDefinedExpr::IdentType IT;
119
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 switch (Kind) {
121 default:
122 assert(0 && "Unknown simple primary expr!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
Anders Carlsson22742662007-07-21 05:21:51 +0000124 IT = PreDefinedExpr::Func;
125 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000126 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000127 IT = PreDefinedExpr::Function;
128 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000129 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000130 IT = PreDefinedExpr::PrettyFunction;
131 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 }
Anders Carlsson22742662007-07-21 05:21:51 +0000133
134 // Pre-defined identifiers are always of type char *.
135 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000136}
137
Steve Narofff69936d2007-09-16 03:34:24 +0000138Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000139 llvm::SmallString<16> CharBuffer;
140 CharBuffer.resize(Tok.getLength());
141 const char *ThisTokBegin = &CharBuffer[0];
142 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
143
144 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
145 Tok.getLocation(), PP);
146 if (Literal.hadError())
147 return ExprResult(true);
148 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
149 Tok.getLocation());
150}
151
Steve Narofff69936d2007-09-16 03:34:24 +0000152Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 // fast path for a single digit (which is quite common). A single digit
154 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
155 if (Tok.getLength() == 1) {
156 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
157
Chris Lattner701e5eb2007-09-04 02:45:27 +0000158 unsigned IntSize = static_cast<unsigned>(
159 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000160 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
161 Context.IntTy,
162 Tok.getLocation()));
163 }
164 llvm::SmallString<512> IntegerBuffer;
165 IntegerBuffer.resize(Tok.getLength());
166 const char *ThisTokBegin = &IntegerBuffer[0];
167
168 // Get the spelling of the token, which eliminates trigraphs, etc.
169 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
170 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
171 Tok.getLocation(), PP);
172 if (Literal.hadError)
173 return ExprResult(true);
174
Chris Lattner5d661452007-08-26 03:42:43 +0000175 Expr *Res;
176
177 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000178 QualType Ty;
179 const llvm::fltSemantics *Format;
180 uint64_t Size; unsigned Align;
181
182 if (Literal.isFloat) {
183 Ty = Context.FloatTy;
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000184 Context.Target.getFloatInfo(Size, Align, Format,
185 Context.getFullLoc(Tok.getLocation()));
186
Chris Lattner525a0502007-09-22 18:29:59 +0000187 } else if (Literal.isLong) {
188 Ty = Context.LongDoubleTy;
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000189 Context.Target.getLongDoubleInfo(Size, Align, Format,
190 Context.getFullLoc(Tok.getLocation()));
Chris Lattner525a0502007-09-22 18:29:59 +0000191 } else {
192 Ty = Context.DoubleTy;
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000193 Context.Target.getDoubleInfo(Size, Align, Format,
194 Context.getFullLoc(Tok.getLocation()));
Chris Lattner525a0502007-09-22 18:29:59 +0000195 }
196
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000197 // isExact will be set by GetFloatValue().
198 bool isExact = false;
199
200 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
201 Ty, Tok.getLocation());
202
Chris Lattner5d661452007-08-26 03:42:43 +0000203 } else if (!Literal.isIntegerLiteral()) {
204 return ExprResult(true);
205 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 QualType t;
207
Neil Boothb9449512007-08-29 22:00:19 +0000208 // long long is a C99 feature.
209 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000210 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000211 Diag(Tok.getLocation(), diag::ext_longlong);
212
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 // Get the value in the widest-possible width.
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000214 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(
215 Context.getFullLoc(Tok.getLocation())), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000216
217 if (Literal.GetIntegerValue(ResultVal)) {
218 // If this value didn't fit into uintmax_t, warn and force to ull.
219 Diag(Tok.getLocation(), diag::warn_integer_too_large);
220 t = Context.UnsignedLongLongTy;
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000221 assert(Context.getTypeSize(t, Tok.getLocation()) ==
Reid Spencer5f016e22007-07-11 17:01:13 +0000222 ResultVal.getBitWidth() && "long long is not intmax_t?");
223 } else {
224 // If this value fits into a ULL, try to figure out what else it fits into
225 // according to the rules of C99 6.4.4.1p5.
226
227 // Octal, Hexadecimal, and integers with a U suffix are allowed to
228 // be an unsigned int.
229 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
230
231 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner97c51562007-08-23 21:58:08 +0000232 if (!Literal.isLong && !Literal.isLongLong) {
233 // Are int/unsigned possibilities?
Chris Lattner701e5eb2007-09-04 02:45:27 +0000234 unsigned IntSize = static_cast<unsigned>(
235 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000236 // Does it fit in a unsigned int?
237 if (ResultVal.isIntN(IntSize)) {
238 // Does it fit in a signed int?
239 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
240 t = Context.IntTy;
241 else if (AllowUnsigned)
242 t = Context.UnsignedIntTy;
243 }
244
245 if (!t.isNull())
246 ResultVal.trunc(IntSize);
247 }
248
249 // Are long/unsigned long possibilities?
250 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner701e5eb2007-09-04 02:45:27 +0000251 unsigned LongSize = static_cast<unsigned>(
252 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000253
254 // Does it fit in a unsigned long?
255 if (ResultVal.isIntN(LongSize)) {
256 // Does it fit in a signed long?
257 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
258 t = Context.LongTy;
259 else if (AllowUnsigned)
260 t = Context.UnsignedLongTy;
261 }
262 if (!t.isNull())
263 ResultVal.trunc(LongSize);
264 }
265
266 // Finally, check long long if needed.
267 if (t.isNull()) {
Chris Lattner701e5eb2007-09-04 02:45:27 +0000268 unsigned LongLongSize = static_cast<unsigned>(
269 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000270
271 // Does it fit in a unsigned long long?
272 if (ResultVal.isIntN(LongLongSize)) {
273 // Does it fit in a signed long long?
274 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
275 t = Context.LongLongTy;
276 else if (AllowUnsigned)
277 t = Context.UnsignedLongLongTy;
278 }
279 }
280
281 // If we still couldn't decide a type, we probably have something that
282 // does not fit in a signed long long, but has no U suffix.
283 if (t.isNull()) {
284 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
285 t = Context.UnsignedLongLongTy;
286 }
287 }
288
Chris Lattner5d661452007-08-26 03:42:43 +0000289 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000290 }
Chris Lattner5d661452007-08-26 03:42:43 +0000291
292 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
293 if (Literal.isImaginary)
294 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
295
296 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000297}
298
Steve Narofff69936d2007-09-16 03:34:24 +0000299Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 ExprTy *Val) {
301 Expr *e = (Expr *)Val;
Steve Narofff69936d2007-09-16 03:34:24 +0000302 assert((e != 0) && "ActOnParenExpr() missing expr");
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 return new ParenExpr(L, R, e);
304}
305
306/// The UsualUnaryConversions() function is *not* called by this routine.
307/// See C99 6.3.2.1p[2-4] for more details.
308QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
309 SourceLocation OpLoc, bool isSizeof) {
310 // C99 6.5.3.4p1:
311 if (isa<FunctionType>(exprType) && isSizeof)
312 // alignof(function) is allowed.
313 Diag(OpLoc, diag::ext_sizeof_function_type);
314 else if (exprType->isVoidType())
315 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
316 else if (exprType->isIncompleteType()) {
317 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
318 diag::err_alignof_incomplete_type,
319 exprType.getAsString());
320 return QualType(); // error
321 }
322 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
323 return Context.getSizeType();
324}
325
326Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000327ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +0000328 SourceLocation LPLoc, TypeTy *Ty,
329 SourceLocation RPLoc) {
330 // If error parsing type, ignore.
331 if (Ty == 0) return true;
332
333 // Verify that this is a valid expression.
334 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
335
336 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
337
338 if (resultType.isNull())
339 return true;
340 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
341}
342
Chris Lattner5d794252007-08-24 21:41:10 +0000343QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000344 DefaultFunctionArrayConversion(V);
345
Chris Lattnercc26ed72007-08-26 05:39:26 +0000346 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000347 if (const ComplexType *CT = V->getType()->getAsComplexType())
348 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000349
350 // Otherwise they pass through real integer and floating point types here.
351 if (V->getType()->isArithmeticType())
352 return V->getType();
353
354 // Reject anything else.
355 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
356 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000357}
358
359
Reid Spencer5f016e22007-07-11 17:01:13 +0000360
Steve Narofff69936d2007-09-16 03:34:24 +0000361Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 tok::TokenKind Kind,
363 ExprTy *Input) {
364 UnaryOperator::Opcode Opc;
365 switch (Kind) {
366 default: assert(0 && "Unknown unary op!");
367 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
368 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
369 }
370 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
371 if (result.isNull())
372 return true;
373 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
374}
375
376Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000377ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000379 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000380
381 // Perform default conversions.
382 DefaultFunctionArrayConversion(LHSExp);
383 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000384
Chris Lattner12d9ff62007-07-16 00:14:47 +0000385 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000386
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000388 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 // in the subscript position. As a result, we need to derive the array base
390 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000391 Expr *BaseExpr, *IndexExpr;
392 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000393 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000394 BaseExpr = LHSExp;
395 IndexExpr = RHSExp;
396 // FIXME: need to deal with const...
397 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000398 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000399 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000400 BaseExpr = RHSExp;
401 IndexExpr = LHSExp;
402 // FIXME: need to deal with const...
403 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000404 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
405 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000406 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000407
408 // Component access limited to variables (reject vec4.rg[1]).
409 if (!isa<DeclRefExpr>(BaseExpr))
410 return Diag(LLoc, diag::err_ocuvector_component_access,
411 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000412 // FIXME: need to deal with const...
413 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000415 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
416 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 }
418 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000419 if (!IndexExpr->getType()->isIntegerType())
420 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
421 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000422
Chris Lattner12d9ff62007-07-16 00:14:47 +0000423 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
424 // the following check catches trying to index a pointer to a function (e.g.
425 // void (*)(int)). Functions are not objects in C99.
426 if (!ResultType->isObjectType())
427 return Diag(BaseExpr->getLocStart(),
428 diag::err_typecheck_subscript_not_object,
429 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
430
431 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000432}
433
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000434QualType Sema::
435CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
436 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnerc8629632007-07-31 19:29:30 +0000437 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000438
439 // The vector accessor can't exceed the number of elements.
440 const char *compStr = CompName.getName();
441 if (strlen(compStr) > vecType->getNumElements()) {
442 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
443 baseType.getAsString(), SourceRange(CompLoc));
444 return QualType();
445 }
446 // The component names must come from the same set.
Chris Lattner88dca042007-08-02 22:33:49 +0000447 if (vecType->getPointAccessorIdx(*compStr) != -1) {
448 do
449 compStr++;
450 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
451 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
452 do
453 compStr++;
454 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
455 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
456 do
457 compStr++;
458 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
459 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000460
461 if (*compStr) {
462 // We didn't get to the end of the string. This means the component names
463 // didn't come from the same set *or* we encountered an illegal name.
464 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
465 std::string(compStr,compStr+1), SourceRange(CompLoc));
466 return QualType();
467 }
468 // Each component accessor can't exceed the vector type.
469 compStr = CompName.getName();
470 while (*compStr) {
471 if (vecType->isAccessorWithinNumElements(*compStr))
472 compStr++;
473 else
474 break;
475 }
476 if (*compStr) {
477 // We didn't get to the end of the string. This means a component accessor
478 // exceeds the number of elements in the vector.
479 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
480 baseType.getAsString(), SourceRange(CompLoc));
481 return QualType();
482 }
483 // The component accessor looks fine - now we need to compute the actual type.
484 // The vector type is implied by the component accessor. For example,
485 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
486 unsigned CompSize = strlen(CompName.getName());
487 if (CompSize == 1)
488 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000489
490 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
491 // Now look up the TypeDefDecl from the vector type. Without this,
492 // diagostics look bad. We want OCU vector types to appear built-in.
493 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
494 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
495 return Context.getTypedefType(OCUVectorDecls[i]);
496 }
497 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000498}
499
Reid Spencer5f016e22007-07-11 17:01:13 +0000500Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000501ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000502 tok::TokenKind OpKind, SourceLocation MemberLoc,
503 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000504 Expr *BaseExpr = static_cast<Expr *>(Base);
505 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +0000506
507 // Perform default conversions.
508 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000509
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000510 QualType BaseType = BaseExpr->getType();
511 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000512
Reid Spencer5f016e22007-07-11 17:01:13 +0000513 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000514 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000515 BaseType = PT->getPointeeType();
516 else
517 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
518 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000519 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000520 // The base type is either a record or an OCUVectorType.
Chris Lattnerc8629632007-07-31 19:29:30 +0000521 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000522 RecordDecl *RDecl = RTy->getDecl();
523 if (RTy->isIncompleteType())
524 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
525 BaseExpr->getSourceRange());
526 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000527 FieldDecl *MemberDecl = RDecl->getMember(&Member);
528 if (!MemberDecl)
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000529 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
530 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000531 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
532 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff608e0ee2007-08-03 22:40:33 +0000533 // Component access limited to variables (reject vec4.rg.g).
534 if (!isa<DeclRefExpr>(BaseExpr))
535 return Diag(OpLoc, diag::err_ocuvector_component_access,
536 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000537 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
538 if (ret.isNull())
539 return true;
Chris Lattner6481a572007-08-03 17:31:20 +0000540 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000541 } else if (BaseType->isObjcInterfaceType()) {
542 ObjcInterfaceDecl *IFace;
543 if (isa<ObjcInterfaceType>(BaseType.getCanonicalType()))
544 IFace = dyn_cast<ObjcInterfaceType>(BaseType)->getDecl();
545 else
Fariborz Jahanian06cef252007-12-13 20:47:42 +0000546 IFace = dyn_cast<ObjcQualifiedInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000547 ObjcInterfaceDecl *clsDeclared;
548 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
549 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
550 OpKind==tok::arrow);
551 }
552 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
553 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000554}
555
Steve Narofff69936d2007-09-16 03:34:24 +0000556/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +0000557/// This provides the location of the left/right parens and a list of comma
558/// locations.
559Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000560ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner74c469f2007-07-21 03:03:59 +0000561 ExprTy **args, unsigned NumArgsInCall,
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000563 Expr *Fn = static_cast<Expr *>(fn);
564 Expr **Args = reinterpret_cast<Expr**>(args);
565 assert(Fn && "no function call expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000566
Chris Lattner74c469f2007-07-21 03:03:59 +0000567 UsualUnaryConversions(Fn);
568 QualType funcType = Fn->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000569
570 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
571 // type pointer to function".
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000572 const PointerType *PT = funcType->getAsPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000573 if (PT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000574 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
575 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000576
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000577 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000578 if (funcT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000579 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
580 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000581
582 // If a prototype isn't declared, the parser implicitly defines a func decl
583 QualType resultType = funcT->getResultType();
584
585 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
586 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
587 // assignment, to the types of the corresponding parameter, ...
588
589 unsigned NumArgsInProto = proto->getNumArgs();
590 unsigned NumArgsToCheck = NumArgsInCall;
591
592 if (NumArgsInCall < NumArgsInProto)
593 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
Chris Lattner74c469f2007-07-21 03:03:59 +0000594 Fn->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 else if (NumArgsInCall > NumArgsInProto) {
596 if (!proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +0000597 Diag(Args[NumArgsInProto]->getLocStart(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000598 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +0000599 SourceRange(Args[NumArgsInProto]->getLocStart(),
600 Args[NumArgsInCall-1]->getLocEnd()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000601 }
602 NumArgsToCheck = NumArgsInProto;
603 }
604 // Continue to check argument types (even if we have too few/many args).
605 for (unsigned i = 0; i < NumArgsToCheck; i++) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000606 Expr *argExpr = Args[i];
Steve Narofff69936d2007-09-16 03:34:24 +0000607 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000608
609 QualType lhsType = proto->getArgType(i);
610 QualType rhsType = argExpr->getType();
Steve Naroff700204c2007-07-24 21:46:40 +0000611
Steve Naroff82c7e6d2007-07-25 20:45:33 +0000612 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnerc8629632007-07-31 19:29:30 +0000613 if (const ArrayType *ary = lhsType->getAsArrayType())
Steve Naroff700204c2007-07-24 21:46:40 +0000614 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff82c7e6d2007-07-25 20:45:33 +0000615 else if (lhsType->isFunctionType())
Steve Naroff700204c2007-07-24 21:46:40 +0000616 lhsType = Context.getPointerType(lhsType);
617
Steve Naroff90045e82007-07-13 23:32:42 +0000618 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
619 argExpr);
Steve Narofff1120de2007-08-24 22:33:52 +0000620 if (Args[i] != argExpr) // The expression was converted.
621 Args[i] = argExpr; // Make sure we store the converted expression.
Reid Spencer5f016e22007-07-11 17:01:13 +0000622 SourceLocation l = argExpr->getLocStart();
623
624 // decode the result (notice that AST's are still created for extensions).
625 switch (result) {
626 case Compatible:
627 break;
628 case PointerFromInt:
Steve Naroff529a4ad2007-11-27 17:58:44 +0000629 Diag(l, diag::ext_typecheck_passing_pointer_int,
630 lhsType.getAsString(), rhsType.getAsString(),
631 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000632 break;
633 case IntFromPointer:
634 Diag(l, diag::ext_typecheck_passing_pointer_int,
635 lhsType.getAsString(), rhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000636 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000637 break;
638 case IncompatiblePointer:
639 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
640 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000641 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000642 break;
643 case CompatiblePointerDiscardsQualifiers:
644 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
645 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000646 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000647 break;
648 case Incompatible:
649 return Diag(l, diag::err_typecheck_passing_incompatible,
650 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000651 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000652 }
653 }
Steve Naroffb291ab62007-08-28 23:30:39 +0000654 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
655 // Promote the arguments (C99 6.5.2.2p7).
656 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
657 Expr *argExpr = Args[i];
Steve Narofff69936d2007-09-16 03:34:24 +0000658 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffb291ab62007-08-28 23:30:39 +0000659
660 DefaultArgumentPromotion(argExpr);
661 if (Args[i] != argExpr) // The expression was converted.
662 Args[i] = argExpr; // Make sure we store the converted expression.
663 }
664 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
665 // Even if the types checked, bail if the number of arguments don't match.
Reid Spencer5f016e22007-07-11 17:01:13 +0000666 return true;
Steve Naroffb291ab62007-08-28 23:30:39 +0000667 }
668 } else if (isa<FunctionTypeNoProto>(funcT)) {
669 // Promote the arguments (C99 6.5.2.2p6).
670 for (unsigned i = 0; i < NumArgsInCall; i++) {
671 Expr *argExpr = Args[i];
Steve Narofff69936d2007-09-16 03:34:24 +0000672 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffb291ab62007-08-28 23:30:39 +0000673
674 DefaultArgumentPromotion(argExpr);
675 if (Args[i] != argExpr) // The expression was converted.
676 Args[i] = argExpr; // Make sure we store the converted expression.
677 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000678 }
Chris Lattner59907c42007-08-10 20:18:51 +0000679 // Do special checking on direct calls to functions.
680 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
681 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
682 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattnerc27c6652007-12-20 00:05:45 +0000683 if (CheckFunctionCall(Fn, RParenLoc, FDecl, Args, NumArgsInCall)) {
684 // Function rejected, delete sub-ast's.
685 delete Fn;
686 for (unsigned i = 0; i != NumArgsInCall; ++i)
687 delete Args[i];
Anders Carlsson71993dd2007-08-17 05:31:46 +0000688 return true;
Chris Lattnerc27c6652007-12-20 00:05:45 +0000689 }
Chris Lattner59907c42007-08-10 20:18:51 +0000690
Chris Lattner74c469f2007-07-21 03:03:59 +0000691 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000692}
693
694Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000695ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +0000696 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +0000697 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +0000698 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +0000699 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +0000700 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +0000701 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +0000702
Steve Naroff2fdc3742007-12-10 22:44:33 +0000703 // FIXME: add more semantic analysis (C99 6.5.2.5).
704 if (CheckInitializer(literalExpr, literalType, false))
705 return 0;
Anders Carlssond35c8322007-12-05 07:24:19 +0000706
Steve Naroffaff1edd2007-07-19 21:32:11 +0000707 return new CompoundLiteralExpr(literalType, literalExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000708}
709
710Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000711ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000712 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +0000713 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000714
Steve Naroff08d92e42007-09-15 18:49:24 +0000715 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +0000716 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000717
Steve Naroff38374b02007-09-02 20:30:18 +0000718 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
719 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
720 return e;
Steve Naroff4aa88f82007-07-19 01:06:55 +0000721}
722
Anders Carlssona64db8f2007-11-27 05:51:55 +0000723bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty)
724{
725 assert(VectorTy->isVectorType() && "Not a vector type!");
726
727 if (Ty->isVectorType() || Ty->isIntegerType()) {
728 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
729 Context.getTypeSize(Ty, SourceLocation()))
730 return Diag(R.getBegin(),
731 Ty->isVectorType() ?
732 diag::err_invalid_conversion_between_vectors :
733 diag::err_invalid_conversion_between_vector_and_integer,
734 VectorTy.getAsString().c_str(),
735 Ty.getAsString().c_str(), R);
736 } else
737 return Diag(R.getBegin(),
738 diag::err_invalid_conversion_between_vector_and_scalar,
739 VectorTy.getAsString().c_str(),
740 Ty.getAsString().c_str(), R);
741
742 return false;
743}
744
Steve Naroff4aa88f82007-07-19 01:06:55 +0000745Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000746ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +0000747 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +0000748 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +0000749
750 Expr *castExpr = static_cast<Expr*>(Op);
751 QualType castType = QualType::getFromOpaquePtr(Ty);
752
Steve Naroff711602b2007-08-31 00:32:44 +0000753 UsualUnaryConversions(castExpr);
754
Chris Lattner75af4802007-07-18 16:00:06 +0000755 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
756 // type needs to be scalar.
Chris Lattner3da2db42007-10-29 04:26:44 +0000757 if (!castType->isVoidType()) { // Cast to void allows any expr type.
758 if (!castType->isScalarType())
759 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
760 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Anders Carlssona64db8f2007-11-27 05:51:55 +0000761 if (!castExpr->getType()->isScalarType())
Chris Lattner3da2db42007-10-29 04:26:44 +0000762 return Diag(castExpr->getLocStart(),
763 diag::err_typecheck_expect_scalar_operand,
764 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssona64db8f2007-11-27 05:51:55 +0000765
766 if (castExpr->getType()->isVectorType()) {
767 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
768 castExpr->getType(), castType))
769 return true;
770 } else if (castType->isVectorType()) {
771 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
772 castType, castExpr->getType()))
773 return true;
Chris Lattner3da2db42007-10-29 04:26:44 +0000774 }
Steve Naroff16beff82007-07-16 23:25:18 +0000775 }
776 return new CastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000777}
778
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000779// promoteExprToType - a helper function to ensure we create exactly one
780// ImplicitCastExpr.
781static void promoteExprToType(Expr *&expr, QualType type) {
782 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
783 impCast->setType(type);
784 else
785 expr = new ImplicitCastExpr(type, expr);
786 return;
787}
788
Chris Lattnera21ddb32007-11-26 01:40:58 +0000789/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
790/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +0000791inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +0000792 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000793 UsualUnaryConversions(cond);
794 UsualUnaryConversions(lex);
795 UsualUnaryConversions(rex);
796 QualType condT = cond->getType();
797 QualType lexT = lex->getType();
798 QualType rexT = rex->getType();
799
Reid Spencer5f016e22007-07-11 17:01:13 +0000800 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +0000801 if (!condT->isScalarType()) { // C99 6.5.15p2
802 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
803 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +0000804 return QualType();
805 }
806 // now check the two expressions.
Steve Naroffa4332e22007-07-17 00:58:39 +0000807 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
808 UsualArithmeticConversions(lex, rex);
809 return lex->getType();
810 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000811 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
812 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
Chris Lattnera21ddb32007-11-26 01:40:58 +0000813 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000814 return lexT;
815
Reid Spencer5f016e22007-07-11 17:01:13 +0000816 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000817 lexT.getAsString(), rexT.getAsString(),
818 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000819 return QualType();
820 }
821 }
Chris Lattner590b6642007-07-15 23:26:56 +0000822 // C99 6.5.15p3
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000823 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
824 promoteExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff49b45262007-07-13 16:58:59 +0000825 return lexT;
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000826 }
827 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
828 promoteExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff49b45262007-07-13 16:58:59 +0000829 return rexT;
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000830 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000831 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
832 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
833 // get the "pointed to" types
834 QualType lhptee = LHSPT->getPointeeType();
835 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000836
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000837 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
838 if (lhptee->isVoidType() &&
839 (rhptee->isObjectType() || rhptee->isIncompleteType()))
840 return lexT;
841 if (rhptee->isVoidType() &&
842 (lhptee->isObjectType() || lhptee->isIncompleteType()))
843 return rexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000844
Steve Naroffec0550f2007-10-15 20:41:53 +0000845 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
846 rhptee.getUnqualifiedType())) {
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000847 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
848 lexT.getAsString(), rexT.getAsString(),
849 lex->getSourceRange(), rex->getSourceRange());
850 return lexT; // FIXME: this is an _ext - is this return o.k?
851 }
852 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000853 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
854 // differently qualified versions of compatible types, the result type is
855 // a pointer to an appropriately qualified version of the *composite*
856 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000857 return lexT; // FIXME: Need to return the composite type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000858 }
859 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000860
Steve Naroff49b45262007-07-13 16:58:59 +0000861 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
862 return lexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000863
864 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000865 lexT.getAsString(), rexT.getAsString(),
866 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000867 return QualType();
868}
869
Steve Narofff69936d2007-09-16 03:34:24 +0000870/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +0000871/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +0000872Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000873 SourceLocation ColonLoc,
874 ExprTy *Cond, ExprTy *LHS,
875 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +0000876 Expr *CondExpr = (Expr *) Cond;
877 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +0000878
879 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
880 // was the condition.
881 bool isLHSNull = LHSExpr == 0;
882 if (isLHSNull)
883 LHSExpr = CondExpr;
884
Chris Lattner26824902007-07-16 21:39:03 +0000885 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
886 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000887 if (result.isNull())
888 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +0000889 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
890 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000891}
892
Steve Naroffb291ab62007-08-28 23:30:39 +0000893/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
894/// do not have a prototype. Integer promotions are performed on each
895/// argument, and arguments that have type float are promoted to double.
896void Sema::DefaultArgumentPromotion(Expr *&expr) {
897 QualType t = expr->getType();
898 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
899
900 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
901 promoteExprToType(expr, Context.IntTy);
902 if (t == Context.FloatTy)
903 promoteExprToType(expr, Context.DoubleTy);
904}
905
Steve Narofffa2eaab2007-07-15 02:02:06 +0000906/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000907void Sema::DefaultFunctionArrayConversion(Expr *&e) {
Steve Narofffa2eaab2007-07-15 02:02:06 +0000908 QualType t = e->getType();
Steve Naroff90045e82007-07-13 23:32:42 +0000909 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
Bill Wendling08ad47c2007-07-17 03:52:31 +0000910
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000911 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000912 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
913 t = e->getType();
914 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000915 if (t->isFunctionType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000916 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnerc8629632007-07-31 19:29:30 +0000917 else if (const ArrayType *ary = t->getAsArrayType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000918 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000919}
920
921/// UsualUnaryConversion - Performs various conversions that are common to most
922/// operators (C99 6.3). The conversions of array and function types are
923/// sometimes surpressed. For example, the array->pointer conversion doesn't
924/// apply if the array is an argument to the sizeof or address (&) operators.
925/// In these instances, this routine should *not* be called.
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000926void Sema::UsualUnaryConversions(Expr *&expr) {
Steve Naroff49b45262007-07-13 16:58:59 +0000927 QualType t = expr->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000928 assert(!t.isNull() && "UsualUnaryConversions - missing type");
929
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000930 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000931 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
932 t = expr->getType();
933 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000934 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000935 promoteExprToType(expr, Context.IntTy);
936 else
937 DefaultFunctionArrayConversion(expr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000938}
939
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000940/// UsualArithmeticConversions - Performs various conversions that are common to
Reid Spencer5f016e22007-07-11 17:01:13 +0000941/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
942/// routine returns the first non-arithmetic type found. The client is
943/// responsible for emitting appropriate error diagnostics.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000944QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
945 bool isCompAssign) {
Steve Naroff8702a0f2007-08-25 19:54:59 +0000946 if (!isCompAssign) {
947 UsualUnaryConversions(lhsExpr);
948 UsualUnaryConversions(rhsExpr);
949 }
Steve Naroff3187e202007-10-18 18:55:53 +0000950 // For conversion purposes, we ignore any qualifiers.
951 // For example, "const float" and "float" are equivalent.
Steve Narofff68a63f2007-11-10 19:45:54 +0000952 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
953 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000954
955 // If both types are identical, no conversion is needed.
Steve Naroff3187e202007-10-18 18:55:53 +0000956 if (lhs == rhs)
957 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000958
959 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
960 // The caller can deal with this (e.g. pointer + int).
Steve Naroffa4332e22007-07-17 00:58:39 +0000961 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000962 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000963
964 // At this point, we have two different arithmetic types.
965
966 // Handle complex types first (C99 6.3.1.8p1).
967 if (lhs->isComplexType() || rhs->isComplexType()) {
968 // if we have an integer operand, the result is the complex type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000969 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000970 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
971 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000972 }
973 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000974 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
975 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000976 }
Steve Narofff1448a02007-08-27 01:27:54 +0000977 // This handles complex/complex, complex/float, or float/complex.
978 // When both operands are complex, the shorter operand is converted to the
979 // type of the longer, and that is the type of the result. This corresponds
980 // to what is done when combining two real floating-point operands.
981 // The fun begins when size promotion occur across type domains.
982 // From H&S 6.3.4: When one operand is complex and the other is a real
983 // floating-point type, the less precise type is converted, within it's
984 // real or complex domain, to the precision of the other type. For example,
985 // when combining a "long double" with a "double _Complex", the
986 // "double _Complex" is promoted to "long double _Complex".
Steve Narofffb0d4962007-08-27 15:30:22 +0000987 int result = Context.compareFloatingType(lhs, rhs);
988
989 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff55fe4552007-08-27 21:32:55 +0000990 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
991 if (!isCompAssign)
992 promoteExprToType(rhsExpr, rhs);
993 } else if (result < 0) { // The right side is bigger, convert lhs.
994 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
995 if (!isCompAssign)
996 promoteExprToType(lhsExpr, lhs);
997 }
998 // At this point, lhs and rhs have the same rank/size. Now, make sure the
999 // domains match. This is a requirement for our implementation, C99
1000 // does not require this promotion.
1001 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1002 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff29960362007-08-27 21:43:43 +00001003 if (!isCompAssign)
1004 promoteExprToType(lhsExpr, rhs);
1005 return rhs;
Steve Naroff55fe4552007-08-27 21:32:55 +00001006 } else { // handle "_Complex double, double".
Steve Naroff29960362007-08-27 21:43:43 +00001007 if (!isCompAssign)
1008 promoteExprToType(rhsExpr, lhs);
1009 return lhs;
Steve Naroff55fe4552007-08-27 21:32:55 +00001010 }
Steve Naroffa4332e22007-07-17 00:58:39 +00001011 }
Steve Naroff29960362007-08-27 21:43:43 +00001012 return lhs; // The domain/size match exactly.
Reid Spencer5f016e22007-07-11 17:01:13 +00001013 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001014 // Now handle "real" floating types (i.e. float, double, long double).
1015 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1016 // if we have an integer operand, the result is the real floating type.
Steve Naroffa4332e22007-07-17 00:58:39 +00001017 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001018 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1019 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001020 }
1021 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001022 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
1023 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001024 }
Steve Narofffa2eaab2007-07-15 02:02:06 +00001025 // We have two real floating types, float/complex combos were handled above.
1026 // Convert the smaller operand to the bigger result.
Steve Narofffb0d4962007-08-27 15:30:22 +00001027 int result = Context.compareFloatingType(lhs, rhs);
1028
1029 if (result > 0) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001030 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1031 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001032 }
Steve Narofffb0d4962007-08-27 15:30:22 +00001033 if (result < 0) { // convert the lhs
1034 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1035 return rhs;
1036 }
1037 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Reid Spencer5f016e22007-07-11 17:01:13 +00001038 }
Steve Narofffa2eaab2007-07-15 02:02:06 +00001039 // Finally, we have two differing integer types.
Steve Naroffa4332e22007-07-17 00:58:39 +00001040 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001041 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1042 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001043 }
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001044 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1045 return rhs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001046}
1047
1048// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1049// being closely modeled after the C99 spec:-). The odd characteristic of this
1050// routine is it effectively iqnores the qualifiers on the top level pointee.
1051// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1052// FIXME: add a couple examples in this comment.
1053Sema::AssignmentCheckResult
1054Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1055 QualType lhptee, rhptee;
1056
1057 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001058 lhptee = lhsType->getAsPointerType()->getPointeeType();
1059 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001060
1061 // make sure we operate on the canonical type
1062 lhptee = lhptee.getCanonicalType();
1063 rhptee = rhptee.getCanonicalType();
1064
1065 AssignmentCheckResult r = Compatible;
1066
1067 // C99 6.5.16.1p1: This following citation is common to constraints
1068 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1069 // qualifiers of the type *pointed to* by the right;
1070 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1071 rhptee.getQualifiers())
1072 r = CompatiblePointerDiscardsQualifiers;
1073
1074 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1075 // incomplete type and the other is a pointer to a qualified or unqualified
1076 // version of void...
1077 if (lhptee.getUnqualifiedType()->isVoidType() &&
1078 (rhptee->isObjectType() || rhptee->isIncompleteType()))
1079 ;
1080 else if (rhptee.getUnqualifiedType()->isVoidType() &&
1081 (lhptee->isObjectType() || lhptee->isIncompleteType()))
1082 ;
1083 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1084 // unqualified versions of compatible types, ...
Steve Naroffec0550f2007-10-15 20:41:53 +00001085 else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1086 rhptee.getUnqualifiedType()))
Reid Spencer5f016e22007-07-11 17:01:13 +00001087 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1088 return r;
1089}
1090
1091/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1092/// has code to accommodate several GCC extensions when type checking
1093/// pointers. Here are some objectionable examples that GCC considers warnings:
1094///
1095/// int a, *pint;
1096/// short *pshort;
1097/// struct foo *pfoo;
1098///
1099/// pint = pshort; // warning: assignment from incompatible pointer type
1100/// a = pint; // warning: assignment makes integer from pointer without a cast
1101/// pint = a; // warning: assignment makes pointer from integer without a cast
1102/// pint = pfoo; // warning: assignment from incompatible pointer type
1103///
1104/// As a result, the code for dealing with pointers is more complex than the
1105/// C99 spec dictates.
1106/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1107///
1108Sema::AssignmentCheckResult
1109Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001110
1111
Steve Naroff8eabdff2007-11-13 00:31:42 +00001112 if (lhsType.getCanonicalType().getUnqualifiedType() ==
1113 rhsType.getCanonicalType().getUnqualifiedType())
Chris Lattner84d35ce2007-10-29 05:15:40 +00001114 return Compatible; // common case, fast path...
Steve Naroff700204c2007-07-24 21:46:40 +00001115
Anders Carlsson793680e2007-10-12 23:56:29 +00001116 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroffec0550f2007-10-15 20:41:53 +00001117 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001118 return Compatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001119 }
1120 else if (lhsType->isObjcQualifiedIdType()
1121 || rhsType->isObjcQualifiedIdType()) {
1122 if (Context.ObjcQualifiedIdTypesAreCompatible(lhsType, rhsType))
1123 return Compatible;
1124 }
1125 else if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001126 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Anders Carlsson695dbb62007-11-30 04:21:22 +00001127 if (!getLangOptions().LaxVectorConversions) {
1128 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1129 return Incompatible;
1130 } else {
1131 if (lhsType->isVectorType() && rhsType->isVectorType()) {
1132 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1133 (lhsType->isRealFloatingType() &&
1134 rhsType->isRealFloatingType())) {
1135 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1136 Context.getTypeSize(rhsType, SourceLocation()))
1137 return Compatible;
1138 }
1139 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 return Incompatible;
Anders Carlsson695dbb62007-11-30 04:21:22 +00001141 }
1142 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 return Compatible;
1144 } else if (lhsType->isPointerType()) {
1145 if (rhsType->isIntegerType())
1146 return PointerFromInt;
1147
1148 if (rhsType->isPointerType())
1149 return CheckPointerTypesForAssignment(lhsType, rhsType);
1150 } else if (rhsType->isPointerType()) {
1151 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1152 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1153 return IntFromPointer;
1154
1155 if (lhsType->isPointerType())
1156 return CheckPointerTypesForAssignment(lhsType, rhsType);
1157 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroffec0550f2007-10-15 20:41:53 +00001158 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001159 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001160 }
1161 return Incompatible;
1162}
1163
Steve Naroff90045e82007-07-13 23:32:42 +00001164Sema::AssignmentCheckResult
1165Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroff529a4ad2007-11-27 17:58:44 +00001166 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1167 // a null pointer constant.
1168 if (lhsType->isPointerType() && rExpr->isNullPointerConstant(Context)) {
1169 promoteExprToType(rExpr, lhsType);
1170 return Compatible;
1171 }
Chris Lattner943140e2007-10-16 02:55:40 +00001172 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001173 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001174 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001175 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001176 //
1177 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1178 // are better understood.
1179 if (!lhsType->isReferenceType())
1180 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001181
1182 Sema::AssignmentCheckResult result;
Steve Naroff90045e82007-07-13 23:32:42 +00001183
Steve Narofff1120de2007-08-24 22:33:52 +00001184 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1185
1186 // C99 6.5.16.1p2: The value of the right operand is converted to the
1187 // type of the assignment expression.
1188 if (rExpr->getType() != lhsType)
1189 promoteExprToType(rExpr, lhsType);
1190 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001191}
1192
1193Sema::AssignmentCheckResult
1194Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1195 return CheckAssignmentConstraints(lhsType, rhsType);
1196}
1197
Chris Lattnerca5eede2007-12-12 05:47:28 +00001198QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 Diag(loc, diag::err_typecheck_invalid_operands,
1200 lex->getType().getAsString(), rex->getType().getAsString(),
1201 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerca5eede2007-12-12 05:47:28 +00001202 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001203}
1204
Steve Naroff49b45262007-07-13 16:58:59 +00001205inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1206 Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001207 QualType lhsType = lex->getType(), rhsType = rex->getType();
1208
1209 // make sure the vector types are identical.
1210 if (lhsType == rhsType)
1211 return lhsType;
1212 // You cannot convert between vector values of different size.
1213 Diag(loc, diag::err_typecheck_vector_not_convertable,
1214 lex->getType().getAsString(), rex->getType().getAsString(),
1215 lex->getSourceRange(), rex->getSourceRange());
1216 return QualType();
1217}
1218
1219inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001220 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001221{
Steve Naroff90045e82007-07-13 23:32:42 +00001222 QualType lhsType = lex->getType(), rhsType = rex->getType();
1223
1224 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001225 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001226
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001227 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001228
Steve Naroffa4332e22007-07-17 00:58:39 +00001229 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001230 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001231 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001232}
1233
1234inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001235 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001236{
Steve Naroff90045e82007-07-13 23:32:42 +00001237 QualType lhsType = lex->getType(), rhsType = rex->getType();
1238
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001239 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001240
Steve Naroffa4332e22007-07-17 00:58:39 +00001241 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001242 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001243 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001244}
1245
1246inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001247 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001248{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001249 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001250 return CheckVectorOperands(loc, lex, rex);
1251
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001252 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Steve Naroff3e5e5562007-07-16 22:23:01 +00001253
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001255 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001256 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001257
Steve Naroffa4332e22007-07-17 00:58:39 +00001258 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1259 return lex->getType();
1260 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1261 return rex->getType();
Chris Lattnerca5eede2007-12-12 05:47:28 +00001262 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001263}
1264
1265inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001266 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001267{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001268 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001269 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001270
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001271 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001272
Chris Lattner6e4ab612007-12-09 21:53:25 +00001273 // Enforce type constraints: C99 6.5.6p3.
1274
1275 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001276 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001277 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001278
1279 // Either ptr - int or ptr - ptr.
1280 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1281 // The LHS must be an object type, not incomplete, function, etc.
1282 if (!LHSPTy->getPointeeType()->isObjectType()) {
1283 // Handle the GNU void* extension.
1284 if (LHSPTy->getPointeeType()->isVoidType()) {
1285 Diag(loc, diag::ext_gnu_void_ptr,
1286 lex->getSourceRange(), rex->getSourceRange());
1287 } else {
1288 Diag(loc, diag::err_typecheck_sub_ptr_object,
1289 lex->getType().getAsString(), lex->getSourceRange());
1290 return QualType();
1291 }
1292 }
1293
1294 // The result type of a pointer-int computation is the pointer type.
1295 if (rex->getType()->isIntegerType())
1296 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001297
Chris Lattner6e4ab612007-12-09 21:53:25 +00001298 // Handle pointer-pointer subtractions.
1299 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1300 // RHS must be an object type, unless void (GNU).
1301 if (!RHSPTy->getPointeeType()->isObjectType()) {
1302 // Handle the GNU void* extension.
1303 if (RHSPTy->getPointeeType()->isVoidType()) {
1304 if (!LHSPTy->getPointeeType()->isVoidType())
1305 Diag(loc, diag::ext_gnu_void_ptr,
1306 lex->getSourceRange(), rex->getSourceRange());
1307 } else {
1308 Diag(loc, diag::err_typecheck_sub_ptr_object,
1309 rex->getType().getAsString(), rex->getSourceRange());
1310 return QualType();
1311 }
1312 }
1313
1314 // Pointee types must be compatible.
1315 if (!Context.typesAreCompatible(LHSPTy->getPointeeType(),
1316 RHSPTy->getPointeeType())) {
1317 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1318 lex->getType().getAsString(), rex->getType().getAsString(),
1319 lex->getSourceRange(), rex->getSourceRange());
1320 return QualType();
1321 }
1322
1323 return Context.getPointerDiffType();
1324 }
1325 }
1326
Chris Lattnerca5eede2007-12-12 05:47:28 +00001327 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001328}
1329
1330inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Chris Lattnerca5eede2007-12-12 05:47:28 +00001331 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1332 // C99 6.5.7p2: Each of the operands shall have integer type.
1333 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1334 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001335
Chris Lattnerca5eede2007-12-12 05:47:28 +00001336 // Shifts don't perform usual arithmetic conversions, they just do integer
1337 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00001338 if (!isCompAssign)
1339 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00001340 UsualUnaryConversions(rex);
1341
1342 // "The type of the result is that of the promoted left operand."
1343 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001344}
1345
Chris Lattnera5937dd2007-08-26 01:18:55 +00001346inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1347 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Reid Spencer5f016e22007-07-11 17:01:13 +00001348{
Chris Lattnera5937dd2007-08-26 01:18:55 +00001349 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00001350 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1351 UsualArithmeticConversions(lex, rex);
1352 else {
1353 UsualUnaryConversions(lex);
1354 UsualUnaryConversions(rex);
1355 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001356 QualType lType = lex->getType();
1357 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001358
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001359 // For non-floating point types, check for self-comparisons of the form
1360 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1361 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001362 if (!lType->isFloatingType()) {
1363 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1364 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1365 if (DRL->getDecl() == DRR->getDecl())
1366 Diag(loc, diag::warn_selfcomparison);
1367 }
1368
Chris Lattnera5937dd2007-08-26 01:18:55 +00001369 if (isRelational) {
1370 if (lType->isRealType() && rType->isRealType())
1371 return Context.IntTy;
1372 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001373 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001374 if (lType->isFloatingType()) {
1375 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001376 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00001377 }
1378
Chris Lattnera5937dd2007-08-26 01:18:55 +00001379 if (lType->isArithmeticType() && rType->isArithmeticType())
1380 return Context.IntTy;
1381 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001382
Chris Lattnerd28f8152007-08-26 01:10:14 +00001383 bool LHSIsNull = lex->isNullPointerConstant(Context);
1384 bool RHSIsNull = rex->isNullPointerConstant(Context);
1385
Chris Lattnera5937dd2007-08-26 01:18:55 +00001386 // All of the following pointer related warnings are GCC extensions, except
1387 // when handling null pointer constants. One day, we can consider making them
1388 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00001389 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff66296cb2007-11-13 14:57:38 +00001390
1391 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1392 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1393 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroffec0550f2007-10-15 20:41:53 +00001394 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1395 rType.getUnqualifiedType())) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001396 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1397 lType.getAsString(), rType.getAsString(),
1398 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 }
Chris Lattnerd28f8152007-08-26 01:10:14 +00001400 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001401 return Context.IntTy;
1402 }
1403 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001404 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001405 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1406 lType.getAsString(), rType.getAsString(),
1407 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001408 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001409 return Context.IntTy;
1410 }
1411 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001412 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001413 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1414 lType.getAsString(), rType.getAsString(),
1415 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001416 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001417 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 }
Chris Lattnerca5eede2007-12-12 05:47:28 +00001419 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001420}
1421
Reid Spencer5f016e22007-07-11 17:01:13 +00001422inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001423 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001424{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001425 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001427
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001428 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001429
Steve Naroffa4332e22007-07-17 00:58:39 +00001430 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001431 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001432 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001433}
1434
1435inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00001436 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001437{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001438 UsualUnaryConversions(lex);
1439 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001440
Steve Naroffa4332e22007-07-17 00:58:39 +00001441 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001442 return Context.IntTy;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001443 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001444}
1445
1446inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00001447 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001448{
1449 QualType lhsType = lex->getType();
1450 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1451 bool hadError = false;
1452 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1453
1454 switch (mlval) { // C99 6.5.16p2
1455 case Expr::MLV_Valid:
1456 break;
1457 case Expr::MLV_ConstQualified:
1458 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1459 hadError = true;
1460 break;
1461 case Expr::MLV_ArrayType:
1462 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1463 lhsType.getAsString(), lex->getSourceRange());
1464 return QualType();
1465 case Expr::MLV_NotObjectType:
1466 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1467 lhsType.getAsString(), lex->getSourceRange());
1468 return QualType();
1469 case Expr::MLV_InvalidExpression:
1470 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1471 lex->getSourceRange());
1472 return QualType();
1473 case Expr::MLV_IncompleteType:
1474 case Expr::MLV_IncompleteVoidType:
1475 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1476 lhsType.getAsString(), lex->getSourceRange());
1477 return QualType();
Steve Narofffec0b492007-07-30 03:29:09 +00001478 case Expr::MLV_DuplicateVectorComponents:
1479 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1480 lex->getSourceRange());
1481 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 }
Steve Naroff90045e82007-07-13 23:32:42 +00001483 AssignmentCheckResult result;
1484
1485 if (compoundType.isNull())
1486 result = CheckSingleAssignmentConstraints(lhsType, rex);
1487 else
1488 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001489
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 // decode the result (notice that extensions still return a type).
1491 switch (result) {
1492 case Compatible:
1493 break;
1494 case Incompatible:
1495 Diag(loc, diag::err_typecheck_assign_incompatible,
1496 lhsType.getAsString(), rhsType.getAsString(),
1497 lex->getSourceRange(), rex->getSourceRange());
1498 hadError = true;
1499 break;
1500 case PointerFromInt:
Steve Naroff529a4ad2007-11-27 17:58:44 +00001501 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1502 lhsType.getAsString(), rhsType.getAsString(),
1503 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001504 break;
1505 case IntFromPointer:
1506 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1507 lhsType.getAsString(), rhsType.getAsString(),
1508 lex->getSourceRange(), rex->getSourceRange());
1509 break;
1510 case IncompatiblePointer:
1511 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1512 lhsType.getAsString(), rhsType.getAsString(),
1513 lex->getSourceRange(), rex->getSourceRange());
1514 break;
1515 case CompatiblePointerDiscardsQualifiers:
1516 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1517 lhsType.getAsString(), rhsType.getAsString(),
1518 lex->getSourceRange(), rex->getSourceRange());
1519 break;
1520 }
1521 // C99 6.5.16p3: The type of an assignment expression is the type of the
1522 // left operand unless the left operand has qualified type, in which case
1523 // it is the unqualified version of the type of the left operand.
1524 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1525 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001526 // C++ 5.17p1: the type of the assignment expression is that of its left
1527 // oprdu.
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 return hadError ? QualType() : lhsType.getUnqualifiedType();
1529}
1530
1531inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00001532 Expr *&lex, Expr *&rex, SourceLocation loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001533 UsualUnaryConversions(rex);
1534 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001535}
1536
Steve Naroff49b45262007-07-13 16:58:59 +00001537/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1538/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00001539QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00001540 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 assert(!resType.isNull() && "no type for increment/decrement expression");
1542
Steve Naroff084f9ed2007-08-24 17:20:07 +00001543 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00001544 if (const PointerType *pt = resType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001545 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1546 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1547 resType.getAsString(), op->getSourceRange());
1548 return QualType();
1549 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00001550 } else if (!resType->isRealType()) {
1551 if (resType->isComplexType())
1552 // C99 does not support ++/-- on complex types.
1553 Diag(OpLoc, diag::ext_integer_increment_complex,
1554 resType.getAsString(), op->getSourceRange());
1555 else {
1556 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1557 resType.getAsString(), op->getSourceRange());
1558 return QualType();
1559 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001560 }
Steve Naroffdd10e022007-08-23 21:37:33 +00001561 // At this point, we know we have a real, complex or pointer type.
1562 // Now make sure the operand is a modifiable lvalue.
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1564 if (mlval != Expr::MLV_Valid) {
1565 // FIXME: emit a more precise diagnostic...
1566 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1567 op->getSourceRange());
1568 return QualType();
1569 }
1570 return resType;
1571}
1572
1573/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1574/// This routine allows us to typecheck complex/recursive expressions
1575/// where the declaration is needed for type checking. Here are some
1576/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1577static Decl *getPrimaryDeclaration(Expr *e) {
1578 switch (e->getStmtClass()) {
1579 case Stmt::DeclRefExprClass:
1580 return cast<DeclRefExpr>(e)->getDecl();
1581 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00001582 // Fields cannot be declared with a 'register' storage class.
1583 // &X->f is always ok, even if X is declared register.
1584 if (cast<MemberExpr>(e)->isArrow())
1585 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1587 case Stmt::ArraySubscriptExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00001588 // &X[4] and &4[X] is invalid if X is invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Reid Spencer5f016e22007-07-11 17:01:13 +00001590 case Stmt::UnaryOperatorClass:
1591 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1592 case Stmt::ParenExprClass:
1593 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00001594 case Stmt::ImplicitCastExprClass:
1595 // &X[4] when X is an array, has an implicit cast from array to pointer.
1596 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 default:
1598 return 0;
1599 }
1600}
1601
1602/// CheckAddressOfOperand - The operand of & must be either a function
1603/// designator or an lvalue designating an object. If it is an lvalue, the
1604/// object cannot be declared with storage class register or be a bit field.
1605/// Note: The usual conversions are *not* applied to the operand of the &
1606/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1607QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1608 Decl *dcl = getPrimaryDeclaration(op);
1609 Expr::isLvalueResult lval = op->isLvalue();
1610
1611 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00001612 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1613 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00001614 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1615 op->getSourceRange());
1616 return QualType();
1617 }
1618 } else if (dcl) {
1619 // We have an lvalue with a decl. Make sure the decl is not declared
1620 // with the register storage-class specifier.
1621 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1622 if (vd->getStorageClass() == VarDecl::Register) {
1623 Diag(OpLoc, diag::err_typecheck_address_of_register,
1624 op->getSourceRange());
1625 return QualType();
1626 }
1627 } else
1628 assert(0 && "Unknown/unexpected decl type");
1629
1630 // FIXME: add check for bitfields!
1631 }
1632 // If the operand has type "type", the result has type "pointer to type".
1633 return Context.getPointerType(op->getType());
1634}
1635
1636QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001637 UsualUnaryConversions(op);
1638 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001639
Chris Lattnerbefee482007-07-31 16:53:04 +00001640 if (const PointerType *PT = qType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 QualType ptype = PT->getPointeeType();
1642 // C99 6.5.3.2p4. "if it points to an object,...".
1643 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1644 // GCC compat: special case 'void *' (treat as warning).
1645 if (ptype->isVoidType()) {
1646 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1647 qType.getAsString(), op->getSourceRange());
1648 } else {
1649 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1650 ptype.getAsString(), op->getSourceRange());
1651 return QualType();
1652 }
1653 }
1654 return ptype;
1655 }
1656 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1657 qType.getAsString(), op->getSourceRange());
1658 return QualType();
1659}
1660
1661static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1662 tok::TokenKind Kind) {
1663 BinaryOperator::Opcode Opc;
1664 switch (Kind) {
1665 default: assert(0 && "Unknown binop!");
1666 case tok::star: Opc = BinaryOperator::Mul; break;
1667 case tok::slash: Opc = BinaryOperator::Div; break;
1668 case tok::percent: Opc = BinaryOperator::Rem; break;
1669 case tok::plus: Opc = BinaryOperator::Add; break;
1670 case tok::minus: Opc = BinaryOperator::Sub; break;
1671 case tok::lessless: Opc = BinaryOperator::Shl; break;
1672 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1673 case tok::lessequal: Opc = BinaryOperator::LE; break;
1674 case tok::less: Opc = BinaryOperator::LT; break;
1675 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1676 case tok::greater: Opc = BinaryOperator::GT; break;
1677 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1678 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1679 case tok::amp: Opc = BinaryOperator::And; break;
1680 case tok::caret: Opc = BinaryOperator::Xor; break;
1681 case tok::pipe: Opc = BinaryOperator::Or; break;
1682 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1683 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1684 case tok::equal: Opc = BinaryOperator::Assign; break;
1685 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1686 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1687 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1688 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1689 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1690 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1691 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1692 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1693 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1694 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1695 case tok::comma: Opc = BinaryOperator::Comma; break;
1696 }
1697 return Opc;
1698}
1699
1700static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1701 tok::TokenKind Kind) {
1702 UnaryOperator::Opcode Opc;
1703 switch (Kind) {
1704 default: assert(0 && "Unknown unary op!");
1705 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1706 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1707 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1708 case tok::star: Opc = UnaryOperator::Deref; break;
1709 case tok::plus: Opc = UnaryOperator::Plus; break;
1710 case tok::minus: Opc = UnaryOperator::Minus; break;
1711 case tok::tilde: Opc = UnaryOperator::Not; break;
1712 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1713 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1714 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1715 case tok::kw___real: Opc = UnaryOperator::Real; break;
1716 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1717 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1718 }
1719 return Opc;
1720}
1721
1722// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001723Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00001724 ExprTy *LHS, ExprTy *RHS) {
1725 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1726 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1727
Steve Narofff69936d2007-09-16 03:34:24 +00001728 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1729 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00001730
1731 QualType ResultTy; // Result type of the binary operator.
1732 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1733
1734 switch (Opc) {
1735 default:
1736 assert(0 && "Unknown binary expr!");
1737 case BinaryOperator::Assign:
1738 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1739 break;
1740 case BinaryOperator::Mul:
1741 case BinaryOperator::Div:
1742 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1743 break;
1744 case BinaryOperator::Rem:
1745 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1746 break;
1747 case BinaryOperator::Add:
1748 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1749 break;
1750 case BinaryOperator::Sub:
1751 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1752 break;
1753 case BinaryOperator::Shl:
1754 case BinaryOperator::Shr:
1755 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1756 break;
1757 case BinaryOperator::LE:
1758 case BinaryOperator::LT:
1759 case BinaryOperator::GE:
1760 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001761 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001762 break;
1763 case BinaryOperator::EQ:
1764 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001765 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001766 break;
1767 case BinaryOperator::And:
1768 case BinaryOperator::Xor:
1769 case BinaryOperator::Or:
1770 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1771 break;
1772 case BinaryOperator::LAnd:
1773 case BinaryOperator::LOr:
1774 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1775 break;
1776 case BinaryOperator::MulAssign:
1777 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001778 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 if (!CompTy.isNull())
1780 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1781 break;
1782 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001783 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001784 if (!CompTy.isNull())
1785 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1786 break;
1787 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001788 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001789 if (!CompTy.isNull())
1790 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1791 break;
1792 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001793 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001794 if (!CompTy.isNull())
1795 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1796 break;
1797 case BinaryOperator::ShlAssign:
1798 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001799 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001800 if (!CompTy.isNull())
1801 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1802 break;
1803 case BinaryOperator::AndAssign:
1804 case BinaryOperator::XorAssign:
1805 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001806 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001807 if (!CompTy.isNull())
1808 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1809 break;
1810 case BinaryOperator::Comma:
1811 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1812 break;
1813 }
1814 if (ResultTy.isNull())
1815 return true;
1816 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001817 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001818 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001819 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001820}
1821
1822// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001823Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00001824 ExprTy *input) {
1825 Expr *Input = (Expr*)input;
1826 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1827 QualType resultType;
1828 switch (Opc) {
1829 default:
1830 assert(0 && "Unimplemented unary expr!");
1831 case UnaryOperator::PreInc:
1832 case UnaryOperator::PreDec:
1833 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1834 break;
1835 case UnaryOperator::AddrOf:
1836 resultType = CheckAddressOfOperand(Input, OpLoc);
1837 break;
1838 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00001839 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00001840 resultType = CheckIndirectionOperand(Input, OpLoc);
1841 break;
1842 case UnaryOperator::Plus:
1843 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001844 UsualUnaryConversions(Input);
1845 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001846 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1847 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1848 resultType.getAsString());
1849 break;
1850 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001851 UsualUnaryConversions(Input);
1852 resultType = Input->getType();
Steve Naroff084f9ed2007-08-24 17:20:07 +00001853 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1854 if (!resultType->isIntegerType()) {
1855 if (resultType->isComplexType())
1856 // C99 does not support '~' for complex conjugation.
1857 Diag(OpLoc, diag::ext_integer_complement_complex,
1858 resultType.getAsString());
1859 else
1860 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1861 resultType.getAsString());
1862 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001863 break;
1864 case UnaryOperator::LNot: // logical negation
1865 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001866 DefaultFunctionArrayConversion(Input);
1867 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001868 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1869 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1870 resultType.getAsString());
1871 // LNot always has type int. C99 6.5.3.3p5.
1872 resultType = Context.IntTy;
1873 break;
1874 case UnaryOperator::SizeOf:
1875 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1876 break;
1877 case UnaryOperator::AlignOf:
1878 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1879 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00001880 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00001881 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00001882 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00001883 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001884 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00001885 resultType = Input->getType();
1886 break;
1887 }
1888 if (resultType.isNull())
1889 return true;
1890 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1891}
1892
Steve Naroff1b273c42007-09-16 14:56:35 +00001893/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1894Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001895 SourceLocation LabLoc,
1896 IdentifierInfo *LabelII) {
1897 // Look up the record for this label identifier.
1898 LabelStmt *&LabelDecl = LabelMap[LabelII];
1899
1900 // If we haven't seen this label yet, create a forward reference.
1901 if (LabelDecl == 0)
1902 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1903
1904 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00001905 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1906 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001907}
1908
Steve Naroff1b273c42007-09-16 14:56:35 +00001909Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001910 SourceLocation RPLoc) { // "({..})"
1911 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1912 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1913 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1914
1915 // FIXME: there are a variety of strange constraints to enforce here, for
1916 // example, it is not possible to goto into a stmt expression apparently.
1917 // More semantic analysis is needed.
1918
1919 // FIXME: the last statement in the compount stmt has its value used. We
1920 // should not warn about it being unused.
1921
1922 // If there are sub stmts in the compound stmt, take the type of the last one
1923 // as the type of the stmtexpr.
1924 QualType Ty = Context.VoidTy;
1925
1926 if (!Compound->body_empty())
1927 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1928 Ty = LastExpr->getType();
1929
1930 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1931}
Steve Naroffd34e9152007-08-01 22:05:33 +00001932
Steve Naroff1b273c42007-09-16 14:56:35 +00001933Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001934 SourceLocation TypeLoc,
1935 TypeTy *argty,
1936 OffsetOfComponent *CompPtr,
1937 unsigned NumComponents,
1938 SourceLocation RPLoc) {
1939 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1940 assert(!ArgTy.isNull() && "Missing type argument!");
1941
1942 // We must have at least one component that refers to the type, and the first
1943 // one is known to be a field designator. Verify that the ArgTy represents
1944 // a struct/union/class.
1945 if (!ArgTy->isRecordType())
1946 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1947
1948 // Otherwise, create a compound literal expression as the base, and
1949 // iteratively process the offsetof designators.
1950 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1951
Chris Lattner9e2b75c2007-08-31 21:49:13 +00001952 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1953 // GCC extension, diagnose them.
1954 if (NumComponents != 1)
1955 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1956 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1957
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001958 for (unsigned i = 0; i != NumComponents; ++i) {
1959 const OffsetOfComponent &OC = CompPtr[i];
1960 if (OC.isBrackets) {
1961 // Offset of an array sub-field. TODO: Should we allow vector elements?
1962 const ArrayType *AT = Res->getType()->getAsArrayType();
1963 if (!AT) {
1964 delete Res;
1965 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1966 Res->getType().getAsString());
1967 }
1968
Chris Lattner704fe352007-08-30 17:59:59 +00001969 // FIXME: C++: Verify that operator[] isn't overloaded.
1970
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001971 // C99 6.5.2.1p1
1972 Expr *Idx = static_cast<Expr*>(OC.U.E);
1973 if (!Idx->getType()->isIntegerType())
1974 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1975 Idx->getSourceRange());
1976
1977 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1978 continue;
1979 }
1980
1981 const RecordType *RC = Res->getType()->getAsRecordType();
1982 if (!RC) {
1983 delete Res;
1984 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1985 Res->getType().getAsString());
1986 }
1987
1988 // Get the decl corresponding to this.
1989 RecordDecl *RD = RC->getDecl();
1990 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1991 if (!MemberDecl)
1992 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1993 OC.U.IdentInfo->getName(),
1994 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00001995
1996 // FIXME: C++: Verify that MemberDecl isn't a static field.
1997 // FIXME: Verify that MemberDecl isn't a bitfield.
1998
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001999 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
2000 }
2001
2002 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2003 BuiltinLoc);
2004}
2005
2006
Steve Naroff1b273c42007-09-16 14:56:35 +00002007Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00002008 TypeTy *arg1, TypeTy *arg2,
2009 SourceLocation RPLoc) {
2010 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2011 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2012
2013 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2014
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002015 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00002016}
2017
Steve Naroff1b273c42007-09-16 14:56:35 +00002018Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00002019 ExprTy *expr1, ExprTy *expr2,
2020 SourceLocation RPLoc) {
2021 Expr *CondExpr = static_cast<Expr*>(cond);
2022 Expr *LHSExpr = static_cast<Expr*>(expr1);
2023 Expr *RHSExpr = static_cast<Expr*>(expr2);
2024
2025 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2026
2027 // The conditional expression is required to be a constant expression.
2028 llvm::APSInt condEval(32);
2029 SourceLocation ExpLoc;
2030 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2031 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2032 CondExpr->getSourceRange());
2033
2034 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2035 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2036 RHSExpr->getType();
2037 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2038}
2039
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002040Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2041 ExprTy *expr, TypeTy *type,
2042 SourceLocation RPLoc)
2043{
2044 Expr *E = static_cast<Expr*>(expr);
2045 QualType T = QualType::getFromOpaquePtr(type);
2046
2047 InitBuiltinVaListType();
2048
2049 Sema::AssignmentCheckResult result;
2050
2051 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
2052 E->getType());
2053 if (result != Compatible)
2054 return Diag(E->getLocStart(),
2055 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2056 E->getType().getAsString(),
2057 E->getSourceRange());
2058
2059 // FIXME: Warn if a non-POD type is passed in.
2060
2061 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2062}
2063
Anders Carlsson55085182007-08-21 17:43:55 +00002064// TODO: Move this to SemaObjC.cpp
Chris Lattnerb3a99cd2007-12-12 01:04:12 +00002065Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
2066 ExprTy **Strings,
2067 unsigned NumStrings) {
Chris Lattnerb3a99cd2007-12-12 01:04:12 +00002068 SourceLocation AtLoc = AtLocs[0];
2069 StringLiteral* S = static_cast<StringLiteral *>(Strings[0]);
Fariborz Jahanian79a99f22007-12-12 23:55:49 +00002070 if (NumStrings > 1) {
2071 // Concatenate objc strings.
2072 StringLiteral* ES = static_cast<StringLiteral *>(Strings[NumStrings-1]);
2073 SourceLocation EndLoc = ES->getSourceRange().getEnd();
2074 unsigned Length = 0;
2075 for (unsigned i = 0; i < NumStrings; i++)
2076 Length += static_cast<StringLiteral *>(Strings[i])->getByteLength();
2077 char *strBuf = new char [Length];
2078 char *p = strBuf;
2079 bool isWide = false;
2080 for (unsigned i = 0; i < NumStrings; i++) {
2081 S = static_cast<StringLiteral *>(Strings[i]);
2082 if (S->isWide())
2083 isWide = true;
2084 memcpy(p, S->getStrData(), S->getByteLength());
2085 p += S->getByteLength();
2086 delete S;
2087 }
2088 S = new StringLiteral(strBuf, Length,
2089 isWide, Context.getPointerType(Context.CharTy),
2090 AtLoc, EndLoc);
2091 }
Anders Carlsson55085182007-08-21 17:43:55 +00002092
2093 if (CheckBuiltinCFStringArgument(S))
2094 return true;
2095
Steve Naroff21988912007-10-15 23:35:17 +00002096 if (Context.getObjcConstantStringInterface().isNull()) {
2097 // Initialize the constant string interface lazily. This assumes
2098 // the NSConstantString interface is seen in this translation unit.
2099 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
2100 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
2101 SourceLocation(), TUScope);
Steve Naroffa1fe1172007-10-16 00:00:18 +00002102 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff806a4eb2007-10-18 23:53:51 +00002103 if (!strIFace)
2104 return Diag(S->getLocStart(), diag::err_undef_interface,
2105 NSIdent->getName());
Steve Naroffa1fe1172007-10-16 00:00:18 +00002106 Context.setObjcConstantStringInterface(strIFace);
Steve Naroff21988912007-10-15 23:35:17 +00002107 }
2108 QualType t = Context.getObjcConstantStringInterface();
Anders Carlsson55085182007-08-21 17:43:55 +00002109 t = Context.getPointerType(t);
Steve Naroffbeaf2992007-11-03 11:27:19 +00002110 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlsson55085182007-08-21 17:43:55 +00002111}
Anders Carlssonf9bcf012007-08-22 15:14:15 +00002112
2113Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattner674af952007-10-16 22:51:17 +00002114 SourceLocation EncodeLoc,
Anders Carlssonf9bcf012007-08-22 15:14:15 +00002115 SourceLocation LParenLoc,
2116 TypeTy *Ty,
2117 SourceLocation RParenLoc) {
2118 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
2119
2120 QualType t = Context.getPointerType(Context.CharTy);
2121 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
2122}
Steve Naroff708391a2007-09-17 21:01:15 +00002123
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002124Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
2125 SourceLocation AtLoc,
Fariborz Jahanian2a35fa92007-10-16 23:21:02 +00002126 SourceLocation SelLoc,
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002127 SourceLocation LParenLoc,
2128 SourceLocation RParenLoc) {
Steve Naroff8ee529b2007-10-31 18:42:27 +00002129 QualType t = Context.getObjcSelType();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002130 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
2131}
2132
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002133Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
2134 SourceLocation AtLoc,
2135 SourceLocation ProtoLoc,
2136 SourceLocation LParenLoc,
2137 SourceLocation RParenLoc) {
2138 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
2139 if (!PDecl) {
2140 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
2141 return true;
2142 }
2143
Fariborz Jahanian66c5dfc2007-12-07 00:18:54 +00002144 QualType t = Context.getObjcProtoType();
Fariborz Jahanian3e27aa12007-10-18 22:59:23 +00002145 if (t.isNull())
2146 return true;
Fariborz Jahanian66c5dfc2007-12-07 00:18:54 +00002147 t = Context.getPointerType(t);
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002148 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
2149}
Steve Naroff81bfde92007-10-16 23:12:48 +00002150
2151bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2152 ObjcMethodDecl *Method) {
2153 bool anyIncompatibleArgs = false;
2154
2155 for (unsigned i = 0; i < NumArgs; i++) {
2156 Expr *argExpr = Args[i];
2157 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2158
2159 QualType lhsType = Method->getParamDecl(i)->getType();
2160 QualType rhsType = argExpr->getType();
2161
2162 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2163 if (const ArrayType *ary = lhsType->getAsArrayType())
2164 lhsType = Context.getPointerType(ary->getElementType());
2165 else if (lhsType->isFunctionType())
2166 lhsType = Context.getPointerType(lhsType);
2167
2168 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2169 argExpr);
2170 if (Args[i] != argExpr) // The expression was converted.
2171 Args[i] = argExpr; // Make sure we store the converted expression.
2172 SourceLocation l = argExpr->getLocStart();
2173
2174 // decode the result (notice that AST's are still created for extensions).
2175 switch (result) {
2176 case Compatible:
2177 break;
2178 case PointerFromInt:
Steve Naroff529a4ad2007-11-27 17:58:44 +00002179 Diag(l, diag::ext_typecheck_sending_pointer_int,
2180 lhsType.getAsString(), rhsType.getAsString(),
2181 argExpr->getSourceRange());
Steve Naroff81bfde92007-10-16 23:12:48 +00002182 break;
2183 case IntFromPointer:
2184 Diag(l, diag::ext_typecheck_sending_pointer_int,
2185 lhsType.getAsString(), rhsType.getAsString(),
2186 argExpr->getSourceRange());
2187 break;
2188 case IncompatiblePointer:
2189 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2190 rhsType.getAsString(), lhsType.getAsString(),
2191 argExpr->getSourceRange());
2192 break;
2193 case CompatiblePointerDiscardsQualifiers:
2194 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2195 rhsType.getAsString(), lhsType.getAsString(),
2196 argExpr->getSourceRange());
2197 break;
2198 case Incompatible:
2199 Diag(l, diag::err_typecheck_sending_incompatible,
2200 rhsType.getAsString(), lhsType.getAsString(),
2201 argExpr->getSourceRange());
2202 anyIncompatibleArgs = true;
2203 }
2204 }
2205 return anyIncompatibleArgs;
2206}
2207
Steve Naroff68d331a2007-09-27 14:38:14 +00002208// ActOnClassMessage - used for both unary and keyword messages.
2209// ArgExprs is optional - if it is present, the number of expressions
2210// is obtained from Sel.getNumArgs().
2211Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002212 Scope *S,
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002213 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff49f109c2007-11-15 13:05:42 +00002214 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff708391a2007-09-17 21:01:15 +00002215{
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002216 assert(receiverName && "missing receiver class name");
Steve Naroff563477d2007-09-18 23:55:05 +00002217
Steve Naroff81bfde92007-10-16 23:12:48 +00002218 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002219 ObjcInterfaceDecl* ClassDecl = 0;
2220 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2221 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahaniancffff842007-11-12 20:20:37 +00002222 if (ClassDecl && CurMethodDecl->isInstance()) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002223 // Synthesize a cast to the super class. This hack allows us to loosely
2224 // represent super without creating a special expression node.
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002225 IdentifierInfo &II = Context.Idents.get("self");
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002226 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II, false);
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002227 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2228 superTy = Context.getPointerType(superTy);
2229 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2230 SourceLocation(), ReceiverExpr.Val);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002231 // We are really in an instance method, redirect.
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002232 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
Steve Naroff49f109c2007-11-15 13:05:42 +00002233 Args, NumArgs);
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002234 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002235 // We are sending a message to 'super' within a class method. Do nothing,
2236 // the receiver will pass through as 'super' (how convenient:-).
2237 } else
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002238 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002239
2240 // FIXME: can ClassDecl ever be null?
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002241 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff983df5b2007-10-16 20:39:36 +00002242 QualType returnType;
Steve Naroff945c0a82007-11-05 15:27:52 +00002243
2244 // Before we give up, check if the selector is an instance method.
2245 if (!Method)
2246 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff983df5b2007-10-16 20:39:36 +00002247 if (!Method) {
2248 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2249 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002250 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002251 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002252 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002253 if (Sel.getNumArgs()) {
2254 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2255 return true;
2256 }
Steve Naroff983df5b2007-10-16 20:39:36 +00002257 }
Steve Naroffdb611d52007-11-03 16:37:59 +00002258 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
Steve Naroff49f109c2007-11-15 13:05:42 +00002259 lbrac, rbrac, ArgExprs, NumArgs);
Steve Naroff708391a2007-09-17 21:01:15 +00002260}
2261
Steve Naroff68d331a2007-09-27 14:38:14 +00002262// ActOnInstanceMessage - used for both unary and keyword messages.
2263// ArgExprs is optional - if it is present, the number of expressions
2264// is obtained from Sel.getNumArgs().
2265Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroffbcfb06a2007-09-28 22:22:11 +00002266 ExprTy *receiver, Selector Sel,
Steve Naroff49f109c2007-11-15 13:05:42 +00002267 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff68d331a2007-09-27 14:38:14 +00002268{
Steve Naroff563477d2007-09-18 23:55:05 +00002269 assert(receiver && "missing receiver expression");
2270
Steve Naroff81bfde92007-10-16 23:12:48 +00002271 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroff563477d2007-09-18 23:55:05 +00002272 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002273 QualType receiverType = RExpr->getType();
Steve Naroff3b950172007-10-10 21:53:07 +00002274 QualType returnType;
Steve Naroffdb611d52007-11-03 16:37:59 +00002275 ObjcMethodDecl *Method;
Steve Naroff3b950172007-10-10 21:53:07 +00002276
Steve Naroff7c249152007-11-11 17:52:25 +00002277 if (receiverType == Context.getObjcIdType() ||
2278 receiverType == Context.getObjcClassType()) {
Steve Naroffdb611d52007-11-03 16:37:59 +00002279 Method = InstanceMethodPool[Sel].Method;
Steve Naroffa56f6162007-12-18 01:30:32 +00002280 if (!Method)
2281 Method = FactoryMethodPool[Sel].Method;
Steve Naroff983df5b2007-10-16 20:39:36 +00002282 if (!Method) {
2283 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2284 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002285 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002286 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002287 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002288 if (Sel.getNumArgs())
2289 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2290 return true;
Steve Naroff983df5b2007-10-16 20:39:36 +00002291 }
Steve Naroff3b950172007-10-10 21:53:07 +00002292 } else {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002293 bool receiverIsQualId =
2294 dyn_cast<ObjcQualifiedIdType>(RExpr->getType()) != 0;
Chris Lattner22b73ba2007-10-10 23:42:28 +00002295 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2296 // revisited. how do we get the ClassDecl from the receiver expression?
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002297 if (!receiverIsQualId)
2298 while (receiverType->isPointerType()) {
2299 PointerType *pointerType =
2300 static_cast<PointerType*>(receiverType.getTypePtr());
2301 receiverType = pointerType->getPointeeType();
2302 }
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002303 ObjcInterfaceDecl* ClassDecl;
2304 if (ObjcQualifiedInterfaceType *QIT =
2305 dyn_cast<ObjcQualifiedInterfaceType>(receiverType)) {
Fariborz Jahanian06cef252007-12-13 20:47:42 +00002306 ClassDecl = QIT->getDecl();
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002307 Method = ClassDecl->lookupInstanceMethod(Sel);
2308 if (!Method) {
2309 // search protocols
2310 for (unsigned i = 0; i < QIT->getNumProtocols(); i++) {
2311 ObjcProtocolDecl *PDecl = QIT->getProtocols(i);
2312 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
2313 break;
2314 }
2315 }
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002316 if (!Method)
2317 Diag(lbrac, diag::warn_method_not_found_in_protocol,
2318 std::string("-"), Sel.getName(),
2319 SourceRange(lbrac, rbrac));
2320 }
2321 else if (ObjcQualifiedIdType *QIT =
2322 dyn_cast<ObjcQualifiedIdType>(receiverType)) {
2323 // search protocols
2324 for (unsigned i = 0; i < QIT->getNumProtocols(); i++) {
2325 ObjcProtocolDecl *PDecl = QIT->getProtocols(i);
2326 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
2327 break;
2328 }
2329 if (!Method)
2330 Diag(lbrac, diag::warn_method_not_found_in_protocol,
2331 std::string("-"), Sel.getName(),
2332 SourceRange(lbrac, rbrac));
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002333 }
2334 else {
2335 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2336 "bad receiver type");
2337 ClassDecl = static_cast<ObjcInterfaceType*>(
2338 receiverType.getTypePtr())->getDecl();
2339 // FIXME: consider using InstanceMethodPool, since it will be faster
2340 // than the following method (which can do *many* linear searches). The
2341 // idea is to add class info to InstanceMethodPool...
2342 Method = ClassDecl->lookupInstanceMethod(Sel);
2343 }
Steve Naroff983df5b2007-10-16 20:39:36 +00002344 if (!Method) {
Steve Naroffc43d8682007-11-11 00:10:47 +00002345 // If we have an implementation in scope, check "private" methods.
2346 if (ObjcImplementationDecl *ImpDecl =
2347 ObjcImplementations[ClassDecl->getIdentifier()])
Steve Naroff94a5c332007-12-19 22:27:04 +00002348 Method = ImpDecl->getInstanceMethod(Sel);
Steve Naroff9a4ad372007-12-11 03:38:03 +00002349 // If we still haven't found a method, look in the global pool. This
2350 // behavior isn't very desirable, however we need it for GCC compatibility.
Steve Naroff9feba022007-12-07 20:41:14 +00002351 if (!Method)
2352 Method = InstanceMethodPool[Sel].Method;
Steve Naroffc43d8682007-11-11 00:10:47 +00002353 }
2354 if (!Method) {
Steve Naroff983df5b2007-10-16 20:39:36 +00002355 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2356 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002357 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002358 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002359 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002360 if (Sel.getNumArgs())
2361 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2362 return true;
Steve Naroff983df5b2007-10-16 20:39:36 +00002363 }
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002364 }
Steve Naroffdb611d52007-11-03 16:37:59 +00002365 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
Steve Naroff49f109c2007-11-15 13:05:42 +00002366 ArgExprs, NumArgs);
Steve Naroff708391a2007-09-17 21:01:15 +00002367}