blob: d51a29631bf92619d8670859aa6353e14ac565b3 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +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"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
Steve Narofffa465d12007-10-02 20:01:56 +000017#include "clang/AST/DeclObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "clang/AST/Expr.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000019#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/Diagnostic.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
26#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000027#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028using namespace clang;
29
Steve Naroff87d58b42007-09-16 03:34:24 +000030/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000031/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
32/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
33/// multiple tokens. However, the common case is that StringToks points to one
34/// string.
35///
36Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000037Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000038 assert(NumStringToks && "Must have at least one string!");
39
40 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
41 if (Literal.hadError)
42 return ExprResult(true);
43
44 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
45 for (unsigned i = 0; i != NumStringToks; ++i)
46 StringTokLocs.push_back(StringToks[i].getLocation());
47
48 // FIXME: handle wchar_t
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000049 QualType t;
50
51 if (Literal.Pascal)
52 t = Context.getPointerType(Context.UnsignedCharTy);
53 else
54 t = Context.getPointerType(Context.CharTy);
55
56 if (Literal.Pascal && Literal.GetStringLength() > 256)
57 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
58 SourceRange(StringToks[0].getLocation(),
59 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000060
61 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
62 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000063 Literal.AnyWide, t,
64 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000065 StringToks[NumStringToks-1].getLocation());
66}
67
68
Steve Naroff0acc9c92007-09-15 18:49:24 +000069/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000070/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
71/// identifier is used in an function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000072Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000073 IdentifierInfo &II,
74 bool HasTrailingLParen) {
75 // Could be enum-constant or decl.
Steve Narofff0c31dd2007-09-16 16:16:00 +000076 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Chris Lattner4b009652007-07-25 00:24:17 +000077 if (D == 0) {
78 // Otherwise, this could be an implicitly declared function reference (legal
79 // in C90, extension in C99).
80 if (HasTrailingLParen &&
81 // Not in C++.
82 !getLangOptions().CPlusPlus)
83 D = ImplicitlyDefineFunction(Loc, II, S);
84 else {
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000085 if (CurMethodDecl) {
86 ObjcInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
87 ObjcInterfaceDecl *clsDeclared;
88 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared))
89 return new ObjCIvarRefExpr(IV, IV->getType(), Loc);
90 }
Chris Lattner4b009652007-07-25 00:24:17 +000091 // If this name wasn't predeclared and if this is not a function call,
92 // diagnose the problem.
93 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
94 }
95 }
Steve Naroff91b03f72007-08-28 03:03:08 +000096 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroffcae537d2007-08-28 18:45:29 +000097 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +000098 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +000099 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000100 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000101 }
Chris Lattner4b009652007-07-25 00:24:17 +0000102 if (isa<TypedefDecl>(D))
103 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
104
105 assert(0 && "Invalid decl");
106 abort();
107}
108
Steve Naroff87d58b42007-09-16 03:34:24 +0000109Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000110 tok::TokenKind Kind) {
111 PreDefinedExpr::IdentType IT;
112
113 switch (Kind) {
114 default:
115 assert(0 && "Unknown simple primary expr!");
116 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
117 IT = PreDefinedExpr::Func;
118 break;
119 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
120 IT = PreDefinedExpr::Function;
121 break;
122 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
123 IT = PreDefinedExpr::PrettyFunction;
124 break;
125 }
126
127 // Pre-defined identifiers are always of type char *.
128 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
129}
130
Steve Naroff87d58b42007-09-16 03:34:24 +0000131Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000132 llvm::SmallString<16> CharBuffer;
133 CharBuffer.resize(Tok.getLength());
134 const char *ThisTokBegin = &CharBuffer[0];
135 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
136
137 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
138 Tok.getLocation(), PP);
139 if (Literal.hadError())
140 return ExprResult(true);
141 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
142 Tok.getLocation());
143}
144
Steve Naroff87d58b42007-09-16 03:34:24 +0000145Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000146 // fast path for a single digit (which is quite common). A single digit
147 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
148 if (Tok.getLength() == 1) {
149 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
150
Chris Lattner3496d522007-09-04 02:45:27 +0000151 unsigned IntSize = static_cast<unsigned>(
152 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000153 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
154 Context.IntTy,
155 Tok.getLocation()));
156 }
157 llvm::SmallString<512> IntegerBuffer;
158 IntegerBuffer.resize(Tok.getLength());
159 const char *ThisTokBegin = &IntegerBuffer[0];
160
161 // Get the spelling of the token, which eliminates trigraphs, etc.
162 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
163 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
164 Tok.getLocation(), PP);
165 if (Literal.hadError)
166 return ExprResult(true);
167
Chris Lattner1de66eb2007-08-26 03:42:43 +0000168 Expr *Res;
169
170 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000171 QualType Ty;
172 const llvm::fltSemantics *Format;
173 uint64_t Size; unsigned Align;
174
175 if (Literal.isFloat) {
176 Ty = Context.FloatTy;
177 Context.Target.getFloatInfo(Size, Align, Format, Tok.getLocation());
178 } else if (Literal.isLong) {
179 Ty = Context.LongDoubleTy;
180 Context.Target.getLongDoubleInfo(Size, Align, Format, Tok.getLocation());
181 } else {
182 Ty = Context.DoubleTy;
183 Context.Target.getDoubleInfo(Size, Align, Format, Tok.getLocation());
184 }
185
186 Res = new FloatingLiteral(Literal.GetFloatValue(*Format), Ty,
187 Tok.getLocation());
Chris Lattner1de66eb2007-08-26 03:42:43 +0000188 } else if (!Literal.isIntegerLiteral()) {
189 return ExprResult(true);
190 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000191 QualType t;
192
Neil Booth7421e9c2007-08-29 22:00:19 +0000193 // long long is a C99 feature.
194 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000195 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000196 Diag(Tok.getLocation(), diag::ext_longlong);
197
Chris Lattner4b009652007-07-25 00:24:17 +0000198 // Get the value in the widest-possible width.
199 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
200
201 if (Literal.GetIntegerValue(ResultVal)) {
202 // If this value didn't fit into uintmax_t, warn and force to ull.
203 Diag(Tok.getLocation(), diag::warn_integer_too_large);
204 t = Context.UnsignedLongLongTy;
205 assert(Context.getTypeSize(t, Tok.getLocation()) ==
206 ResultVal.getBitWidth() && "long long is not intmax_t?");
207 } else {
208 // If this value fits into a ULL, try to figure out what else it fits into
209 // according to the rules of C99 6.4.4.1p5.
210
211 // Octal, Hexadecimal, and integers with a U suffix are allowed to
212 // be an unsigned int.
213 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
214
215 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000216 if (!Literal.isLong && !Literal.isLongLong) {
217 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000218 unsigned IntSize = static_cast<unsigned>(
219 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000220 // Does it fit in a unsigned int?
221 if (ResultVal.isIntN(IntSize)) {
222 // Does it fit in a signed int?
223 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
224 t = Context.IntTy;
225 else if (AllowUnsigned)
226 t = Context.UnsignedIntTy;
227 }
228
229 if (!t.isNull())
230 ResultVal.trunc(IntSize);
231 }
232
233 // Are long/unsigned long possibilities?
234 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000235 unsigned LongSize = static_cast<unsigned>(
236 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000237
238 // Does it fit in a unsigned long?
239 if (ResultVal.isIntN(LongSize)) {
240 // Does it fit in a signed long?
241 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
242 t = Context.LongTy;
243 else if (AllowUnsigned)
244 t = Context.UnsignedLongTy;
245 }
246 if (!t.isNull())
247 ResultVal.trunc(LongSize);
248 }
249
250 // Finally, check long long if needed.
251 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000252 unsigned LongLongSize = static_cast<unsigned>(
253 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000254
255 // Does it fit in a unsigned long long?
256 if (ResultVal.isIntN(LongLongSize)) {
257 // Does it fit in a signed long long?
258 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
259 t = Context.LongLongTy;
260 else if (AllowUnsigned)
261 t = Context.UnsignedLongLongTy;
262 }
263 }
264
265 // If we still couldn't decide a type, we probably have something that
266 // does not fit in a signed long long, but has no U suffix.
267 if (t.isNull()) {
268 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
269 t = Context.UnsignedLongLongTy;
270 }
271 }
272
Chris Lattner1de66eb2007-08-26 03:42:43 +0000273 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000274 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000275
276 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
277 if (Literal.isImaginary)
278 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
279
280 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000281}
282
Steve Naroff87d58b42007-09-16 03:34:24 +0000283Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000284 ExprTy *Val) {
285 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000286 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000287 return new ParenExpr(L, R, e);
288}
289
290/// The UsualUnaryConversions() function is *not* called by this routine.
291/// See C99 6.3.2.1p[2-4] for more details.
292QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
293 SourceLocation OpLoc, bool isSizeof) {
294 // C99 6.5.3.4p1:
295 if (isa<FunctionType>(exprType) && isSizeof)
296 // alignof(function) is allowed.
297 Diag(OpLoc, diag::ext_sizeof_function_type);
298 else if (exprType->isVoidType())
299 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
300 else if (exprType->isIncompleteType()) {
301 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
302 diag::err_alignof_incomplete_type,
303 exprType.getAsString());
304 return QualType(); // error
305 }
306 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
307 return Context.getSizeType();
308}
309
310Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000311ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000312 SourceLocation LPLoc, TypeTy *Ty,
313 SourceLocation RPLoc) {
314 // If error parsing type, ignore.
315 if (Ty == 0) return true;
316
317 // Verify that this is a valid expression.
318 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
319
320 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
321
322 if (resultType.isNull())
323 return true;
324 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
325}
326
Chris Lattner5110ad52007-08-24 21:41:10 +0000327QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000328 DefaultFunctionArrayConversion(V);
329
Chris Lattnera16e42d2007-08-26 05:39:26 +0000330 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000331 if (const ComplexType *CT = V->getType()->getAsComplexType())
332 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000333
334 // Otherwise they pass through real integer and floating point types here.
335 if (V->getType()->isArithmeticType())
336 return V->getType();
337
338 // Reject anything else.
339 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
340 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000341}
342
343
Chris Lattner4b009652007-07-25 00:24:17 +0000344
Steve Naroff87d58b42007-09-16 03:34:24 +0000345Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000346 tok::TokenKind Kind,
347 ExprTy *Input) {
348 UnaryOperator::Opcode Opc;
349 switch (Kind) {
350 default: assert(0 && "Unknown unary op!");
351 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
352 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
353 }
354 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
355 if (result.isNull())
356 return true;
357 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
358}
359
360Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000361ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000362 ExprTy *Idx, SourceLocation RLoc) {
363 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
364
365 // Perform default conversions.
366 DefaultFunctionArrayConversion(LHSExp);
367 DefaultFunctionArrayConversion(RHSExp);
368
369 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
370
371 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000372 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000373 // in the subscript position. As a result, we need to derive the array base
374 // and index from the expression types.
375 Expr *BaseExpr, *IndexExpr;
376 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000377 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000378 BaseExpr = LHSExp;
379 IndexExpr = RHSExp;
380 // FIXME: need to deal with const...
381 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000382 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000383 // Handle the uncommon case of "123[Ptr]".
384 BaseExpr = RHSExp;
385 IndexExpr = LHSExp;
386 // FIXME: need to deal with const...
387 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000388 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
389 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000390 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000391
392 // Component access limited to variables (reject vec4.rg[1]).
393 if (!isa<DeclRefExpr>(BaseExpr))
394 return Diag(LLoc, diag::err_ocuvector_component_access,
395 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000396 // FIXME: need to deal with const...
397 ResultType = VTy->getElementType();
398 } else {
399 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
400 RHSExp->getSourceRange());
401 }
402 // C99 6.5.2.1p1
403 if (!IndexExpr->getType()->isIntegerType())
404 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
405 IndexExpr->getSourceRange());
406
407 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
408 // the following check catches trying to index a pointer to a function (e.g.
409 // void (*)(int)). Functions are not objects in C99.
410 if (!ResultType->isObjectType())
411 return Diag(BaseExpr->getLocStart(),
412 diag::err_typecheck_subscript_not_object,
413 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
414
415 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
416}
417
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000418QualType Sema::
419CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
420 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000421 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000422
423 // The vector accessor can't exceed the number of elements.
424 const char *compStr = CompName.getName();
425 if (strlen(compStr) > vecType->getNumElements()) {
426 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
427 baseType.getAsString(), SourceRange(CompLoc));
428 return QualType();
429 }
430 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000431 if (vecType->getPointAccessorIdx(*compStr) != -1) {
432 do
433 compStr++;
434 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
435 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
436 do
437 compStr++;
438 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
439 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
440 do
441 compStr++;
442 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
443 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000444
445 if (*compStr) {
446 // We didn't get to the end of the string. This means the component names
447 // didn't come from the same set *or* we encountered an illegal name.
448 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
449 std::string(compStr,compStr+1), SourceRange(CompLoc));
450 return QualType();
451 }
452 // Each component accessor can't exceed the vector type.
453 compStr = CompName.getName();
454 while (*compStr) {
455 if (vecType->isAccessorWithinNumElements(*compStr))
456 compStr++;
457 else
458 break;
459 }
460 if (*compStr) {
461 // We didn't get to the end of the string. This means a component accessor
462 // exceeds the number of elements in the vector.
463 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
464 baseType.getAsString(), SourceRange(CompLoc));
465 return QualType();
466 }
467 // The component accessor looks fine - now we need to compute the actual type.
468 // The vector type is implied by the component accessor. For example,
469 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
470 unsigned CompSize = strlen(CompName.getName());
471 if (CompSize == 1)
472 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000473
474 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
475 // Now look up the TypeDefDecl from the vector type. Without this,
476 // diagostics look bad. We want OCU vector types to appear built-in.
477 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
478 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
479 return Context.getTypedefType(OCUVectorDecls[i]);
480 }
481 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000482}
483
Chris Lattner4b009652007-07-25 00:24:17 +0000484Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000485ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000486 tok::TokenKind OpKind, SourceLocation MemberLoc,
487 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000488 Expr *BaseExpr = static_cast<Expr *>(Base);
489 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000490
Steve Naroff2cb66382007-07-26 03:11:44 +0000491 QualType BaseType = BaseExpr->getType();
492 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000493
Chris Lattner4b009652007-07-25 00:24:17 +0000494 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000495 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000496 BaseType = PT->getPointeeType();
497 else
498 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
499 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000500 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000501 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000502 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000503 RecordDecl *RDecl = RTy->getDecl();
504 if (RTy->isIncompleteType())
505 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
506 BaseExpr->getSourceRange());
507 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000508 FieldDecl *MemberDecl = RDecl->getMember(&Member);
509 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000510 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
511 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000512 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
513 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000514 // Component access limited to variables (reject vec4.rg.g).
515 if (!isa<DeclRefExpr>(BaseExpr))
516 return Diag(OpLoc, diag::err_ocuvector_component_access,
517 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000518 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
519 if (ret.isNull())
520 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000521 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Steve Naroff2cb66382007-07-26 03:11:44 +0000522 } else
523 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
524 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000525}
526
Steve Naroff87d58b42007-09-16 03:34:24 +0000527/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000528/// This provides the location of the left/right parens and a list of comma
529/// locations.
530Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000531ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000532 ExprTy **args, unsigned NumArgsInCall,
533 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
534 Expr *Fn = static_cast<Expr *>(fn);
535 Expr **Args = reinterpret_cast<Expr**>(args);
536 assert(Fn && "no function call expression");
537
538 UsualUnaryConversions(Fn);
539 QualType funcType = Fn->getType();
540
541 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
542 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000543 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000544 if (PT == 0)
545 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
546 SourceRange(Fn->getLocStart(), RParenLoc));
547
Chris Lattner71225142007-07-31 21:27:01 +0000548 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000549 if (funcT == 0)
550 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
551 SourceRange(Fn->getLocStart(), RParenLoc));
552
553 // If a prototype isn't declared, the parser implicitly defines a func decl
554 QualType resultType = funcT->getResultType();
555
556 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
557 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
558 // assignment, to the types of the corresponding parameter, ...
559
560 unsigned NumArgsInProto = proto->getNumArgs();
561 unsigned NumArgsToCheck = NumArgsInCall;
562
563 if (NumArgsInCall < NumArgsInProto)
564 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
565 Fn->getSourceRange());
566 else if (NumArgsInCall > NumArgsInProto) {
567 if (!proto->isVariadic()) {
568 Diag(Args[NumArgsInProto]->getLocStart(),
569 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
570 SourceRange(Args[NumArgsInProto]->getLocStart(),
571 Args[NumArgsInCall-1]->getLocEnd()));
572 }
573 NumArgsToCheck = NumArgsInProto;
574 }
575 // Continue to check argument types (even if we have too few/many args).
576 for (unsigned i = 0; i < NumArgsToCheck; i++) {
577 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000578 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000579
580 QualType lhsType = proto->getArgType(i);
581 QualType rhsType = argExpr->getType();
582
Steve Naroff75644062007-07-25 20:45:33 +0000583 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000584 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000585 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000586 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000587 lhsType = Context.getPointerType(lhsType);
588
589 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
590 argExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000591 if (Args[i] != argExpr) // The expression was converted.
592 Args[i] = argExpr; // Make sure we store the converted expression.
Chris Lattner4b009652007-07-25 00:24:17 +0000593 SourceLocation l = argExpr->getLocStart();
594
595 // decode the result (notice that AST's are still created for extensions).
596 switch (result) {
597 case Compatible:
598 break;
599 case PointerFromInt:
600 // check for null pointer constant (C99 6.3.2.3p3)
601 if (!argExpr->isNullPointerConstant(Context)) {
602 Diag(l, diag::ext_typecheck_passing_pointer_int,
603 lhsType.getAsString(), rhsType.getAsString(),
604 Fn->getSourceRange(), argExpr->getSourceRange());
605 }
606 break;
607 case IntFromPointer:
608 Diag(l, diag::ext_typecheck_passing_pointer_int,
609 lhsType.getAsString(), rhsType.getAsString(),
610 Fn->getSourceRange(), argExpr->getSourceRange());
611 break;
612 case IncompatiblePointer:
613 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
614 rhsType.getAsString(), lhsType.getAsString(),
615 Fn->getSourceRange(), argExpr->getSourceRange());
616 break;
617 case CompatiblePointerDiscardsQualifiers:
618 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
619 rhsType.getAsString(), lhsType.getAsString(),
620 Fn->getSourceRange(), argExpr->getSourceRange());
621 break;
622 case Incompatible:
623 return Diag(l, diag::err_typecheck_passing_incompatible,
624 rhsType.getAsString(), lhsType.getAsString(),
625 Fn->getSourceRange(), argExpr->getSourceRange());
626 }
627 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000628 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
629 // Promote the arguments (C99 6.5.2.2p7).
630 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
631 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000632 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000633
634 DefaultArgumentPromotion(argExpr);
635 if (Args[i] != argExpr) // The expression was converted.
636 Args[i] = argExpr; // Make sure we store the converted expression.
637 }
638 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
639 // Even if the types checked, bail if the number of arguments don't match.
Chris Lattner4b009652007-07-25 00:24:17 +0000640 return true;
Steve Naroffdb65e052007-08-28 23:30:39 +0000641 }
642 } else if (isa<FunctionTypeNoProto>(funcT)) {
643 // Promote the arguments (C99 6.5.2.2p6).
644 for (unsigned i = 0; i < NumArgsInCall; i++) {
645 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000646 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000647
648 DefaultArgumentPromotion(argExpr);
649 if (Args[i] != argExpr) // The expression was converted.
650 Args[i] = argExpr; // Make sure we store the converted expression.
651 }
Chris Lattner4b009652007-07-25 00:24:17 +0000652 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000653 // Do special checking on direct calls to functions.
654 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
655 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
656 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000657 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
658 NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000659 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000660
Chris Lattner4b009652007-07-25 00:24:17 +0000661 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
662}
663
664Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000665ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000666 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000667 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000668 QualType literalType = QualType::getFromOpaquePtr(Ty);
669 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000670 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000671 Expr *literalExpr = static_cast<Expr*>(InitExpr);
672
673 // FIXME: add semantic analysis (C99 6.5.2.5).
674 return new CompoundLiteralExpr(literalType, literalExpr);
675}
676
677Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000678ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000679 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000680 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000681
Steve Naroff0acc9c92007-09-15 18:49:24 +0000682 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000683 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000684
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000685 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
686 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
687 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000688}
689
690Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000691ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000692 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000693 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000694
695 Expr *castExpr = static_cast<Expr*>(Op);
696 QualType castType = QualType::getFromOpaquePtr(Ty);
697
Steve Naroff68adb482007-08-31 00:32:44 +0000698 UsualUnaryConversions(castExpr);
699
Chris Lattner4b009652007-07-25 00:24:17 +0000700 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
701 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000702 if (!castType->isVoidType()) { // Cast to void allows any expr type.
703 if (!castType->isScalarType())
704 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
705 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
706 if (!castExpr->getType()->isScalarType()) {
707 return Diag(castExpr->getLocStart(),
708 diag::err_typecheck_expect_scalar_operand,
709 castExpr->getType().getAsString(),castExpr->getSourceRange());
710 }
Chris Lattner4b009652007-07-25 00:24:17 +0000711 }
712 return new CastExpr(castType, castExpr, LParenLoc);
713}
714
Steve Naroff144667e2007-10-18 05:13:08 +0000715// promoteExprToType - a helper function to ensure we create exactly one
716// ImplicitCastExpr.
717static void promoteExprToType(Expr *&expr, QualType type) {
718 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
719 impCast->setType(type);
720 else
721 expr = new ImplicitCastExpr(type, expr);
722 return;
723}
724
Chris Lattner4b009652007-07-25 00:24:17 +0000725inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
726 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
727 UsualUnaryConversions(cond);
728 UsualUnaryConversions(lex);
729 UsualUnaryConversions(rex);
730 QualType condT = cond->getType();
731 QualType lexT = lex->getType();
732 QualType rexT = rex->getType();
733
734 // first, check the condition.
735 if (!condT->isScalarType()) { // C99 6.5.15p2
736 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
737 condT.getAsString());
738 return QualType();
739 }
740 // now check the two expressions.
741 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
742 UsualArithmeticConversions(lex, rex);
743 return lex->getType();
744 }
Chris Lattner71225142007-07-31 21:27:01 +0000745 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
746 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
747
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000748 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
Chris Lattner71225142007-07-31 21:27:01 +0000749 return lexT;
750
Chris Lattner4b009652007-07-25 00:24:17 +0000751 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
752 lexT.getAsString(), rexT.getAsString(),
753 lex->getSourceRange(), rex->getSourceRange());
754 return QualType();
755 }
756 }
757 // C99 6.5.15p3
Steve Naroff144667e2007-10-18 05:13:08 +0000758 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
759 promoteExprToType(rex, lexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000760 return lexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000761 }
762 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
763 promoteExprToType(lex, rexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000764 return rexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000765 }
Chris Lattner71225142007-07-31 21:27:01 +0000766 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
767 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
768 // get the "pointed to" types
769 QualType lhptee = LHSPT->getPointeeType();
770 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000771
Chris Lattner71225142007-07-31 21:27:01 +0000772 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
773 if (lhptee->isVoidType() &&
774 (rhptee->isObjectType() || rhptee->isIncompleteType()))
775 return lexT;
776 if (rhptee->isVoidType() &&
777 (lhptee->isObjectType() || lhptee->isIncompleteType()))
778 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000779
Steve Naroff85f0dc52007-10-15 20:41:53 +0000780 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
781 rhptee.getUnqualifiedType())) {
Chris Lattner71225142007-07-31 21:27:01 +0000782 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
783 lexT.getAsString(), rexT.getAsString(),
784 lex->getSourceRange(), rex->getSourceRange());
785 return lexT; // FIXME: this is an _ext - is this return o.k?
786 }
787 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000788 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
789 // differently qualified versions of compatible types, the result type is
790 // a pointer to an appropriately qualified version of the *composite*
791 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000792 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000793 }
Chris Lattner4b009652007-07-25 00:24:17 +0000794 }
Chris Lattner71225142007-07-31 21:27:01 +0000795
Chris Lattner4b009652007-07-25 00:24:17 +0000796 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
797 return lexT;
798
799 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
800 lexT.getAsString(), rexT.getAsString(),
801 lex->getSourceRange(), rex->getSourceRange());
802 return QualType();
803}
804
Steve Naroff87d58b42007-09-16 03:34:24 +0000805/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000806/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000807Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000808 SourceLocation ColonLoc,
809 ExprTy *Cond, ExprTy *LHS,
810 ExprTy *RHS) {
811 Expr *CondExpr = (Expr *) Cond;
812 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
813 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
814 RHSExpr, QuestionLoc);
815 if (result.isNull())
816 return true;
817 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
818}
819
Steve Naroffdb65e052007-08-28 23:30:39 +0000820/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
821/// do not have a prototype. Integer promotions are performed on each
822/// argument, and arguments that have type float are promoted to double.
823void Sema::DefaultArgumentPromotion(Expr *&expr) {
824 QualType t = expr->getType();
825 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
826
827 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
828 promoteExprToType(expr, Context.IntTy);
829 if (t == Context.FloatTy)
830 promoteExprToType(expr, Context.DoubleTy);
831}
832
Chris Lattner4b009652007-07-25 00:24:17 +0000833/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
834void Sema::DefaultFunctionArrayConversion(Expr *&e) {
835 QualType t = e->getType();
836 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
837
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000838 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000839 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
840 t = e->getType();
841 }
842 if (t->isFunctionType())
843 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000844 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000845 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
846}
847
848/// UsualUnaryConversion - Performs various conversions that are common to most
849/// operators (C99 6.3). The conversions of array and function types are
850/// sometimes surpressed. For example, the array->pointer conversion doesn't
851/// apply if the array is an argument to the sizeof or address (&) operators.
852/// In these instances, this routine should *not* be called.
853void Sema::UsualUnaryConversions(Expr *&expr) {
854 QualType t = expr->getType();
855 assert(!t.isNull() && "UsualUnaryConversions - missing type");
856
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000857 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000858 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
859 t = expr->getType();
860 }
861 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
862 promoteExprToType(expr, Context.IntTy);
863 else
864 DefaultFunctionArrayConversion(expr);
865}
866
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000867/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000868/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
869/// routine returns the first non-arithmetic type found. The client is
870/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000871QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
872 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000873 if (!isCompAssign) {
874 UsualUnaryConversions(lhsExpr);
875 UsualUnaryConversions(rhsExpr);
876 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000877 // For conversion purposes, we ignore any qualifiers.
878 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000879 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
880 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000881
882 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000883 if (lhs == rhs)
884 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000885
886 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
887 // The caller can deal with this (e.g. pointer + int).
888 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000889 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000890
891 // At this point, we have two different arithmetic types.
892
893 // Handle complex types first (C99 6.3.1.8p1).
894 if (lhs->isComplexType() || rhs->isComplexType()) {
895 // if we have an integer operand, the result is the complex type.
896 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000897 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
898 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000899 }
900 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000901 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
902 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000903 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000904 // This handles complex/complex, complex/float, or float/complex.
905 // When both operands are complex, the shorter operand is converted to the
906 // type of the longer, and that is the type of the result. This corresponds
907 // to what is done when combining two real floating-point operands.
908 // The fun begins when size promotion occur across type domains.
909 // From H&S 6.3.4: When one operand is complex and the other is a real
910 // floating-point type, the less precise type is converted, within it's
911 // real or complex domain, to the precision of the other type. For example,
912 // when combining a "long double" with a "double _Complex", the
913 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000914 int result = Context.compareFloatingType(lhs, rhs);
915
916 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000917 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
918 if (!isCompAssign)
919 promoteExprToType(rhsExpr, rhs);
920 } else if (result < 0) { // The right side is bigger, convert lhs.
921 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
922 if (!isCompAssign)
923 promoteExprToType(lhsExpr, lhs);
924 }
925 // At this point, lhs and rhs have the same rank/size. Now, make sure the
926 // domains match. This is a requirement for our implementation, C99
927 // does not require this promotion.
928 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
929 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000930 if (!isCompAssign)
931 promoteExprToType(lhsExpr, rhs);
932 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000933 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000934 if (!isCompAssign)
935 promoteExprToType(rhsExpr, lhs);
936 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000937 }
Chris Lattner4b009652007-07-25 00:24:17 +0000938 }
Steve Naroff3b6157f2007-08-27 21:43:43 +0000939 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +0000940 }
941 // Now handle "real" floating types (i.e. float, double, long double).
942 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
943 // if we have an integer operand, the result is the real floating type.
944 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000945 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
946 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000947 }
948 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000949 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
950 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000951 }
952 // We have two real floating types, float/complex combos were handled above.
953 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +0000954 int result = Context.compareFloatingType(lhs, rhs);
955
956 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000957 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
958 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000959 }
Steve Naroff45fc9822007-08-27 15:30:22 +0000960 if (result < 0) { // convert the lhs
961 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
962 return rhs;
963 }
964 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +0000965 }
966 // Finally, we have two differing integer types.
967 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000968 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
969 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000970 }
Steve Naroff8f708362007-08-24 19:07:16 +0000971 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
972 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000973}
974
975// CheckPointerTypesForAssignment - This is a very tricky routine (despite
976// being closely modeled after the C99 spec:-). The odd characteristic of this
977// routine is it effectively iqnores the qualifiers on the top level pointee.
978// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
979// FIXME: add a couple examples in this comment.
980Sema::AssignmentCheckResult
981Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
982 QualType lhptee, rhptee;
983
984 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +0000985 lhptee = lhsType->getAsPointerType()->getPointeeType();
986 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000987
988 // make sure we operate on the canonical type
989 lhptee = lhptee.getCanonicalType();
990 rhptee = rhptee.getCanonicalType();
991
992 AssignmentCheckResult r = Compatible;
993
994 // C99 6.5.16.1p1: This following citation is common to constraints
995 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
996 // qualifiers of the type *pointed to* by the right;
997 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
998 rhptee.getQualifiers())
999 r = CompatiblePointerDiscardsQualifiers;
1000
1001 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1002 // incomplete type and the other is a pointer to a qualified or unqualified
1003 // version of void...
1004 if (lhptee.getUnqualifiedType()->isVoidType() &&
1005 (rhptee->isObjectType() || rhptee->isIncompleteType()))
1006 ;
1007 else if (rhptee.getUnqualifiedType()->isVoidType() &&
1008 (lhptee->isObjectType() || lhptee->isIncompleteType()))
1009 ;
1010 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1011 // unqualified versions of compatible types, ...
Steve Naroff85f0dc52007-10-15 20:41:53 +00001012 else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1013 rhptee.getUnqualifiedType()))
Chris Lattner4b009652007-07-25 00:24:17 +00001014 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1015 return r;
1016}
1017
1018/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1019/// has code to accommodate several GCC extensions when type checking
1020/// pointers. Here are some objectionable examples that GCC considers warnings:
1021///
1022/// int a, *pint;
1023/// short *pshort;
1024/// struct foo *pfoo;
1025///
1026/// pint = pshort; // warning: assignment from incompatible pointer type
1027/// a = pint; // warning: assignment makes integer from pointer without a cast
1028/// pint = a; // warning: assignment makes pointer from integer without a cast
1029/// pint = pfoo; // warning: assignment from incompatible pointer type
1030///
1031/// As a result, the code for dealing with pointers is more complex than the
1032/// C99 spec dictates.
1033/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1034///
1035Sema::AssignmentCheckResult
1036Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera703c2e2007-10-29 05:15:40 +00001037 if (lhsType.getCanonicalType() == rhsType.getCanonicalType())
1038 return Compatible; // common case, fast path...
Chris Lattner4b009652007-07-25 00:24:17 +00001039
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001040 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001041 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001042 return Compatible;
1043 } else if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001044 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1045 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1046 return Incompatible;
1047 }
1048 return Compatible;
1049 } else if (lhsType->isPointerType()) {
1050 if (rhsType->isIntegerType())
1051 return PointerFromInt;
1052
1053 if (rhsType->isPointerType())
1054 return CheckPointerTypesForAssignment(lhsType, rhsType);
1055 } else if (rhsType->isPointerType()) {
1056 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1057 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1058 return IntFromPointer;
1059
1060 if (lhsType->isPointerType())
1061 return CheckPointerTypesForAssignment(lhsType, rhsType);
1062 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001063 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001064 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001065 }
1066 return Incompatible;
1067}
1068
1069Sema::AssignmentCheckResult
1070Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Chris Lattner5f505bf2007-10-16 02:55:40 +00001071 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001072 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001073 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001074 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001075 //
1076 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1077 // are better understood.
1078 if (!lhsType->isReferenceType())
1079 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001080
1081 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +00001082
Steve Naroff0f32f432007-08-24 22:33:52 +00001083 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1084
1085 // C99 6.5.16.1p2: The value of the right operand is converted to the
1086 // type of the assignment expression.
1087 if (rExpr->getType() != lhsType)
1088 promoteExprToType(rExpr, lhsType);
1089 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001090}
1091
1092Sema::AssignmentCheckResult
1093Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1094 return CheckAssignmentConstraints(lhsType, rhsType);
1095}
1096
1097inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1098 Diag(loc, diag::err_typecheck_invalid_operands,
1099 lex->getType().getAsString(), rex->getType().getAsString(),
1100 lex->getSourceRange(), rex->getSourceRange());
1101}
1102
1103inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1104 Expr *&rex) {
1105 QualType lhsType = lex->getType(), rhsType = rex->getType();
1106
1107 // make sure the vector types are identical.
1108 if (lhsType == rhsType)
1109 return lhsType;
1110 // You cannot convert between vector values of different size.
1111 Diag(loc, diag::err_typecheck_vector_not_convertable,
1112 lex->getType().getAsString(), rex->getType().getAsString(),
1113 lex->getSourceRange(), rex->getSourceRange());
1114 return QualType();
1115}
1116
1117inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001118 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001119{
1120 QualType lhsType = lex->getType(), rhsType = rex->getType();
1121
1122 if (lhsType->isVectorType() || rhsType->isVectorType())
1123 return CheckVectorOperands(loc, lex, rex);
1124
Steve Naroff8f708362007-08-24 19:07:16 +00001125 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001126
Chris Lattner4b009652007-07-25 00:24:17 +00001127 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001128 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001129 InvalidOperands(loc, lex, rex);
1130 return QualType();
1131}
1132
1133inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001134 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001135{
1136 QualType lhsType = lex->getType(), rhsType = rex->getType();
1137
Steve Naroff8f708362007-08-24 19:07:16 +00001138 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001139
Chris Lattner4b009652007-07-25 00:24:17 +00001140 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001141 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001142 InvalidOperands(loc, lex, rex);
1143 return QualType();
1144}
1145
1146inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001147 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001148{
1149 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1150 return CheckVectorOperands(loc, lex, rex);
1151
Steve Naroff8f708362007-08-24 19:07:16 +00001152 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001153
1154 // handle the common case first (both operands are arithmetic).
1155 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001156 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001157
1158 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1159 return lex->getType();
1160 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1161 return rex->getType();
1162 InvalidOperands(loc, lex, rex);
1163 return QualType();
1164}
1165
1166inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001167 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001168{
1169 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1170 return CheckVectorOperands(loc, lex, rex);
1171
Steve Naroff8f708362007-08-24 19:07:16 +00001172 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001173
1174 // handle the common case first (both operands are arithmetic).
1175 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001176 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001177
1178 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001179 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001180 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1181 return Context.getPointerDiffType();
1182 InvalidOperands(loc, lex, rex);
1183 return QualType();
1184}
1185
1186inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001187 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001188{
1189 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1190 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001191 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001192
1193 // handle the common case first (both operands are arithmetic).
1194 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001195 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001196 InvalidOperands(loc, lex, rex);
1197 return QualType();
1198}
1199
Ted Kremenekdbb14ce2007-10-29 16:45:23 +00001200// Utility method to plow through parentheses to get the first nested
1201// non-ParenExpr expr.
1202static inline Expr* IgnoreParen(Expr* E) {
Ted Kremenek193c1252007-10-30 21:03:09 +00001203 while (ParenExpr* P = dyn_cast<ParenExpr>(E))
1204 E = P->getSubExpr();
Ted Kremenekdbb14ce2007-10-29 16:45:23 +00001205
1206 return E;
1207}
1208
Chris Lattner254f3bc2007-08-26 01:18:55 +00001209inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1210 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001211{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001212 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001213 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1214 UsualArithmeticConversions(lex, rex);
1215 else {
1216 UsualUnaryConversions(lex);
1217 UsualUnaryConversions(rex);
1218 }
Chris Lattner4b009652007-07-25 00:24:17 +00001219 QualType lType = lex->getType();
1220 QualType rType = rex->getType();
1221
Ted Kremenek486509e2007-10-29 17:13:39 +00001222
1223 // For non-floating point types, check for self-comparisons of the form
1224 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1225 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001226 if (!lType->isFloatingType()) {
1227 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1228 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1229 if (DRL->getDecl() == DRR->getDecl())
1230 Diag(loc, diag::warn_selfcomparison);
1231 }
1232
Chris Lattner254f3bc2007-08-26 01:18:55 +00001233 if (isRelational) {
1234 if (lType->isRealType() && rType->isRealType())
1235 return Context.IntTy;
1236 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001237 // Check for comparisons of floating point operands using != and ==.
1238 // Issue a warning if these are no self-comparisons, as they are not likely
1239 // to do what the programmer intended.
1240 if (lType->isFloatingType()) {
1241 assert (rType->isFloatingType());
1242
Ted Kremenek75439142007-10-29 16:40:01 +00001243 // Special case: check for x == x (which is OK).
1244 bool EmitWarning = true;
1245
Ted Kremenekdbb14ce2007-10-29 16:45:23 +00001246 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1247 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
Ted Kremenek75439142007-10-29 16:40:01 +00001248 if (DRL->getDecl() == DRR->getDecl())
1249 EmitWarning = false;
1250
1251 if (EmitWarning)
1252 Diag(loc, diag::warn_floatingpoint_eq);
1253 }
1254
Chris Lattner254f3bc2007-08-26 01:18:55 +00001255 if (lType->isArithmeticType() && rType->isArithmeticType())
1256 return Context.IntTy;
1257 }
Chris Lattner4b009652007-07-25 00:24:17 +00001258
Chris Lattner22be8422007-08-26 01:10:14 +00001259 bool LHSIsNull = lex->isNullPointerConstant(Context);
1260 bool RHSIsNull = rex->isNullPointerConstant(Context);
1261
Chris Lattner254f3bc2007-08-26 01:18:55 +00001262 // All of the following pointer related warnings are GCC extensions, except
1263 // when handling null pointer constants. One day, we can consider making them
1264 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001265 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner22be8422007-08-26 01:10:14 +00001266 if (!LHSIsNull && !RHSIsNull &&
Steve Naroff85f0dc52007-10-15 20:41:53 +00001267 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1268 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001269 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1270 lType.getAsString(), rType.getAsString(),
1271 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001272 }
Chris Lattner22be8422007-08-26 01:10:14 +00001273 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001274 return Context.IntTy;
1275 }
1276 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001277 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001278 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1279 lType.getAsString(), rType.getAsString(),
1280 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001281 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001282 return Context.IntTy;
1283 }
1284 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001285 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001286 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1287 lType.getAsString(), rType.getAsString(),
1288 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001289 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001290 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001291 }
1292 InvalidOperands(loc, lex, rex);
1293 return QualType();
1294}
1295
Chris Lattner4b009652007-07-25 00:24:17 +00001296inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001297 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001298{
1299 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1300 return CheckVectorOperands(loc, lex, rex);
1301
Steve Naroff8f708362007-08-24 19:07:16 +00001302 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001303
1304 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001305 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001306 InvalidOperands(loc, lex, rex);
1307 return QualType();
1308}
1309
1310inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1311 Expr *&lex, Expr *&rex, SourceLocation loc)
1312{
1313 UsualUnaryConversions(lex);
1314 UsualUnaryConversions(rex);
1315
1316 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1317 return Context.IntTy;
1318 InvalidOperands(loc, lex, rex);
1319 return QualType();
1320}
1321
1322inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001323 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001324{
1325 QualType lhsType = lex->getType();
1326 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1327 bool hadError = false;
1328 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1329
1330 switch (mlval) { // C99 6.5.16p2
1331 case Expr::MLV_Valid:
1332 break;
1333 case Expr::MLV_ConstQualified:
1334 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1335 hadError = true;
1336 break;
1337 case Expr::MLV_ArrayType:
1338 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1339 lhsType.getAsString(), lex->getSourceRange());
1340 return QualType();
1341 case Expr::MLV_NotObjectType:
1342 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1343 lhsType.getAsString(), lex->getSourceRange());
1344 return QualType();
1345 case Expr::MLV_InvalidExpression:
1346 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1347 lex->getSourceRange());
1348 return QualType();
1349 case Expr::MLV_IncompleteType:
1350 case Expr::MLV_IncompleteVoidType:
1351 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1352 lhsType.getAsString(), lex->getSourceRange());
1353 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001354 case Expr::MLV_DuplicateVectorComponents:
1355 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1356 lex->getSourceRange());
1357 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001358 }
1359 AssignmentCheckResult result;
1360
1361 if (compoundType.isNull())
1362 result = CheckSingleAssignmentConstraints(lhsType, rex);
1363 else
1364 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001365
Chris Lattner4b009652007-07-25 00:24:17 +00001366 // decode the result (notice that extensions still return a type).
1367 switch (result) {
1368 case Compatible:
1369 break;
1370 case Incompatible:
1371 Diag(loc, diag::err_typecheck_assign_incompatible,
1372 lhsType.getAsString(), rhsType.getAsString(),
1373 lex->getSourceRange(), rex->getSourceRange());
1374 hadError = true;
1375 break;
1376 case PointerFromInt:
1377 // check for null pointer constant (C99 6.3.2.3p3)
1378 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1379 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1380 lhsType.getAsString(), rhsType.getAsString(),
1381 lex->getSourceRange(), rex->getSourceRange());
1382 }
1383 break;
1384 case IntFromPointer:
1385 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1386 lhsType.getAsString(), rhsType.getAsString(),
1387 lex->getSourceRange(), rex->getSourceRange());
1388 break;
1389 case IncompatiblePointer:
1390 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1391 lhsType.getAsString(), rhsType.getAsString(),
1392 lex->getSourceRange(), rex->getSourceRange());
1393 break;
1394 case CompatiblePointerDiscardsQualifiers:
1395 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1396 lhsType.getAsString(), rhsType.getAsString(),
1397 lex->getSourceRange(), rex->getSourceRange());
1398 break;
1399 }
1400 // C99 6.5.16p3: The type of an assignment expression is the type of the
1401 // left operand unless the left operand has qualified type, in which case
1402 // it is the unqualified version of the type of the left operand.
1403 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1404 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001405 // C++ 5.17p1: the type of the assignment expression is that of its left
1406 // oprdu.
Chris Lattner4b009652007-07-25 00:24:17 +00001407 return hadError ? QualType() : lhsType.getUnqualifiedType();
1408}
1409
1410inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1411 Expr *&lex, Expr *&rex, SourceLocation loc) {
1412 UsualUnaryConversions(rex);
1413 return rex->getType();
1414}
1415
1416/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1417/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1418QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1419 QualType resType = op->getType();
1420 assert(!resType.isNull() && "no type for increment/decrement expression");
1421
Steve Naroffd30e1932007-08-24 17:20:07 +00001422 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001423 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001424 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1425 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1426 resType.getAsString(), op->getSourceRange());
1427 return QualType();
1428 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001429 } else if (!resType->isRealType()) {
1430 if (resType->isComplexType())
1431 // C99 does not support ++/-- on complex types.
1432 Diag(OpLoc, diag::ext_integer_increment_complex,
1433 resType.getAsString(), op->getSourceRange());
1434 else {
1435 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1436 resType.getAsString(), op->getSourceRange());
1437 return QualType();
1438 }
Chris Lattner4b009652007-07-25 00:24:17 +00001439 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001440 // At this point, we know we have a real, complex or pointer type.
1441 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001442 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1443 if (mlval != Expr::MLV_Valid) {
1444 // FIXME: emit a more precise diagnostic...
1445 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1446 op->getSourceRange());
1447 return QualType();
1448 }
1449 return resType;
1450}
1451
1452/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1453/// This routine allows us to typecheck complex/recursive expressions
1454/// where the declaration is needed for type checking. Here are some
1455/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1456static Decl *getPrimaryDeclaration(Expr *e) {
1457 switch (e->getStmtClass()) {
1458 case Stmt::DeclRefExprClass:
1459 return cast<DeclRefExpr>(e)->getDecl();
1460 case Stmt::MemberExprClass:
1461 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1462 case Stmt::ArraySubscriptExprClass:
1463 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1464 case Stmt::CallExprClass:
1465 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1466 case Stmt::UnaryOperatorClass:
1467 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1468 case Stmt::ParenExprClass:
1469 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1470 default:
1471 return 0;
1472 }
1473}
1474
1475/// CheckAddressOfOperand - The operand of & must be either a function
1476/// designator or an lvalue designating an object. If it is an lvalue, the
1477/// object cannot be declared with storage class register or be a bit field.
1478/// Note: The usual conversions are *not* applied to the operand of the &
1479/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1480QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1481 Decl *dcl = getPrimaryDeclaration(op);
1482 Expr::isLvalueResult lval = op->isLvalue();
1483
1484 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1485 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1486 ;
1487 else { // FIXME: emit more specific diag...
1488 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1489 op->getSourceRange());
1490 return QualType();
1491 }
1492 } else if (dcl) {
1493 // We have an lvalue with a decl. Make sure the decl is not declared
1494 // with the register storage-class specifier.
1495 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1496 if (vd->getStorageClass() == VarDecl::Register) {
1497 Diag(OpLoc, diag::err_typecheck_address_of_register,
1498 op->getSourceRange());
1499 return QualType();
1500 }
1501 } else
1502 assert(0 && "Unknown/unexpected decl type");
1503
1504 // FIXME: add check for bitfields!
1505 }
1506 // If the operand has type "type", the result has type "pointer to type".
1507 return Context.getPointerType(op->getType());
1508}
1509
1510QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1511 UsualUnaryConversions(op);
1512 QualType qType = op->getType();
1513
Chris Lattner7931f4a2007-07-31 16:53:04 +00001514 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001515 QualType ptype = PT->getPointeeType();
1516 // C99 6.5.3.2p4. "if it points to an object,...".
1517 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1518 // GCC compat: special case 'void *' (treat as warning).
1519 if (ptype->isVoidType()) {
1520 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1521 qType.getAsString(), op->getSourceRange());
1522 } else {
1523 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1524 ptype.getAsString(), op->getSourceRange());
1525 return QualType();
1526 }
1527 }
1528 return ptype;
1529 }
1530 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1531 qType.getAsString(), op->getSourceRange());
1532 return QualType();
1533}
1534
1535static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1536 tok::TokenKind Kind) {
1537 BinaryOperator::Opcode Opc;
1538 switch (Kind) {
1539 default: assert(0 && "Unknown binop!");
1540 case tok::star: Opc = BinaryOperator::Mul; break;
1541 case tok::slash: Opc = BinaryOperator::Div; break;
1542 case tok::percent: Opc = BinaryOperator::Rem; break;
1543 case tok::plus: Opc = BinaryOperator::Add; break;
1544 case tok::minus: Opc = BinaryOperator::Sub; break;
1545 case tok::lessless: Opc = BinaryOperator::Shl; break;
1546 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1547 case tok::lessequal: Opc = BinaryOperator::LE; break;
1548 case tok::less: Opc = BinaryOperator::LT; break;
1549 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1550 case tok::greater: Opc = BinaryOperator::GT; break;
1551 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1552 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1553 case tok::amp: Opc = BinaryOperator::And; break;
1554 case tok::caret: Opc = BinaryOperator::Xor; break;
1555 case tok::pipe: Opc = BinaryOperator::Or; break;
1556 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1557 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1558 case tok::equal: Opc = BinaryOperator::Assign; break;
1559 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1560 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1561 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1562 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1563 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1564 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1565 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1566 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1567 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1568 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1569 case tok::comma: Opc = BinaryOperator::Comma; break;
1570 }
1571 return Opc;
1572}
1573
1574static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1575 tok::TokenKind Kind) {
1576 UnaryOperator::Opcode Opc;
1577 switch (Kind) {
1578 default: assert(0 && "Unknown unary op!");
1579 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1580 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1581 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1582 case tok::star: Opc = UnaryOperator::Deref; break;
1583 case tok::plus: Opc = UnaryOperator::Plus; break;
1584 case tok::minus: Opc = UnaryOperator::Minus; break;
1585 case tok::tilde: Opc = UnaryOperator::Not; break;
1586 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1587 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1588 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1589 case tok::kw___real: Opc = UnaryOperator::Real; break;
1590 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1591 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1592 }
1593 return Opc;
1594}
1595
1596// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001597Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001598 ExprTy *LHS, ExprTy *RHS) {
1599 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1600 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1601
Steve Naroff87d58b42007-09-16 03:34:24 +00001602 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1603 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001604
1605 QualType ResultTy; // Result type of the binary operator.
1606 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1607
1608 switch (Opc) {
1609 default:
1610 assert(0 && "Unknown binary expr!");
1611 case BinaryOperator::Assign:
1612 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1613 break;
1614 case BinaryOperator::Mul:
1615 case BinaryOperator::Div:
1616 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1617 break;
1618 case BinaryOperator::Rem:
1619 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1620 break;
1621 case BinaryOperator::Add:
1622 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1623 break;
1624 case BinaryOperator::Sub:
1625 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1626 break;
1627 case BinaryOperator::Shl:
1628 case BinaryOperator::Shr:
1629 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1630 break;
1631 case BinaryOperator::LE:
1632 case BinaryOperator::LT:
1633 case BinaryOperator::GE:
1634 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001635 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001636 break;
1637 case BinaryOperator::EQ:
1638 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001639 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001640 break;
1641 case BinaryOperator::And:
1642 case BinaryOperator::Xor:
1643 case BinaryOperator::Or:
1644 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1645 break;
1646 case BinaryOperator::LAnd:
1647 case BinaryOperator::LOr:
1648 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1649 break;
1650 case BinaryOperator::MulAssign:
1651 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001652 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001653 if (!CompTy.isNull())
1654 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1655 break;
1656 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001657 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001658 if (!CompTy.isNull())
1659 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1660 break;
1661 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001662 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001663 if (!CompTy.isNull())
1664 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1665 break;
1666 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001667 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001668 if (!CompTy.isNull())
1669 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1670 break;
1671 case BinaryOperator::ShlAssign:
1672 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001673 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001674 if (!CompTy.isNull())
1675 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1676 break;
1677 case BinaryOperator::AndAssign:
1678 case BinaryOperator::XorAssign:
1679 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001680 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001681 if (!CompTy.isNull())
1682 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1683 break;
1684 case BinaryOperator::Comma:
1685 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1686 break;
1687 }
1688 if (ResultTy.isNull())
1689 return true;
1690 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001691 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001692 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001693 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001694}
1695
1696// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001697Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001698 ExprTy *input) {
1699 Expr *Input = (Expr*)input;
1700 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1701 QualType resultType;
1702 switch (Opc) {
1703 default:
1704 assert(0 && "Unimplemented unary expr!");
1705 case UnaryOperator::PreInc:
1706 case UnaryOperator::PreDec:
1707 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1708 break;
1709 case UnaryOperator::AddrOf:
1710 resultType = CheckAddressOfOperand(Input, OpLoc);
1711 break;
1712 case UnaryOperator::Deref:
1713 resultType = CheckIndirectionOperand(Input, OpLoc);
1714 break;
1715 case UnaryOperator::Plus:
1716 case UnaryOperator::Minus:
1717 UsualUnaryConversions(Input);
1718 resultType = Input->getType();
1719 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1720 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1721 resultType.getAsString());
1722 break;
1723 case UnaryOperator::Not: // bitwise complement
1724 UsualUnaryConversions(Input);
1725 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001726 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1727 if (!resultType->isIntegerType()) {
1728 if (resultType->isComplexType())
1729 // C99 does not support '~' for complex conjugation.
1730 Diag(OpLoc, diag::ext_integer_complement_complex,
1731 resultType.getAsString());
1732 else
1733 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1734 resultType.getAsString());
1735 }
Chris Lattner4b009652007-07-25 00:24:17 +00001736 break;
1737 case UnaryOperator::LNot: // logical negation
1738 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1739 DefaultFunctionArrayConversion(Input);
1740 resultType = Input->getType();
1741 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1742 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1743 resultType.getAsString());
1744 // LNot always has type int. C99 6.5.3.3p5.
1745 resultType = Context.IntTy;
1746 break;
1747 case UnaryOperator::SizeOf:
1748 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1749 break;
1750 case UnaryOperator::AlignOf:
1751 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1752 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001753 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001754 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001755 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001756 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001757 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001758 resultType = Input->getType();
1759 break;
1760 }
1761 if (resultType.isNull())
1762 return true;
1763 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1764}
1765
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001766/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1767Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001768 SourceLocation LabLoc,
1769 IdentifierInfo *LabelII) {
1770 // Look up the record for this label identifier.
1771 LabelStmt *&LabelDecl = LabelMap[LabelII];
1772
1773 // If we haven't seen this label yet, create a forward reference.
1774 if (LabelDecl == 0)
1775 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1776
1777 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001778 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1779 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001780}
1781
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001782Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00001783 SourceLocation RPLoc) { // "({..})"
1784 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1785 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1786 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1787
1788 // FIXME: there are a variety of strange constraints to enforce here, for
1789 // example, it is not possible to goto into a stmt expression apparently.
1790 // More semantic analysis is needed.
1791
1792 // FIXME: the last statement in the compount stmt has its value used. We
1793 // should not warn about it being unused.
1794
1795 // If there are sub stmts in the compound stmt, take the type of the last one
1796 // as the type of the stmtexpr.
1797 QualType Ty = Context.VoidTy;
1798
1799 if (!Compound->body_empty())
1800 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1801 Ty = LastExpr->getType();
1802
1803 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1804}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001805
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001806Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001807 SourceLocation TypeLoc,
1808 TypeTy *argty,
1809 OffsetOfComponent *CompPtr,
1810 unsigned NumComponents,
1811 SourceLocation RPLoc) {
1812 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1813 assert(!ArgTy.isNull() && "Missing type argument!");
1814
1815 // We must have at least one component that refers to the type, and the first
1816 // one is known to be a field designator. Verify that the ArgTy represents
1817 // a struct/union/class.
1818 if (!ArgTy->isRecordType())
1819 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1820
1821 // Otherwise, create a compound literal expression as the base, and
1822 // iteratively process the offsetof designators.
1823 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1824
Chris Lattnerb37522e2007-08-31 21:49:13 +00001825 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1826 // GCC extension, diagnose them.
1827 if (NumComponents != 1)
1828 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1829 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1830
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001831 for (unsigned i = 0; i != NumComponents; ++i) {
1832 const OffsetOfComponent &OC = CompPtr[i];
1833 if (OC.isBrackets) {
1834 // Offset of an array sub-field. TODO: Should we allow vector elements?
1835 const ArrayType *AT = Res->getType()->getAsArrayType();
1836 if (!AT) {
1837 delete Res;
1838 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1839 Res->getType().getAsString());
1840 }
1841
Chris Lattner2af6a802007-08-30 17:59:59 +00001842 // FIXME: C++: Verify that operator[] isn't overloaded.
1843
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001844 // C99 6.5.2.1p1
1845 Expr *Idx = static_cast<Expr*>(OC.U.E);
1846 if (!Idx->getType()->isIntegerType())
1847 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1848 Idx->getSourceRange());
1849
1850 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1851 continue;
1852 }
1853
1854 const RecordType *RC = Res->getType()->getAsRecordType();
1855 if (!RC) {
1856 delete Res;
1857 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1858 Res->getType().getAsString());
1859 }
1860
1861 // Get the decl corresponding to this.
1862 RecordDecl *RD = RC->getDecl();
1863 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1864 if (!MemberDecl)
1865 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1866 OC.U.IdentInfo->getName(),
1867 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00001868
1869 // FIXME: C++: Verify that MemberDecl isn't a static field.
1870 // FIXME: Verify that MemberDecl isn't a bitfield.
1871
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001872 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1873 }
1874
1875 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1876 BuiltinLoc);
1877}
1878
1879
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001880Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001881 TypeTy *arg1, TypeTy *arg2,
1882 SourceLocation RPLoc) {
1883 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1884 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1885
1886 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1887
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001888 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001889}
1890
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001891Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00001892 ExprTy *expr1, ExprTy *expr2,
1893 SourceLocation RPLoc) {
1894 Expr *CondExpr = static_cast<Expr*>(cond);
1895 Expr *LHSExpr = static_cast<Expr*>(expr1);
1896 Expr *RHSExpr = static_cast<Expr*>(expr2);
1897
1898 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1899
1900 // The conditional expression is required to be a constant expression.
1901 llvm::APSInt condEval(32);
1902 SourceLocation ExpLoc;
1903 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1904 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1905 CondExpr->getSourceRange());
1906
1907 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1908 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1909 RHSExpr->getType();
1910 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1911}
1912
Anders Carlsson36760332007-10-15 20:28:48 +00001913Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
1914 ExprTy *expr, TypeTy *type,
1915 SourceLocation RPLoc)
1916{
1917 Expr *E = static_cast<Expr*>(expr);
1918 QualType T = QualType::getFromOpaquePtr(type);
1919
1920 InitBuiltinVaListType();
1921
1922 Sema::AssignmentCheckResult result;
1923
1924 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
1925 E->getType());
1926 if (result != Compatible)
1927 return Diag(E->getLocStart(),
1928 diag::err_first_argument_to_va_arg_not_of_type_va_list,
1929 E->getType().getAsString(),
1930 E->getSourceRange());
1931
1932 // FIXME: Warn if a non-POD type is passed in.
1933
1934 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
1935}
1936
Anders Carlssona66cad42007-08-21 17:43:55 +00001937// TODO: Move this to SemaObjC.cpp
Steve Naroff0add5d22007-11-03 11:27:19 +00001938Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation AtLoc,
1939 ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00001940 StringLiteral* S = static_cast<StringLiteral *>(string);
1941
1942 if (CheckBuiltinCFStringArgument(S))
1943 return true;
1944
Steve Narofff2e30312007-10-15 23:35:17 +00001945 if (Context.getObjcConstantStringInterface().isNull()) {
1946 // Initialize the constant string interface lazily. This assumes
1947 // the NSConstantString interface is seen in this translation unit.
1948 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
1949 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
1950 SourceLocation(), TUScope);
Steve Naroff134c3502007-10-16 00:00:18 +00001951 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff96f136d2007-10-18 23:53:51 +00001952 if (!strIFace)
1953 return Diag(S->getLocStart(), diag::err_undef_interface,
1954 NSIdent->getName());
Steve Naroff134c3502007-10-16 00:00:18 +00001955 Context.setObjcConstantStringInterface(strIFace);
Steve Narofff2e30312007-10-15 23:35:17 +00001956 }
1957 QualType t = Context.getObjcConstantStringInterface();
Anders Carlssona66cad42007-08-21 17:43:55 +00001958 t = Context.getPointerType(t);
Steve Naroff0add5d22007-11-03 11:27:19 +00001959 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlssona66cad42007-08-21 17:43:55 +00001960}
Anders Carlsson8be1d402007-08-22 15:14:15 +00001961
1962Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattnercfd61c82007-10-16 22:51:17 +00001963 SourceLocation EncodeLoc,
Anders Carlsson8be1d402007-08-22 15:14:15 +00001964 SourceLocation LParenLoc,
1965 TypeTy *Ty,
1966 SourceLocation RParenLoc) {
1967 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
1968
1969 QualType t = Context.getPointerType(Context.CharTy);
1970 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
1971}
Steve Naroffd3f5ee42007-09-17 21:01:15 +00001972
Fariborz Jahanianf807c202007-10-16 20:40:23 +00001973Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1974 SourceLocation AtLoc,
Fariborz Jahanian957448a2007-10-16 23:21:02 +00001975 SourceLocation SelLoc,
Fariborz Jahanianf807c202007-10-16 20:40:23 +00001976 SourceLocation LParenLoc,
1977 SourceLocation RParenLoc) {
Steve Naroffae84af82007-10-31 18:42:27 +00001978 QualType t = Context.getObjcSelType();
Fariborz Jahanianf807c202007-10-16 20:40:23 +00001979 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
1980}
1981
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00001982Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1983 SourceLocation AtLoc,
1984 SourceLocation ProtoLoc,
1985 SourceLocation LParenLoc,
1986 SourceLocation RParenLoc) {
1987 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
1988 if (!PDecl) {
1989 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
1990 return true;
1991 }
1992
1993 QualType t = GetObjcProtoType(AtLoc);
Fariborz Jahanian20b40e42007-10-18 22:59:23 +00001994 if (t.isNull())
1995 return true;
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00001996 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
1997}
Steve Naroff52664182007-10-16 23:12:48 +00001998
1999bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2000 ObjcMethodDecl *Method) {
2001 bool anyIncompatibleArgs = false;
2002
2003 for (unsigned i = 0; i < NumArgs; i++) {
2004 Expr *argExpr = Args[i];
2005 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2006
2007 QualType lhsType = Method->getParamDecl(i)->getType();
2008 QualType rhsType = argExpr->getType();
2009
2010 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2011 if (const ArrayType *ary = lhsType->getAsArrayType())
2012 lhsType = Context.getPointerType(ary->getElementType());
2013 else if (lhsType->isFunctionType())
2014 lhsType = Context.getPointerType(lhsType);
2015
2016 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2017 argExpr);
2018 if (Args[i] != argExpr) // The expression was converted.
2019 Args[i] = argExpr; // Make sure we store the converted expression.
2020 SourceLocation l = argExpr->getLocStart();
2021
2022 // decode the result (notice that AST's are still created for extensions).
2023 switch (result) {
2024 case Compatible:
2025 break;
2026 case PointerFromInt:
2027 // check for null pointer constant (C99 6.3.2.3p3)
2028 if (!argExpr->isNullPointerConstant(Context)) {
2029 Diag(l, diag::ext_typecheck_sending_pointer_int,
2030 lhsType.getAsString(), rhsType.getAsString(),
2031 argExpr->getSourceRange());
2032 }
2033 break;
2034 case IntFromPointer:
2035 Diag(l, diag::ext_typecheck_sending_pointer_int,
2036 lhsType.getAsString(), rhsType.getAsString(),
2037 argExpr->getSourceRange());
2038 break;
2039 case IncompatiblePointer:
2040 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2041 rhsType.getAsString(), lhsType.getAsString(),
2042 argExpr->getSourceRange());
2043 break;
2044 case CompatiblePointerDiscardsQualifiers:
2045 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2046 rhsType.getAsString(), lhsType.getAsString(),
2047 argExpr->getSourceRange());
2048 break;
2049 case Incompatible:
2050 Diag(l, diag::err_typecheck_sending_incompatible,
2051 rhsType.getAsString(), lhsType.getAsString(),
2052 argExpr->getSourceRange());
2053 anyIncompatibleArgs = true;
2054 }
2055 }
2056 return anyIncompatibleArgs;
2057}
2058
Steve Naroff4ed9d662007-09-27 14:38:14 +00002059// ActOnClassMessage - used for both unary and keyword messages.
2060// ArgExprs is optional - if it is present, the number of expressions
2061// is obtained from Sel.getNumArgs().
2062Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002063 Scope *S,
Steve Narofffa465d12007-10-02 20:01:56 +00002064 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff4ed9d662007-09-27 14:38:14 +00002065 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args)
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002066{
Steve Narofffa465d12007-10-02 20:01:56 +00002067 assert(receiverName && "missing receiver class name");
Steve Naroffc39ca262007-09-18 23:55:05 +00002068
Steve Naroff52664182007-10-16 23:12:48 +00002069 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002070 ObjcInterfaceDecl* ClassDecl = 0;
2071 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2072 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahanian342f3602007-11-12 20:20:37 +00002073 if (ClassDecl && CurMethodDecl->isInstance()) {
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002074 IdentifierInfo &II = Context.Idents.get("self");
2075 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II,
2076 false);
2077 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2078 superTy = Context.getPointerType(superTy);
2079 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2080 SourceLocation(), ReceiverExpr.Val);
2081
2082 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
2083 Args);
2084 }
2085 // class method
2086 if (ClassDecl)
2087 receiverName = ClassDecl->getIdentifier();
2088 }
2089 else
2090 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Narofffa465d12007-10-02 20:01:56 +00002091 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002092 QualType returnType;
Steve Naroff75c4baf2007-11-05 15:27:52 +00002093
2094 // Before we give up, check if the selector is an instance method.
2095 if (!Method)
2096 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002097 if (!Method) {
2098 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2099 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002100 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002101 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002102 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002103 if (Sel.getNumArgs()) {
2104 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2105 return true;
2106 }
Steve Naroff7e461452007-10-16 20:39:36 +00002107 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002108 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
2109 lbrac, rbrac, ArgExprs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002110}
2111
Steve Naroff4ed9d662007-09-27 14:38:14 +00002112// ActOnInstanceMessage - used for both unary and keyword messages.
2113// ArgExprs is optional - if it is present, the number of expressions
2114// is obtained from Sel.getNumArgs().
2115Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroff6cb1d362007-09-28 22:22:11 +00002116 ExprTy *receiver, Selector Sel,
Steve Naroff4ed9d662007-09-27 14:38:14 +00002117 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args)
2118{
Steve Naroffc39ca262007-09-18 23:55:05 +00002119 assert(receiver && "missing receiver expression");
2120
Steve Naroff52664182007-10-16 23:12:48 +00002121 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroffc39ca262007-09-18 23:55:05 +00002122 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Narofffa465d12007-10-02 20:01:56 +00002123 QualType receiverType = RExpr->getType();
Steve Naroffee1de132007-10-10 21:53:07 +00002124 QualType returnType;
Steve Naroff1e1c3912007-11-03 16:37:59 +00002125 ObjcMethodDecl *Method;
Steve Naroffee1de132007-10-10 21:53:07 +00002126
Steve Naroff0091d142007-11-11 17:52:25 +00002127 if (receiverType == Context.getObjcIdType() ||
2128 receiverType == Context.getObjcClassType()) {
Steve Naroff1e1c3912007-11-03 16:37:59 +00002129 Method = InstanceMethodPool[Sel].Method;
Steve Naroff7e461452007-10-16 20:39:36 +00002130 if (!Method) {
2131 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2132 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002133 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002134 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002135 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002136 if (Sel.getNumArgs())
2137 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2138 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002139 }
Steve Naroffee1de132007-10-10 21:53:07 +00002140 } else {
Chris Lattner71c01112007-10-10 23:42:28 +00002141 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2142 // revisited. how do we get the ClassDecl from the receiver expression?
Steve Naroffee1de132007-10-10 21:53:07 +00002143 while (receiverType->isPointerType()) {
Chris Lattner71c01112007-10-10 23:42:28 +00002144 PointerType *pointerType =
2145 static_cast<PointerType*>(receiverType.getTypePtr());
Steve Naroffee1de132007-10-10 21:53:07 +00002146 receiverType = pointerType->getPointeeType();
2147 }
Chris Lattner71c01112007-10-10 23:42:28 +00002148 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2149 "bad receiver type");
Steve Naroffee1de132007-10-10 21:53:07 +00002150 ObjcInterfaceDecl* ClassDecl = static_cast<ObjcInterfaceType*>(
2151 receiverType.getTypePtr())->getDecl();
Steve Naroff7e461452007-10-16 20:39:36 +00002152 // FIXME: consider using InstanceMethodPool, since it will be faster
2153 // than the following method (which can do *many* linear searches). The
2154 // idea is to add class info to InstanceMethodPool...
Steve Naroff1e1c3912007-11-03 16:37:59 +00002155 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002156 if (!Method) {
Steve Naroffb1c7ad92007-11-11 00:10:47 +00002157 // If we have an implementation in scope, check "private" methods.
2158 if (ObjcImplementationDecl *ImpDecl =
2159 ObjcImplementations[ClassDecl->getIdentifier()])
2160 Method = ImpDecl->lookupInstanceMethod(Sel);
2161 }
2162 if (!Method) {
Steve Naroff7e461452007-10-16 20:39:36 +00002163 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2164 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002165 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002166 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002167 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002168 if (Sel.getNumArgs())
2169 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2170 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002171 }
Steve Narofffa465d12007-10-02 20:01:56 +00002172 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002173 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
2174 ArgExprs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002175}