blob: dcec7253eac0475946023b8f1f43cd3fc23f6c79 [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"
Ted Kremenek30c66752007-11-25 00:58:00 +000015#include "SemaUtil.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
Steve Narofffa465d12007-10-02 20:01:56 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/AST/Expr.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000020#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Lex/Preprocessor.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Basic/SourceManager.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/TargetInfo.h"
27#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000028#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029using namespace clang;
30
Steve Naroff87d58b42007-09-16 03:34:24 +000031/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000032/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
33/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
34/// multiple tokens. However, the common case is that StringToks points to one
35/// string.
36///
37Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000038Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000039 assert(NumStringToks && "Must have at least one string!");
40
41 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
42 if (Literal.hadError)
43 return ExprResult(true);
44
45 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
46 for (unsigned i = 0; i != NumStringToks; ++i)
47 StringTokLocs.push_back(StringToks[i].getLocation());
48
49 // FIXME: handle wchar_t
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000050 QualType t;
51
52 if (Literal.Pascal)
53 t = Context.getPointerType(Context.UnsignedCharTy);
54 else
55 t = Context.getPointerType(Context.CharTy);
56
57 if (Literal.Pascal && Literal.GetStringLength() > 256)
58 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
59 SourceRange(StringToks[0].getLocation(),
60 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000061
62 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
63 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000064 Literal.AnyWide, t,
65 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000066 StringToks[NumStringToks-1].getLocation());
67}
68
69
Steve Naroff0acc9c92007-09-15 18:49:24 +000070/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000071/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
72/// identifier is used in an function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000073Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000074 IdentifierInfo &II,
75 bool HasTrailingLParen) {
76 // Could be enum-constant or decl.
Steve Narofff0c31dd2007-09-16 16:16:00 +000077 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Chris Lattner4b009652007-07-25 00:24:17 +000078 if (D == 0) {
79 // Otherwise, this could be an implicitly declared function reference (legal
80 // in C90, extension in C99).
81 if (HasTrailingLParen &&
82 // Not in C++.
83 !getLangOptions().CPlusPlus)
84 D = ImplicitlyDefineFunction(Loc, II, S);
85 else {
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000086 if (CurMethodDecl) {
87 ObjcInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
88 ObjcInterfaceDecl *clsDeclared;
Steve Naroff6b759ce2007-11-15 02:58:25 +000089 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
90 IdentifierInfo &II = Context.Idents.get("self");
91 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
92 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
93 static_cast<Expr*>(SelfExpr.Val), true, true);
94 }
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000095 }
Chris Lattner4b009652007-07-25 00:24:17 +000096 // If this name wasn't predeclared and if this is not a function call,
97 // diagnose the problem.
98 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
99 }
100 }
Steve Naroff91b03f72007-08-28 03:03:08 +0000101 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroffcae537d2007-08-28 18:45:29 +0000102 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000103 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000104 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000105 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000106 }
Chris Lattner4b009652007-07-25 00:24:17 +0000107 if (isa<TypedefDecl>(D))
108 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
109
110 assert(0 && "Invalid decl");
111 abort();
112}
113
Steve Naroff87d58b42007-09-16 03:34:24 +0000114Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000115 tok::TokenKind Kind) {
116 PreDefinedExpr::IdentType IT;
117
118 switch (Kind) {
119 default:
120 assert(0 && "Unknown simple primary expr!");
121 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
122 IT = PreDefinedExpr::Func;
123 break;
124 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
125 IT = PreDefinedExpr::Function;
126 break;
127 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
128 IT = PreDefinedExpr::PrettyFunction;
129 break;
130 }
131
132 // Pre-defined identifiers are always of type char *.
133 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
134}
135
Steve Naroff87d58b42007-09-16 03:34:24 +0000136Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000137 llvm::SmallString<16> CharBuffer;
138 CharBuffer.resize(Tok.getLength());
139 const char *ThisTokBegin = &CharBuffer[0];
140 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
141
142 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
143 Tok.getLocation(), PP);
144 if (Literal.hadError())
145 return ExprResult(true);
146 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
147 Tok.getLocation());
148}
149
Steve Naroff87d58b42007-09-16 03:34:24 +0000150Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000151 // fast path for a single digit (which is quite common). A single digit
152 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
153 if (Tok.getLength() == 1) {
154 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
155
Chris Lattner3496d522007-09-04 02:45:27 +0000156 unsigned IntSize = static_cast<unsigned>(
157 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000158 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
159 Context.IntTy,
160 Tok.getLocation()));
161 }
162 llvm::SmallString<512> IntegerBuffer;
163 IntegerBuffer.resize(Tok.getLength());
164 const char *ThisTokBegin = &IntegerBuffer[0];
165
166 // Get the spelling of the token, which eliminates trigraphs, etc.
167 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
168 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
169 Tok.getLocation(), PP);
170 if (Literal.hadError)
171 return ExprResult(true);
172
Chris Lattner1de66eb2007-08-26 03:42:43 +0000173 Expr *Res;
174
175 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000176 QualType Ty;
177 const llvm::fltSemantics *Format;
178 uint64_t Size; unsigned Align;
179
180 if (Literal.isFloat) {
181 Ty = Context.FloatTy;
182 Context.Target.getFloatInfo(Size, Align, Format, Tok.getLocation());
183 } else if (Literal.isLong) {
184 Ty = Context.LongDoubleTy;
185 Context.Target.getLongDoubleInfo(Size, Align, Format, Tok.getLocation());
186 } else {
187 Ty = Context.DoubleTy;
188 Context.Target.getDoubleInfo(Size, Align, Format, Tok.getLocation());
189 }
190
191 Res = new FloatingLiteral(Literal.GetFloatValue(*Format), Ty,
192 Tok.getLocation());
Chris Lattner1de66eb2007-08-26 03:42:43 +0000193 } else if (!Literal.isIntegerLiteral()) {
194 return ExprResult(true);
195 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000196 QualType t;
197
Neil Booth7421e9c2007-08-29 22:00:19 +0000198 // long long is a C99 feature.
199 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000200 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000201 Diag(Tok.getLocation(), diag::ext_longlong);
202
Chris Lattner4b009652007-07-25 00:24:17 +0000203 // Get the value in the widest-possible width.
204 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
205
206 if (Literal.GetIntegerValue(ResultVal)) {
207 // If this value didn't fit into uintmax_t, warn and force to ull.
208 Diag(Tok.getLocation(), diag::warn_integer_too_large);
209 t = Context.UnsignedLongLongTy;
210 assert(Context.getTypeSize(t, Tok.getLocation()) ==
211 ResultVal.getBitWidth() && "long long is not intmax_t?");
212 } else {
213 // If this value fits into a ULL, try to figure out what else it fits into
214 // according to the rules of C99 6.4.4.1p5.
215
216 // Octal, Hexadecimal, and integers with a U suffix are allowed to
217 // be an unsigned int.
218 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
219
220 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000221 if (!Literal.isLong && !Literal.isLongLong) {
222 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000223 unsigned IntSize = static_cast<unsigned>(
224 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000225 // Does it fit in a unsigned int?
226 if (ResultVal.isIntN(IntSize)) {
227 // Does it fit in a signed int?
228 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
229 t = Context.IntTy;
230 else if (AllowUnsigned)
231 t = Context.UnsignedIntTy;
232 }
233
234 if (!t.isNull())
235 ResultVal.trunc(IntSize);
236 }
237
238 // Are long/unsigned long possibilities?
239 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000240 unsigned LongSize = static_cast<unsigned>(
241 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000242
243 // Does it fit in a unsigned long?
244 if (ResultVal.isIntN(LongSize)) {
245 // Does it fit in a signed long?
246 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
247 t = Context.LongTy;
248 else if (AllowUnsigned)
249 t = Context.UnsignedLongTy;
250 }
251 if (!t.isNull())
252 ResultVal.trunc(LongSize);
253 }
254
255 // Finally, check long long if needed.
256 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000257 unsigned LongLongSize = static_cast<unsigned>(
258 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000259
260 // Does it fit in a unsigned long long?
261 if (ResultVal.isIntN(LongLongSize)) {
262 // Does it fit in a signed long long?
263 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
264 t = Context.LongLongTy;
265 else if (AllowUnsigned)
266 t = Context.UnsignedLongLongTy;
267 }
268 }
269
270 // If we still couldn't decide a type, we probably have something that
271 // does not fit in a signed long long, but has no U suffix.
272 if (t.isNull()) {
273 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
274 t = Context.UnsignedLongLongTy;
275 }
276 }
277
Chris Lattner1de66eb2007-08-26 03:42:43 +0000278 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000279 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000280
281 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
282 if (Literal.isImaginary)
283 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
284
285 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000286}
287
Steve Naroff87d58b42007-09-16 03:34:24 +0000288Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000289 ExprTy *Val) {
290 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000291 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000292 return new ParenExpr(L, R, e);
293}
294
295/// The UsualUnaryConversions() function is *not* called by this routine.
296/// See C99 6.3.2.1p[2-4] for more details.
297QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
298 SourceLocation OpLoc, bool isSizeof) {
299 // C99 6.5.3.4p1:
300 if (isa<FunctionType>(exprType) && isSizeof)
301 // alignof(function) is allowed.
302 Diag(OpLoc, diag::ext_sizeof_function_type);
303 else if (exprType->isVoidType())
304 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
305 else if (exprType->isIncompleteType()) {
306 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
307 diag::err_alignof_incomplete_type,
308 exprType.getAsString());
309 return QualType(); // error
310 }
311 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
312 return Context.getSizeType();
313}
314
315Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000316ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000317 SourceLocation LPLoc, TypeTy *Ty,
318 SourceLocation RPLoc) {
319 // If error parsing type, ignore.
320 if (Ty == 0) return true;
321
322 // Verify that this is a valid expression.
323 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
324
325 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
326
327 if (resultType.isNull())
328 return true;
329 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
330}
331
Chris Lattner5110ad52007-08-24 21:41:10 +0000332QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000333 DefaultFunctionArrayConversion(V);
334
Chris Lattnera16e42d2007-08-26 05:39:26 +0000335 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000336 if (const ComplexType *CT = V->getType()->getAsComplexType())
337 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000338
339 // Otherwise they pass through real integer and floating point types here.
340 if (V->getType()->isArithmeticType())
341 return V->getType();
342
343 // Reject anything else.
344 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
345 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000346}
347
348
Chris Lattner4b009652007-07-25 00:24:17 +0000349
Steve Naroff87d58b42007-09-16 03:34:24 +0000350Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000351 tok::TokenKind Kind,
352 ExprTy *Input) {
353 UnaryOperator::Opcode Opc;
354 switch (Kind) {
355 default: assert(0 && "Unknown unary op!");
356 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
357 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
358 }
359 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
360 if (result.isNull())
361 return true;
362 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
363}
364
365Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000366ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000367 ExprTy *Idx, SourceLocation RLoc) {
368 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
369
370 // Perform default conversions.
371 DefaultFunctionArrayConversion(LHSExp);
372 DefaultFunctionArrayConversion(RHSExp);
373
374 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
375
376 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000377 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000378 // in the subscript position. As a result, we need to derive the array base
379 // and index from the expression types.
380 Expr *BaseExpr, *IndexExpr;
381 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000382 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000383 BaseExpr = LHSExp;
384 IndexExpr = RHSExp;
385 // FIXME: need to deal with const...
386 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000387 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000388 // Handle the uncommon case of "123[Ptr]".
389 BaseExpr = RHSExp;
390 IndexExpr = LHSExp;
391 // FIXME: need to deal with const...
392 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000393 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
394 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000395 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000396
397 // Component access limited to variables (reject vec4.rg[1]).
398 if (!isa<DeclRefExpr>(BaseExpr))
399 return Diag(LLoc, diag::err_ocuvector_component_access,
400 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000401 // FIXME: need to deal with const...
402 ResultType = VTy->getElementType();
403 } else {
404 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
405 RHSExp->getSourceRange());
406 }
407 // C99 6.5.2.1p1
408 if (!IndexExpr->getType()->isIntegerType())
409 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
410 IndexExpr->getSourceRange());
411
412 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
413 // the following check catches trying to index a pointer to a function (e.g.
414 // void (*)(int)). Functions are not objects in C99.
415 if (!ResultType->isObjectType())
416 return Diag(BaseExpr->getLocStart(),
417 diag::err_typecheck_subscript_not_object,
418 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
419
420 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
421}
422
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000423QualType Sema::
424CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
425 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000426 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000427
428 // The vector accessor can't exceed the number of elements.
429 const char *compStr = CompName.getName();
430 if (strlen(compStr) > vecType->getNumElements()) {
431 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
432 baseType.getAsString(), SourceRange(CompLoc));
433 return QualType();
434 }
435 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000436 if (vecType->getPointAccessorIdx(*compStr) != -1) {
437 do
438 compStr++;
439 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
440 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
441 do
442 compStr++;
443 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
444 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
445 do
446 compStr++;
447 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
448 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000449
450 if (*compStr) {
451 // We didn't get to the end of the string. This means the component names
452 // didn't come from the same set *or* we encountered an illegal name.
453 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
454 std::string(compStr,compStr+1), SourceRange(CompLoc));
455 return QualType();
456 }
457 // Each component accessor can't exceed the vector type.
458 compStr = CompName.getName();
459 while (*compStr) {
460 if (vecType->isAccessorWithinNumElements(*compStr))
461 compStr++;
462 else
463 break;
464 }
465 if (*compStr) {
466 // We didn't get to the end of the string. This means a component accessor
467 // exceeds the number of elements in the vector.
468 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
469 baseType.getAsString(), SourceRange(CompLoc));
470 return QualType();
471 }
472 // The component accessor looks fine - now we need to compute the actual type.
473 // The vector type is implied by the component accessor. For example,
474 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
475 unsigned CompSize = strlen(CompName.getName());
476 if (CompSize == 1)
477 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000478
479 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
480 // Now look up the TypeDefDecl from the vector type. Without this,
481 // diagostics look bad. We want OCU vector types to appear built-in.
482 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
483 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
484 return Context.getTypedefType(OCUVectorDecls[i]);
485 }
486 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000487}
488
Chris Lattner4b009652007-07-25 00:24:17 +0000489Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000490ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000491 tok::TokenKind OpKind, SourceLocation MemberLoc,
492 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000493 Expr *BaseExpr = static_cast<Expr *>(Base);
494 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000495
Steve Naroff2cb66382007-07-26 03:11:44 +0000496 QualType BaseType = BaseExpr->getType();
497 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000498
Chris Lattner4b009652007-07-25 00:24:17 +0000499 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000500 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000501 BaseType = PT->getPointeeType();
502 else
503 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
504 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000505 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000506 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000507 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000508 RecordDecl *RDecl = RTy->getDecl();
509 if (RTy->isIncompleteType())
510 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
511 BaseExpr->getSourceRange());
512 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000513 FieldDecl *MemberDecl = RDecl->getMember(&Member);
514 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000515 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
516 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000517 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
518 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000519 // Component access limited to variables (reject vec4.rg.g).
520 if (!isa<DeclRefExpr>(BaseExpr))
521 return Diag(OpLoc, diag::err_ocuvector_component_access,
522 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000523 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
524 if (ret.isNull())
525 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000526 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000527 } else if (BaseType->isObjcInterfaceType()) {
528 ObjcInterfaceDecl *IFace;
529 if (isa<ObjcInterfaceType>(BaseType.getCanonicalType()))
530 IFace = dyn_cast<ObjcInterfaceType>(BaseType)->getDecl();
531 else
532 IFace = dyn_cast<ObjcQualifiedInterfaceType>(BaseType)
533 ->getInterfaceType()->getDecl();
534 ObjcInterfaceDecl *clsDeclared;
535 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
536 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
537 OpKind==tok::arrow);
538 }
539 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
540 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000541}
542
Steve Naroff87d58b42007-09-16 03:34:24 +0000543/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000544/// This provides the location of the left/right parens and a list of comma
545/// locations.
546Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000547ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000548 ExprTy **args, unsigned NumArgsInCall,
549 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
550 Expr *Fn = static_cast<Expr *>(fn);
551 Expr **Args = reinterpret_cast<Expr**>(args);
552 assert(Fn && "no function call expression");
553
554 UsualUnaryConversions(Fn);
555 QualType funcType = Fn->getType();
556
557 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
558 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000559 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000560 if (PT == 0)
561 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
562 SourceRange(Fn->getLocStart(), RParenLoc));
563
Chris Lattner71225142007-07-31 21:27:01 +0000564 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000565 if (funcT == 0)
566 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
567 SourceRange(Fn->getLocStart(), RParenLoc));
568
569 // If a prototype isn't declared, the parser implicitly defines a func decl
570 QualType resultType = funcT->getResultType();
571
572 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
573 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
574 // assignment, to the types of the corresponding parameter, ...
575
576 unsigned NumArgsInProto = proto->getNumArgs();
577 unsigned NumArgsToCheck = NumArgsInCall;
578
579 if (NumArgsInCall < NumArgsInProto)
580 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
581 Fn->getSourceRange());
582 else if (NumArgsInCall > NumArgsInProto) {
583 if (!proto->isVariadic()) {
584 Diag(Args[NumArgsInProto]->getLocStart(),
585 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
586 SourceRange(Args[NumArgsInProto]->getLocStart(),
587 Args[NumArgsInCall-1]->getLocEnd()));
588 }
589 NumArgsToCheck = NumArgsInProto;
590 }
591 // Continue to check argument types (even if we have too few/many args).
592 for (unsigned i = 0; i < NumArgsToCheck; i++) {
593 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000594 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000595
596 QualType lhsType = proto->getArgType(i);
597 QualType rhsType = argExpr->getType();
598
Steve Naroff75644062007-07-25 20:45:33 +0000599 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000600 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000601 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000602 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000603 lhsType = Context.getPointerType(lhsType);
604
605 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
606 argExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000607 if (Args[i] != argExpr) // The expression was converted.
608 Args[i] = argExpr; // Make sure we store the converted expression.
Chris Lattner4b009652007-07-25 00:24:17 +0000609 SourceLocation l = argExpr->getLocStart();
610
611 // decode the result (notice that AST's are still created for extensions).
612 switch (result) {
613 case Compatible:
614 break;
615 case PointerFromInt:
616 // check for null pointer constant (C99 6.3.2.3p3)
617 if (!argExpr->isNullPointerConstant(Context)) {
618 Diag(l, diag::ext_typecheck_passing_pointer_int,
619 lhsType.getAsString(), rhsType.getAsString(),
620 Fn->getSourceRange(), argExpr->getSourceRange());
621 }
622 break;
623 case IntFromPointer:
624 Diag(l, diag::ext_typecheck_passing_pointer_int,
625 lhsType.getAsString(), rhsType.getAsString(),
626 Fn->getSourceRange(), argExpr->getSourceRange());
627 break;
628 case IncompatiblePointer:
629 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
630 rhsType.getAsString(), lhsType.getAsString(),
631 Fn->getSourceRange(), argExpr->getSourceRange());
632 break;
633 case CompatiblePointerDiscardsQualifiers:
634 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
635 rhsType.getAsString(), lhsType.getAsString(),
636 Fn->getSourceRange(), argExpr->getSourceRange());
637 break;
638 case Incompatible:
639 return Diag(l, diag::err_typecheck_passing_incompatible,
640 rhsType.getAsString(), lhsType.getAsString(),
641 Fn->getSourceRange(), argExpr->getSourceRange());
642 }
643 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000644 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
645 // Promote the arguments (C99 6.5.2.2p7).
646 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
647 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000648 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000649
650 DefaultArgumentPromotion(argExpr);
651 if (Args[i] != argExpr) // The expression was converted.
652 Args[i] = argExpr; // Make sure we store the converted expression.
653 }
654 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
655 // Even if the types checked, bail if the number of arguments don't match.
Chris Lattner4b009652007-07-25 00:24:17 +0000656 return true;
Steve Naroffdb65e052007-08-28 23:30:39 +0000657 }
658 } else if (isa<FunctionTypeNoProto>(funcT)) {
659 // Promote the arguments (C99 6.5.2.2p6).
660 for (unsigned i = 0; i < NumArgsInCall; i++) {
661 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000662 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000663
664 DefaultArgumentPromotion(argExpr);
665 if (Args[i] != argExpr) // The expression was converted.
666 Args[i] = argExpr; // Make sure we store the converted expression.
667 }
Chris Lattner4b009652007-07-25 00:24:17 +0000668 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000669 // Do special checking on direct calls to functions.
670 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
671 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
672 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000673 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
674 NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000675 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000676
Chris Lattner4b009652007-07-25 00:24:17 +0000677 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
678}
679
680Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000681ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000682 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000683 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000684 QualType literalType = QualType::getFromOpaquePtr(Ty);
685 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000686 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000687 Expr *literalExpr = static_cast<Expr*>(InitExpr);
688
689 // FIXME: add semantic analysis (C99 6.5.2.5).
690 return new CompoundLiteralExpr(literalType, literalExpr);
691}
692
693Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000694ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000695 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000696 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000697
Steve Naroff0acc9c92007-09-15 18:49:24 +0000698 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000699 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000700
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000701 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
702 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
703 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000704}
705
706Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000707ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000708 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000709 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000710
711 Expr *castExpr = static_cast<Expr*>(Op);
712 QualType castType = QualType::getFromOpaquePtr(Ty);
713
Steve Naroff68adb482007-08-31 00:32:44 +0000714 UsualUnaryConversions(castExpr);
715
Chris Lattner4b009652007-07-25 00:24:17 +0000716 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
717 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000718 if (!castType->isVoidType()) { // Cast to void allows any expr type.
719 if (!castType->isScalarType())
720 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
721 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
722 if (!castExpr->getType()->isScalarType()) {
723 return Diag(castExpr->getLocStart(),
724 diag::err_typecheck_expect_scalar_operand,
725 castExpr->getType().getAsString(),castExpr->getSourceRange());
726 }
Chris Lattner4b009652007-07-25 00:24:17 +0000727 }
728 return new CastExpr(castType, castExpr, LParenLoc);
729}
730
Steve Naroff144667e2007-10-18 05:13:08 +0000731// promoteExprToType - a helper function to ensure we create exactly one
732// ImplicitCastExpr.
733static void promoteExprToType(Expr *&expr, QualType type) {
734 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
735 impCast->setType(type);
736 else
737 expr = new ImplicitCastExpr(type, expr);
738 return;
739}
740
Chris Lattner98a425c2007-11-26 01:40:58 +0000741/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
742/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000743inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
744 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
745 UsualUnaryConversions(cond);
746 UsualUnaryConversions(lex);
747 UsualUnaryConversions(rex);
748 QualType condT = cond->getType();
749 QualType lexT = lex->getType();
750 QualType rexT = rex->getType();
751
752 // first, check the condition.
753 if (!condT->isScalarType()) { // C99 6.5.15p2
754 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
755 condT.getAsString());
756 return QualType();
757 }
758 // now check the two expressions.
759 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
760 UsualArithmeticConversions(lex, rex);
761 return lex->getType();
762 }
Chris Lattner71225142007-07-31 21:27:01 +0000763 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
764 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
Chris Lattner98a425c2007-11-26 01:40:58 +0000765 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner71225142007-07-31 21:27:01 +0000766 return lexT;
767
Chris Lattner4b009652007-07-25 00:24:17 +0000768 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
769 lexT.getAsString(), rexT.getAsString(),
770 lex->getSourceRange(), rex->getSourceRange());
771 return QualType();
772 }
773 }
774 // C99 6.5.15p3
Steve Naroff144667e2007-10-18 05:13:08 +0000775 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
776 promoteExprToType(rex, lexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000777 return lexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000778 }
779 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
780 promoteExprToType(lex, rexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000781 return rexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000782 }
Chris Lattner71225142007-07-31 21:27:01 +0000783 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
784 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
785 // get the "pointed to" types
786 QualType lhptee = LHSPT->getPointeeType();
787 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000788
Chris Lattner71225142007-07-31 21:27:01 +0000789 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
790 if (lhptee->isVoidType() &&
791 (rhptee->isObjectType() || rhptee->isIncompleteType()))
792 return lexT;
793 if (rhptee->isVoidType() &&
794 (lhptee->isObjectType() || lhptee->isIncompleteType()))
795 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000796
Steve Naroff85f0dc52007-10-15 20:41:53 +0000797 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
798 rhptee.getUnqualifiedType())) {
Chris Lattner71225142007-07-31 21:27:01 +0000799 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
800 lexT.getAsString(), rexT.getAsString(),
801 lex->getSourceRange(), rex->getSourceRange());
802 return lexT; // FIXME: this is an _ext - is this return o.k?
803 }
804 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000805 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
806 // differently qualified versions of compatible types, the result type is
807 // a pointer to an appropriately qualified version of the *composite*
808 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000809 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000810 }
Chris Lattner4b009652007-07-25 00:24:17 +0000811 }
Chris Lattner71225142007-07-31 21:27:01 +0000812
Chris Lattner4b009652007-07-25 00:24:17 +0000813 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
814 return lexT;
815
816 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
817 lexT.getAsString(), rexT.getAsString(),
818 lex->getSourceRange(), rex->getSourceRange());
819 return QualType();
820}
821
Steve Naroff87d58b42007-09-16 03:34:24 +0000822/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000823/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000824Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000825 SourceLocation ColonLoc,
826 ExprTy *Cond, ExprTy *LHS,
827 ExprTy *RHS) {
828 Expr *CondExpr = (Expr *) Cond;
829 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000830
831 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
832 // was the condition.
833 bool isLHSNull = LHSExpr == 0;
834 if (isLHSNull)
835 LHSExpr = CondExpr;
836
Chris Lattner4b009652007-07-25 00:24:17 +0000837 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
838 RHSExpr, QuestionLoc);
839 if (result.isNull())
840 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000841 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
842 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000843}
844
Steve Naroffdb65e052007-08-28 23:30:39 +0000845/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
846/// do not have a prototype. Integer promotions are performed on each
847/// argument, and arguments that have type float are promoted to double.
848void Sema::DefaultArgumentPromotion(Expr *&expr) {
849 QualType t = expr->getType();
850 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
851
852 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
853 promoteExprToType(expr, Context.IntTy);
854 if (t == Context.FloatTy)
855 promoteExprToType(expr, Context.DoubleTy);
856}
857
Chris Lattner4b009652007-07-25 00:24:17 +0000858/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
859void Sema::DefaultFunctionArrayConversion(Expr *&e) {
860 QualType t = e->getType();
861 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
862
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000863 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000864 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
865 t = e->getType();
866 }
867 if (t->isFunctionType())
868 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000869 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000870 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
871}
872
873/// UsualUnaryConversion - Performs various conversions that are common to most
874/// operators (C99 6.3). The conversions of array and function types are
875/// sometimes surpressed. For example, the array->pointer conversion doesn't
876/// apply if the array is an argument to the sizeof or address (&) operators.
877/// In these instances, this routine should *not* be called.
878void Sema::UsualUnaryConversions(Expr *&expr) {
879 QualType t = expr->getType();
880 assert(!t.isNull() && "UsualUnaryConversions - missing type");
881
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000882 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000883 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
884 t = expr->getType();
885 }
886 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
887 promoteExprToType(expr, Context.IntTy);
888 else
889 DefaultFunctionArrayConversion(expr);
890}
891
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000892/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000893/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
894/// routine returns the first non-arithmetic type found. The client is
895/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000896QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
897 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000898 if (!isCompAssign) {
899 UsualUnaryConversions(lhsExpr);
900 UsualUnaryConversions(rhsExpr);
901 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000902 // For conversion purposes, we ignore any qualifiers.
903 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000904 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
905 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000906
907 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000908 if (lhs == rhs)
909 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000910
911 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
912 // The caller can deal with this (e.g. pointer + int).
913 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000914 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000915
916 // At this point, we have two different arithmetic types.
917
918 // Handle complex types first (C99 6.3.1.8p1).
919 if (lhs->isComplexType() || rhs->isComplexType()) {
920 // if we have an integer operand, the result is the complex type.
921 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000922 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
923 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000924 }
925 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000926 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
927 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000928 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000929 // This handles complex/complex, complex/float, or float/complex.
930 // When both operands are complex, the shorter operand is converted to the
931 // type of the longer, and that is the type of the result. This corresponds
932 // to what is done when combining two real floating-point operands.
933 // The fun begins when size promotion occur across type domains.
934 // From H&S 6.3.4: When one operand is complex and the other is a real
935 // floating-point type, the less precise type is converted, within it's
936 // real or complex domain, to the precision of the other type. For example,
937 // when combining a "long double" with a "double _Complex", the
938 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000939 int result = Context.compareFloatingType(lhs, rhs);
940
941 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000942 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
943 if (!isCompAssign)
944 promoteExprToType(rhsExpr, rhs);
945 } else if (result < 0) { // The right side is bigger, convert lhs.
946 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
947 if (!isCompAssign)
948 promoteExprToType(lhsExpr, lhs);
949 }
950 // At this point, lhs and rhs have the same rank/size. Now, make sure the
951 // domains match. This is a requirement for our implementation, C99
952 // does not require this promotion.
953 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
954 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000955 if (!isCompAssign)
956 promoteExprToType(lhsExpr, rhs);
957 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000958 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000959 if (!isCompAssign)
960 promoteExprToType(rhsExpr, lhs);
961 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000962 }
Chris Lattner4b009652007-07-25 00:24:17 +0000963 }
Steve Naroff3b6157f2007-08-27 21:43:43 +0000964 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +0000965 }
966 // Now handle "real" floating types (i.e. float, double, long double).
967 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
968 // if we have an integer operand, the result is the real floating type.
969 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000970 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
971 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000972 }
973 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000974 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
975 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000976 }
977 // We have two real floating types, float/complex combos were handled above.
978 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +0000979 int result = Context.compareFloatingType(lhs, rhs);
980
981 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000982 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
983 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000984 }
Steve Naroff45fc9822007-08-27 15:30:22 +0000985 if (result < 0) { // convert the lhs
986 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
987 return rhs;
988 }
989 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +0000990 }
991 // Finally, we have two differing integer types.
992 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000993 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
994 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000995 }
Steve Naroff8f708362007-08-24 19:07:16 +0000996 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
997 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000998}
999
1000// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1001// being closely modeled after the C99 spec:-). The odd characteristic of this
1002// routine is it effectively iqnores the qualifiers on the top level pointee.
1003// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1004// FIXME: add a couple examples in this comment.
1005Sema::AssignmentCheckResult
1006Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1007 QualType lhptee, rhptee;
1008
1009 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001010 lhptee = lhsType->getAsPointerType()->getPointeeType();
1011 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001012
1013 // make sure we operate on the canonical type
1014 lhptee = lhptee.getCanonicalType();
1015 rhptee = rhptee.getCanonicalType();
1016
1017 AssignmentCheckResult r = Compatible;
1018
1019 // C99 6.5.16.1p1: This following citation is common to constraints
1020 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1021 // qualifiers of the type *pointed to* by the right;
1022 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1023 rhptee.getQualifiers())
1024 r = CompatiblePointerDiscardsQualifiers;
1025
1026 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1027 // incomplete type and the other is a pointer to a qualified or unqualified
1028 // version of void...
1029 if (lhptee.getUnqualifiedType()->isVoidType() &&
1030 (rhptee->isObjectType() || rhptee->isIncompleteType()))
1031 ;
1032 else if (rhptee.getUnqualifiedType()->isVoidType() &&
1033 (lhptee->isObjectType() || lhptee->isIncompleteType()))
1034 ;
1035 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1036 // unqualified versions of compatible types, ...
Steve Naroff85f0dc52007-10-15 20:41:53 +00001037 else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1038 rhptee.getUnqualifiedType()))
Chris Lattner4b009652007-07-25 00:24:17 +00001039 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1040 return r;
1041}
1042
1043/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1044/// has code to accommodate several GCC extensions when type checking
1045/// pointers. Here are some objectionable examples that GCC considers warnings:
1046///
1047/// int a, *pint;
1048/// short *pshort;
1049/// struct foo *pfoo;
1050///
1051/// pint = pshort; // warning: assignment from incompatible pointer type
1052/// a = pint; // warning: assignment makes integer from pointer without a cast
1053/// pint = a; // warning: assignment makes pointer from integer without a cast
1054/// pint = pfoo; // warning: assignment from incompatible pointer type
1055///
1056/// As a result, the code for dealing with pointers is more complex than the
1057/// C99 spec dictates.
1058/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1059///
1060Sema::AssignmentCheckResult
1061Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Steve Naroffeed76842007-11-13 00:31:42 +00001062 if (lhsType.getCanonicalType().getUnqualifiedType() ==
1063 rhsType.getCanonicalType().getUnqualifiedType())
Chris Lattnera703c2e2007-10-29 05:15:40 +00001064 return Compatible; // common case, fast path...
Chris Lattner4b009652007-07-25 00:24:17 +00001065
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001066 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001067 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001068 return Compatible;
1069 } else if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001070 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1071 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1072 return Incompatible;
1073 }
1074 return Compatible;
1075 } else if (lhsType->isPointerType()) {
1076 if (rhsType->isIntegerType())
1077 return PointerFromInt;
1078
1079 if (rhsType->isPointerType())
1080 return CheckPointerTypesForAssignment(lhsType, rhsType);
1081 } else if (rhsType->isPointerType()) {
1082 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1083 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1084 return IntFromPointer;
1085
1086 if (lhsType->isPointerType())
1087 return CheckPointerTypesForAssignment(lhsType, rhsType);
1088 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001089 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001090 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001091 }
1092 return Incompatible;
1093}
1094
1095Sema::AssignmentCheckResult
1096Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Chris Lattner5f505bf2007-10-16 02:55:40 +00001097 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001098 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001099 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001100 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001101 //
1102 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1103 // are better understood.
1104 if (!lhsType->isReferenceType())
1105 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001106
1107 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +00001108
Steve Naroff0f32f432007-08-24 22:33:52 +00001109 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1110
1111 // C99 6.5.16.1p2: The value of the right operand is converted to the
1112 // type of the assignment expression.
1113 if (rExpr->getType() != lhsType)
1114 promoteExprToType(rExpr, lhsType);
1115 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001116}
1117
1118Sema::AssignmentCheckResult
1119Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1120 return CheckAssignmentConstraints(lhsType, rhsType);
1121}
1122
1123inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1124 Diag(loc, diag::err_typecheck_invalid_operands,
1125 lex->getType().getAsString(), rex->getType().getAsString(),
1126 lex->getSourceRange(), rex->getSourceRange());
1127}
1128
1129inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1130 Expr *&rex) {
1131 QualType lhsType = lex->getType(), rhsType = rex->getType();
1132
1133 // make sure the vector types are identical.
1134 if (lhsType == rhsType)
1135 return lhsType;
1136 // You cannot convert between vector values of different size.
1137 Diag(loc, diag::err_typecheck_vector_not_convertable,
1138 lex->getType().getAsString(), rex->getType().getAsString(),
1139 lex->getSourceRange(), rex->getSourceRange());
1140 return QualType();
1141}
1142
1143inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001144 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001145{
1146 QualType lhsType = lex->getType(), rhsType = rex->getType();
1147
1148 if (lhsType->isVectorType() || rhsType->isVectorType())
1149 return CheckVectorOperands(loc, lex, rex);
1150
Steve Naroff8f708362007-08-24 19:07:16 +00001151 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001152
Chris Lattner4b009652007-07-25 00:24:17 +00001153 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001154 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001155 InvalidOperands(loc, lex, rex);
1156 return QualType();
1157}
1158
1159inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001160 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001161{
1162 QualType lhsType = lex->getType(), rhsType = rex->getType();
1163
Steve Naroff8f708362007-08-24 19:07:16 +00001164 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001165
Chris Lattner4b009652007-07-25 00:24:17 +00001166 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001167 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001168 InvalidOperands(loc, lex, rex);
1169 return QualType();
1170}
1171
1172inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001173 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001174{
1175 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1176 return CheckVectorOperands(loc, lex, rex);
1177
Steve Naroff8f708362007-08-24 19:07:16 +00001178 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001179
1180 // handle the common case first (both operands are arithmetic).
1181 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001182 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001183
1184 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1185 return lex->getType();
1186 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1187 return rex->getType();
1188 InvalidOperands(loc, lex, rex);
1189 return QualType();
1190}
1191
1192inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001193 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001194{
1195 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1196 return CheckVectorOperands(loc, lex, rex);
1197
Steve Naroff8f708362007-08-24 19:07:16 +00001198 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001199
1200 // handle the common case first (both operands are arithmetic).
1201 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001202 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001203
1204 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001205 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001206 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1207 return Context.getPointerDiffType();
1208 InvalidOperands(loc, lex, rex);
1209 return QualType();
1210}
1211
1212inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001213 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001214{
1215 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1216 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001217 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001218
1219 // handle the common case first (both operands are arithmetic).
1220 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001221 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001222 InvalidOperands(loc, lex, rex);
1223 return QualType();
1224}
1225
Chris Lattner254f3bc2007-08-26 01:18:55 +00001226inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1227 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001228{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001229 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001230 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1231 UsualArithmeticConversions(lex, rex);
1232 else {
1233 UsualUnaryConversions(lex);
1234 UsualUnaryConversions(rex);
1235 }
Chris Lattner4b009652007-07-25 00:24:17 +00001236 QualType lType = lex->getType();
1237 QualType rType = rex->getType();
1238
Ted Kremenek486509e2007-10-29 17:13:39 +00001239 // For non-floating point types, check for self-comparisons of the form
1240 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1241 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001242 if (!lType->isFloatingType()) {
1243 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1244 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1245 if (DRL->getDecl() == DRR->getDecl())
1246 Diag(loc, diag::warn_selfcomparison);
1247 }
1248
Chris Lattner254f3bc2007-08-26 01:18:55 +00001249 if (isRelational) {
1250 if (lType->isRealType() && rType->isRealType())
1251 return Context.IntTy;
1252 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001253 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001254 if (lType->isFloatingType()) {
1255 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001256 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001257 }
1258
Chris Lattner254f3bc2007-08-26 01:18:55 +00001259 if (lType->isArithmeticType() && rType->isArithmeticType())
1260 return Context.IntTy;
1261 }
Chris Lattner4b009652007-07-25 00:24:17 +00001262
Chris Lattner22be8422007-08-26 01:10:14 +00001263 bool LHSIsNull = lex->isNullPointerConstant(Context);
1264 bool RHSIsNull = rex->isNullPointerConstant(Context);
1265
Chris Lattner254f3bc2007-08-26 01:18:55 +00001266 // All of the following pointer related warnings are GCC extensions, except
1267 // when handling null pointer constants. One day, we can consider making them
1268 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001269 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff3b435622007-11-13 14:57:38 +00001270
1271 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1272 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1273 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroff85f0dc52007-10-15 20:41:53 +00001274 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1275 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001276 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1277 lType.getAsString(), rType.getAsString(),
1278 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001279 }
Chris Lattner22be8422007-08-26 01:10:14 +00001280 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001281 return Context.IntTy;
1282 }
1283 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001284 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001285 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1286 lType.getAsString(), rType.getAsString(),
1287 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001288 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001289 return Context.IntTy;
1290 }
1291 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001292 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001293 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1294 lType.getAsString(), rType.getAsString(),
1295 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001296 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001297 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001298 }
1299 InvalidOperands(loc, lex, rex);
1300 return QualType();
1301}
1302
Chris Lattner4b009652007-07-25 00:24:17 +00001303inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001304 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001305{
1306 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1307 return CheckVectorOperands(loc, lex, rex);
1308
Steve Naroff8f708362007-08-24 19:07:16 +00001309 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001310
1311 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001312 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001313 InvalidOperands(loc, lex, rex);
1314 return QualType();
1315}
1316
1317inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1318 Expr *&lex, Expr *&rex, SourceLocation loc)
1319{
1320 UsualUnaryConversions(lex);
1321 UsualUnaryConversions(rex);
1322
1323 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1324 return Context.IntTy;
1325 InvalidOperands(loc, lex, rex);
1326 return QualType();
1327}
1328
1329inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001330 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001331{
1332 QualType lhsType = lex->getType();
1333 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1334 bool hadError = false;
1335 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1336
1337 switch (mlval) { // C99 6.5.16p2
1338 case Expr::MLV_Valid:
1339 break;
1340 case Expr::MLV_ConstQualified:
1341 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1342 hadError = true;
1343 break;
1344 case Expr::MLV_ArrayType:
1345 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1346 lhsType.getAsString(), lex->getSourceRange());
1347 return QualType();
1348 case Expr::MLV_NotObjectType:
1349 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1350 lhsType.getAsString(), lex->getSourceRange());
1351 return QualType();
1352 case Expr::MLV_InvalidExpression:
1353 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1354 lex->getSourceRange());
1355 return QualType();
1356 case Expr::MLV_IncompleteType:
1357 case Expr::MLV_IncompleteVoidType:
1358 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1359 lhsType.getAsString(), lex->getSourceRange());
1360 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001361 case Expr::MLV_DuplicateVectorComponents:
1362 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1363 lex->getSourceRange());
1364 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001365 }
1366 AssignmentCheckResult result;
1367
1368 if (compoundType.isNull())
1369 result = CheckSingleAssignmentConstraints(lhsType, rex);
1370 else
1371 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001372
Chris Lattner4b009652007-07-25 00:24:17 +00001373 // decode the result (notice that extensions still return a type).
1374 switch (result) {
1375 case Compatible:
1376 break;
1377 case Incompatible:
1378 Diag(loc, diag::err_typecheck_assign_incompatible,
1379 lhsType.getAsString(), rhsType.getAsString(),
1380 lex->getSourceRange(), rex->getSourceRange());
1381 hadError = true;
1382 break;
1383 case PointerFromInt:
1384 // check for null pointer constant (C99 6.3.2.3p3)
1385 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1386 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1387 lhsType.getAsString(), rhsType.getAsString(),
1388 lex->getSourceRange(), rex->getSourceRange());
1389 }
1390 break;
1391 case IntFromPointer:
1392 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1393 lhsType.getAsString(), rhsType.getAsString(),
1394 lex->getSourceRange(), rex->getSourceRange());
1395 break;
1396 case IncompatiblePointer:
1397 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1398 lhsType.getAsString(), rhsType.getAsString(),
1399 lex->getSourceRange(), rex->getSourceRange());
1400 break;
1401 case CompatiblePointerDiscardsQualifiers:
1402 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1403 lhsType.getAsString(), rhsType.getAsString(),
1404 lex->getSourceRange(), rex->getSourceRange());
1405 break;
1406 }
1407 // C99 6.5.16p3: The type of an assignment expression is the type of the
1408 // left operand unless the left operand has qualified type, in which case
1409 // it is the unqualified version of the type of the left operand.
1410 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1411 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001412 // C++ 5.17p1: the type of the assignment expression is that of its left
1413 // oprdu.
Chris Lattner4b009652007-07-25 00:24:17 +00001414 return hadError ? QualType() : lhsType.getUnqualifiedType();
1415}
1416
1417inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1418 Expr *&lex, Expr *&rex, SourceLocation loc) {
1419 UsualUnaryConversions(rex);
1420 return rex->getType();
1421}
1422
1423/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1424/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1425QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1426 QualType resType = op->getType();
1427 assert(!resType.isNull() && "no type for increment/decrement expression");
1428
Steve Naroffd30e1932007-08-24 17:20:07 +00001429 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001430 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001431 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1432 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1433 resType.getAsString(), op->getSourceRange());
1434 return QualType();
1435 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001436 } else if (!resType->isRealType()) {
1437 if (resType->isComplexType())
1438 // C99 does not support ++/-- on complex types.
1439 Diag(OpLoc, diag::ext_integer_increment_complex,
1440 resType.getAsString(), op->getSourceRange());
1441 else {
1442 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1443 resType.getAsString(), op->getSourceRange());
1444 return QualType();
1445 }
Chris Lattner4b009652007-07-25 00:24:17 +00001446 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001447 // At this point, we know we have a real, complex or pointer type.
1448 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001449 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1450 if (mlval != Expr::MLV_Valid) {
1451 // FIXME: emit a more precise diagnostic...
1452 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1453 op->getSourceRange());
1454 return QualType();
1455 }
1456 return resType;
1457}
1458
1459/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1460/// This routine allows us to typecheck complex/recursive expressions
1461/// where the declaration is needed for type checking. Here are some
1462/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1463static Decl *getPrimaryDeclaration(Expr *e) {
1464 switch (e->getStmtClass()) {
1465 case Stmt::DeclRefExprClass:
1466 return cast<DeclRefExpr>(e)->getDecl();
1467 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001468 // Fields cannot be declared with a 'register' storage class.
1469 // &X->f is always ok, even if X is declared register.
1470 if (cast<MemberExpr>(e)->isArrow())
1471 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001472 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1473 case Stmt::ArraySubscriptExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001474 // &X[4] and &4[X] is invalid if X is invalid.
Chris Lattner4b009652007-07-25 00:24:17 +00001475 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +00001476 case Stmt::UnaryOperatorClass:
1477 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1478 case Stmt::ParenExprClass:
1479 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001480 case Stmt::ImplicitCastExprClass:
1481 // &X[4] when X is an array, has an implicit cast from array to pointer.
1482 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001483 default:
1484 return 0;
1485 }
1486}
1487
1488/// CheckAddressOfOperand - The operand of & must be either a function
1489/// designator or an lvalue designating an object. If it is an lvalue, the
1490/// object cannot be declared with storage class register or be a bit field.
1491/// Note: The usual conversions are *not* applied to the operand of the &
1492/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1493QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1494 Decl *dcl = getPrimaryDeclaration(op);
1495 Expr::isLvalueResult lval = op->isLvalue();
1496
1497 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001498 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1499 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001500 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1501 op->getSourceRange());
1502 return QualType();
1503 }
1504 } else if (dcl) {
1505 // We have an lvalue with a decl. Make sure the decl is not declared
1506 // with the register storage-class specifier.
1507 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1508 if (vd->getStorageClass() == VarDecl::Register) {
1509 Diag(OpLoc, diag::err_typecheck_address_of_register,
1510 op->getSourceRange());
1511 return QualType();
1512 }
1513 } else
1514 assert(0 && "Unknown/unexpected decl type");
1515
1516 // FIXME: add check for bitfields!
1517 }
1518 // If the operand has type "type", the result has type "pointer to type".
1519 return Context.getPointerType(op->getType());
1520}
1521
1522QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1523 UsualUnaryConversions(op);
1524 QualType qType = op->getType();
1525
Chris Lattner7931f4a2007-07-31 16:53:04 +00001526 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001527 QualType ptype = PT->getPointeeType();
1528 // C99 6.5.3.2p4. "if it points to an object,...".
1529 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1530 // GCC compat: special case 'void *' (treat as warning).
1531 if (ptype->isVoidType()) {
1532 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1533 qType.getAsString(), op->getSourceRange());
1534 } else {
1535 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1536 ptype.getAsString(), op->getSourceRange());
1537 return QualType();
1538 }
1539 }
1540 return ptype;
1541 }
1542 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1543 qType.getAsString(), op->getSourceRange());
1544 return QualType();
1545}
1546
1547static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1548 tok::TokenKind Kind) {
1549 BinaryOperator::Opcode Opc;
1550 switch (Kind) {
1551 default: assert(0 && "Unknown binop!");
1552 case tok::star: Opc = BinaryOperator::Mul; break;
1553 case tok::slash: Opc = BinaryOperator::Div; break;
1554 case tok::percent: Opc = BinaryOperator::Rem; break;
1555 case tok::plus: Opc = BinaryOperator::Add; break;
1556 case tok::minus: Opc = BinaryOperator::Sub; break;
1557 case tok::lessless: Opc = BinaryOperator::Shl; break;
1558 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1559 case tok::lessequal: Opc = BinaryOperator::LE; break;
1560 case tok::less: Opc = BinaryOperator::LT; break;
1561 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1562 case tok::greater: Opc = BinaryOperator::GT; break;
1563 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1564 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1565 case tok::amp: Opc = BinaryOperator::And; break;
1566 case tok::caret: Opc = BinaryOperator::Xor; break;
1567 case tok::pipe: Opc = BinaryOperator::Or; break;
1568 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1569 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1570 case tok::equal: Opc = BinaryOperator::Assign; break;
1571 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1572 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1573 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1574 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1575 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1576 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1577 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1578 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1579 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1580 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1581 case tok::comma: Opc = BinaryOperator::Comma; break;
1582 }
1583 return Opc;
1584}
1585
1586static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1587 tok::TokenKind Kind) {
1588 UnaryOperator::Opcode Opc;
1589 switch (Kind) {
1590 default: assert(0 && "Unknown unary op!");
1591 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1592 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1593 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1594 case tok::star: Opc = UnaryOperator::Deref; break;
1595 case tok::plus: Opc = UnaryOperator::Plus; break;
1596 case tok::minus: Opc = UnaryOperator::Minus; break;
1597 case tok::tilde: Opc = UnaryOperator::Not; break;
1598 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1599 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1600 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1601 case tok::kw___real: Opc = UnaryOperator::Real; break;
1602 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1603 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1604 }
1605 return Opc;
1606}
1607
1608// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001609Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001610 ExprTy *LHS, ExprTy *RHS) {
1611 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1612 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1613
Steve Naroff87d58b42007-09-16 03:34:24 +00001614 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1615 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001616
1617 QualType ResultTy; // Result type of the binary operator.
1618 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1619
1620 switch (Opc) {
1621 default:
1622 assert(0 && "Unknown binary expr!");
1623 case BinaryOperator::Assign:
1624 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1625 break;
1626 case BinaryOperator::Mul:
1627 case BinaryOperator::Div:
1628 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1629 break;
1630 case BinaryOperator::Rem:
1631 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1632 break;
1633 case BinaryOperator::Add:
1634 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1635 break;
1636 case BinaryOperator::Sub:
1637 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1638 break;
1639 case BinaryOperator::Shl:
1640 case BinaryOperator::Shr:
1641 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1642 break;
1643 case BinaryOperator::LE:
1644 case BinaryOperator::LT:
1645 case BinaryOperator::GE:
1646 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001647 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001648 break;
1649 case BinaryOperator::EQ:
1650 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001651 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001652 break;
1653 case BinaryOperator::And:
1654 case BinaryOperator::Xor:
1655 case BinaryOperator::Or:
1656 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1657 break;
1658 case BinaryOperator::LAnd:
1659 case BinaryOperator::LOr:
1660 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1661 break;
1662 case BinaryOperator::MulAssign:
1663 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001664 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001665 if (!CompTy.isNull())
1666 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1667 break;
1668 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001669 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001670 if (!CompTy.isNull())
1671 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1672 break;
1673 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001674 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001675 if (!CompTy.isNull())
1676 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1677 break;
1678 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001679 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001680 if (!CompTy.isNull())
1681 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1682 break;
1683 case BinaryOperator::ShlAssign:
1684 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001685 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001686 if (!CompTy.isNull())
1687 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1688 break;
1689 case BinaryOperator::AndAssign:
1690 case BinaryOperator::XorAssign:
1691 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001692 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001693 if (!CompTy.isNull())
1694 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1695 break;
1696 case BinaryOperator::Comma:
1697 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1698 break;
1699 }
1700 if (ResultTy.isNull())
1701 return true;
1702 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001703 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001704 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001705 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001706}
1707
1708// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001709Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001710 ExprTy *input) {
1711 Expr *Input = (Expr*)input;
1712 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1713 QualType resultType;
1714 switch (Opc) {
1715 default:
1716 assert(0 && "Unimplemented unary expr!");
1717 case UnaryOperator::PreInc:
1718 case UnaryOperator::PreDec:
1719 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1720 break;
1721 case UnaryOperator::AddrOf:
1722 resultType = CheckAddressOfOperand(Input, OpLoc);
1723 break;
1724 case UnaryOperator::Deref:
1725 resultType = CheckIndirectionOperand(Input, OpLoc);
1726 break;
1727 case UnaryOperator::Plus:
1728 case UnaryOperator::Minus:
1729 UsualUnaryConversions(Input);
1730 resultType = Input->getType();
1731 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1732 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1733 resultType.getAsString());
1734 break;
1735 case UnaryOperator::Not: // bitwise complement
1736 UsualUnaryConversions(Input);
1737 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001738 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1739 if (!resultType->isIntegerType()) {
1740 if (resultType->isComplexType())
1741 // C99 does not support '~' for complex conjugation.
1742 Diag(OpLoc, diag::ext_integer_complement_complex,
1743 resultType.getAsString());
1744 else
1745 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1746 resultType.getAsString());
1747 }
Chris Lattner4b009652007-07-25 00:24:17 +00001748 break;
1749 case UnaryOperator::LNot: // logical negation
1750 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1751 DefaultFunctionArrayConversion(Input);
1752 resultType = Input->getType();
1753 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1754 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1755 resultType.getAsString());
1756 // LNot always has type int. C99 6.5.3.3p5.
1757 resultType = Context.IntTy;
1758 break;
1759 case UnaryOperator::SizeOf:
1760 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1761 break;
1762 case UnaryOperator::AlignOf:
1763 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1764 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001765 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001766 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001767 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001768 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001769 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001770 resultType = Input->getType();
1771 break;
1772 }
1773 if (resultType.isNull())
1774 return true;
1775 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1776}
1777
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001778/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1779Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001780 SourceLocation LabLoc,
1781 IdentifierInfo *LabelII) {
1782 // Look up the record for this label identifier.
1783 LabelStmt *&LabelDecl = LabelMap[LabelII];
1784
1785 // If we haven't seen this label yet, create a forward reference.
1786 if (LabelDecl == 0)
1787 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1788
1789 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001790 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1791 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001792}
1793
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001794Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00001795 SourceLocation RPLoc) { // "({..})"
1796 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1797 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1798 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1799
1800 // FIXME: there are a variety of strange constraints to enforce here, for
1801 // example, it is not possible to goto into a stmt expression apparently.
1802 // More semantic analysis is needed.
1803
1804 // FIXME: the last statement in the compount stmt has its value used. We
1805 // should not warn about it being unused.
1806
1807 // If there are sub stmts in the compound stmt, take the type of the last one
1808 // as the type of the stmtexpr.
1809 QualType Ty = Context.VoidTy;
1810
1811 if (!Compound->body_empty())
1812 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1813 Ty = LastExpr->getType();
1814
1815 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1816}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001817
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001818Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001819 SourceLocation TypeLoc,
1820 TypeTy *argty,
1821 OffsetOfComponent *CompPtr,
1822 unsigned NumComponents,
1823 SourceLocation RPLoc) {
1824 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1825 assert(!ArgTy.isNull() && "Missing type argument!");
1826
1827 // We must have at least one component that refers to the type, and the first
1828 // one is known to be a field designator. Verify that the ArgTy represents
1829 // a struct/union/class.
1830 if (!ArgTy->isRecordType())
1831 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1832
1833 // Otherwise, create a compound literal expression as the base, and
1834 // iteratively process the offsetof designators.
1835 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1836
Chris Lattnerb37522e2007-08-31 21:49:13 +00001837 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1838 // GCC extension, diagnose them.
1839 if (NumComponents != 1)
1840 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1841 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1842
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001843 for (unsigned i = 0; i != NumComponents; ++i) {
1844 const OffsetOfComponent &OC = CompPtr[i];
1845 if (OC.isBrackets) {
1846 // Offset of an array sub-field. TODO: Should we allow vector elements?
1847 const ArrayType *AT = Res->getType()->getAsArrayType();
1848 if (!AT) {
1849 delete Res;
1850 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1851 Res->getType().getAsString());
1852 }
1853
Chris Lattner2af6a802007-08-30 17:59:59 +00001854 // FIXME: C++: Verify that operator[] isn't overloaded.
1855
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001856 // C99 6.5.2.1p1
1857 Expr *Idx = static_cast<Expr*>(OC.U.E);
1858 if (!Idx->getType()->isIntegerType())
1859 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1860 Idx->getSourceRange());
1861
1862 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1863 continue;
1864 }
1865
1866 const RecordType *RC = Res->getType()->getAsRecordType();
1867 if (!RC) {
1868 delete Res;
1869 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1870 Res->getType().getAsString());
1871 }
1872
1873 // Get the decl corresponding to this.
1874 RecordDecl *RD = RC->getDecl();
1875 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1876 if (!MemberDecl)
1877 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1878 OC.U.IdentInfo->getName(),
1879 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00001880
1881 // FIXME: C++: Verify that MemberDecl isn't a static field.
1882 // FIXME: Verify that MemberDecl isn't a bitfield.
1883
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001884 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1885 }
1886
1887 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1888 BuiltinLoc);
1889}
1890
1891
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001892Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001893 TypeTy *arg1, TypeTy *arg2,
1894 SourceLocation RPLoc) {
1895 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1896 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1897
1898 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1899
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001900 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001901}
1902
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001903Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00001904 ExprTy *expr1, ExprTy *expr2,
1905 SourceLocation RPLoc) {
1906 Expr *CondExpr = static_cast<Expr*>(cond);
1907 Expr *LHSExpr = static_cast<Expr*>(expr1);
1908 Expr *RHSExpr = static_cast<Expr*>(expr2);
1909
1910 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1911
1912 // The conditional expression is required to be a constant expression.
1913 llvm::APSInt condEval(32);
1914 SourceLocation ExpLoc;
1915 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1916 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1917 CondExpr->getSourceRange());
1918
1919 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1920 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1921 RHSExpr->getType();
1922 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1923}
1924
Anders Carlsson36760332007-10-15 20:28:48 +00001925Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
1926 ExprTy *expr, TypeTy *type,
1927 SourceLocation RPLoc)
1928{
1929 Expr *E = static_cast<Expr*>(expr);
1930 QualType T = QualType::getFromOpaquePtr(type);
1931
1932 InitBuiltinVaListType();
1933
1934 Sema::AssignmentCheckResult result;
1935
1936 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
1937 E->getType());
1938 if (result != Compatible)
1939 return Diag(E->getLocStart(),
1940 diag::err_first_argument_to_va_arg_not_of_type_va_list,
1941 E->getType().getAsString(),
1942 E->getSourceRange());
1943
1944 // FIXME: Warn if a non-POD type is passed in.
1945
1946 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
1947}
1948
Anders Carlssona66cad42007-08-21 17:43:55 +00001949// TODO: Move this to SemaObjC.cpp
Steve Naroff0add5d22007-11-03 11:27:19 +00001950Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation AtLoc,
1951 ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00001952 StringLiteral* S = static_cast<StringLiteral *>(string);
1953
1954 if (CheckBuiltinCFStringArgument(S))
1955 return true;
1956
Steve Narofff2e30312007-10-15 23:35:17 +00001957 if (Context.getObjcConstantStringInterface().isNull()) {
1958 // Initialize the constant string interface lazily. This assumes
1959 // the NSConstantString interface is seen in this translation unit.
1960 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
1961 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
1962 SourceLocation(), TUScope);
Steve Naroff134c3502007-10-16 00:00:18 +00001963 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff96f136d2007-10-18 23:53:51 +00001964 if (!strIFace)
1965 return Diag(S->getLocStart(), diag::err_undef_interface,
1966 NSIdent->getName());
Steve Naroff134c3502007-10-16 00:00:18 +00001967 Context.setObjcConstantStringInterface(strIFace);
Steve Narofff2e30312007-10-15 23:35:17 +00001968 }
1969 QualType t = Context.getObjcConstantStringInterface();
Anders Carlssona66cad42007-08-21 17:43:55 +00001970 t = Context.getPointerType(t);
Steve Naroff0add5d22007-11-03 11:27:19 +00001971 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlssona66cad42007-08-21 17:43:55 +00001972}
Anders Carlsson8be1d402007-08-22 15:14:15 +00001973
1974Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattnercfd61c82007-10-16 22:51:17 +00001975 SourceLocation EncodeLoc,
Anders Carlsson8be1d402007-08-22 15:14:15 +00001976 SourceLocation LParenLoc,
1977 TypeTy *Ty,
1978 SourceLocation RParenLoc) {
1979 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
1980
1981 QualType t = Context.getPointerType(Context.CharTy);
1982 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
1983}
Steve Naroffd3f5ee42007-09-17 21:01:15 +00001984
Fariborz Jahanianf807c202007-10-16 20:40:23 +00001985Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1986 SourceLocation AtLoc,
Fariborz Jahanian957448a2007-10-16 23:21:02 +00001987 SourceLocation SelLoc,
Fariborz Jahanianf807c202007-10-16 20:40:23 +00001988 SourceLocation LParenLoc,
1989 SourceLocation RParenLoc) {
Steve Naroffae84af82007-10-31 18:42:27 +00001990 QualType t = Context.getObjcSelType();
Fariborz Jahanianf807c202007-10-16 20:40:23 +00001991 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
1992}
1993
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00001994Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1995 SourceLocation AtLoc,
1996 SourceLocation ProtoLoc,
1997 SourceLocation LParenLoc,
1998 SourceLocation RParenLoc) {
1999 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
2000 if (!PDecl) {
2001 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
2002 return true;
2003 }
2004
2005 QualType t = GetObjcProtoType(AtLoc);
Fariborz Jahanian20b40e42007-10-18 22:59:23 +00002006 if (t.isNull())
2007 return true;
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002008 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
2009}
Steve Naroff52664182007-10-16 23:12:48 +00002010
2011bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2012 ObjcMethodDecl *Method) {
2013 bool anyIncompatibleArgs = false;
2014
2015 for (unsigned i = 0; i < NumArgs; i++) {
2016 Expr *argExpr = Args[i];
2017 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2018
2019 QualType lhsType = Method->getParamDecl(i)->getType();
2020 QualType rhsType = argExpr->getType();
2021
2022 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2023 if (const ArrayType *ary = lhsType->getAsArrayType())
2024 lhsType = Context.getPointerType(ary->getElementType());
2025 else if (lhsType->isFunctionType())
2026 lhsType = Context.getPointerType(lhsType);
2027
2028 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2029 argExpr);
2030 if (Args[i] != argExpr) // The expression was converted.
2031 Args[i] = argExpr; // Make sure we store the converted expression.
2032 SourceLocation l = argExpr->getLocStart();
2033
2034 // decode the result (notice that AST's are still created for extensions).
2035 switch (result) {
2036 case Compatible:
2037 break;
2038 case PointerFromInt:
2039 // check for null pointer constant (C99 6.3.2.3p3)
2040 if (!argExpr->isNullPointerConstant(Context)) {
2041 Diag(l, diag::ext_typecheck_sending_pointer_int,
2042 lhsType.getAsString(), rhsType.getAsString(),
2043 argExpr->getSourceRange());
2044 }
2045 break;
2046 case IntFromPointer:
2047 Diag(l, diag::ext_typecheck_sending_pointer_int,
2048 lhsType.getAsString(), rhsType.getAsString(),
2049 argExpr->getSourceRange());
2050 break;
2051 case IncompatiblePointer:
2052 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2053 rhsType.getAsString(), lhsType.getAsString(),
2054 argExpr->getSourceRange());
2055 break;
2056 case CompatiblePointerDiscardsQualifiers:
2057 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2058 rhsType.getAsString(), lhsType.getAsString(),
2059 argExpr->getSourceRange());
2060 break;
2061 case Incompatible:
2062 Diag(l, diag::err_typecheck_sending_incompatible,
2063 rhsType.getAsString(), lhsType.getAsString(),
2064 argExpr->getSourceRange());
2065 anyIncompatibleArgs = true;
2066 }
2067 }
2068 return anyIncompatibleArgs;
2069}
2070
Steve Naroff4ed9d662007-09-27 14:38:14 +00002071// ActOnClassMessage - used for both unary and keyword messages.
2072// ArgExprs is optional - if it is present, the number of expressions
2073// is obtained from Sel.getNumArgs().
2074Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002075 Scope *S,
Steve Narofffa465d12007-10-02 20:01:56 +00002076 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002077 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002078{
Steve Narofffa465d12007-10-02 20:01:56 +00002079 assert(receiverName && "missing receiver class name");
Steve Naroffc39ca262007-09-18 23:55:05 +00002080
Steve Naroff52664182007-10-16 23:12:48 +00002081 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002082 ObjcInterfaceDecl* ClassDecl = 0;
2083 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2084 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahanian342f3602007-11-12 20:20:37 +00002085 if (ClassDecl && CurMethodDecl->isInstance()) {
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002086 IdentifierInfo &II = Context.Idents.get("self");
2087 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II,
2088 false);
2089 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2090 superTy = Context.getPointerType(superTy);
2091 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2092 SourceLocation(), ReceiverExpr.Val);
2093
2094 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002095 Args, NumArgs);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002096 }
2097 // class method
2098 if (ClassDecl)
2099 receiverName = ClassDecl->getIdentifier();
2100 }
2101 else
2102 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Narofffa465d12007-10-02 20:01:56 +00002103 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002104 QualType returnType;
Steve Naroff75c4baf2007-11-05 15:27:52 +00002105
2106 // Before we give up, check if the selector is an instance method.
2107 if (!Method)
2108 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002109 if (!Method) {
2110 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2111 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002112 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002113 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002114 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002115 if (Sel.getNumArgs()) {
2116 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2117 return true;
2118 }
Steve Naroff7e461452007-10-16 20:39:36 +00002119 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002120 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
Steve Naroff9f176d12007-11-15 13:05:42 +00002121 lbrac, rbrac, ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002122}
2123
Steve Naroff4ed9d662007-09-27 14:38:14 +00002124// ActOnInstanceMessage - used for both unary and keyword messages.
2125// ArgExprs is optional - if it is present, the number of expressions
2126// is obtained from Sel.getNumArgs().
2127Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroff6cb1d362007-09-28 22:22:11 +00002128 ExprTy *receiver, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002129 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff4ed9d662007-09-27 14:38:14 +00002130{
Steve Naroffc39ca262007-09-18 23:55:05 +00002131 assert(receiver && "missing receiver expression");
2132
Steve Naroff52664182007-10-16 23:12:48 +00002133 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroffc39ca262007-09-18 23:55:05 +00002134 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Narofffa465d12007-10-02 20:01:56 +00002135 QualType receiverType = RExpr->getType();
Steve Naroffee1de132007-10-10 21:53:07 +00002136 QualType returnType;
Steve Naroff1e1c3912007-11-03 16:37:59 +00002137 ObjcMethodDecl *Method;
Steve Naroffee1de132007-10-10 21:53:07 +00002138
Steve Naroff0091d142007-11-11 17:52:25 +00002139 if (receiverType == Context.getObjcIdType() ||
2140 receiverType == Context.getObjcClassType()) {
Steve Naroff1e1c3912007-11-03 16:37:59 +00002141 Method = InstanceMethodPool[Sel].Method;
Steve Naroffd0cfcd02007-11-13 04:10:18 +00002142 // If we didn't find an public method, look for a private one.
2143 if (!Method && CurMethodDecl) {
2144 NamedDecl *impCxt = CurMethodDecl->getMethodContext();
2145 if (ObjcImplementationDecl *IMD =
2146 dyn_cast<ObjcImplementationDecl>(impCxt)) {
2147 if (receiverType == Context.getObjcIdType())
2148 Method = IMD->lookupInstanceMethod(Sel);
2149 else
2150 Method = IMD->lookupClassMethod(Sel);
2151 } else if (ObjcCategoryImplDecl *CID =
2152 dyn_cast<ObjcCategoryImplDecl>(impCxt)) {
2153 if (receiverType == Context.getObjcIdType())
2154 Method = CID->lookupInstanceMethod(Sel);
2155 else
2156 Method = CID->lookupClassMethod(Sel);
2157 }
2158 }
Steve Naroff7e461452007-10-16 20:39:36 +00002159 if (!Method) {
2160 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2161 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002162 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002163 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002164 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002165 if (Sel.getNumArgs())
2166 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2167 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002168 }
Steve Naroffee1de132007-10-10 21:53:07 +00002169 } else {
Chris Lattner71c01112007-10-10 23:42:28 +00002170 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2171 // revisited. how do we get the ClassDecl from the receiver expression?
Steve Naroffee1de132007-10-10 21:53:07 +00002172 while (receiverType->isPointerType()) {
Chris Lattner71c01112007-10-10 23:42:28 +00002173 PointerType *pointerType =
2174 static_cast<PointerType*>(receiverType.getTypePtr());
Steve Naroffee1de132007-10-10 21:53:07 +00002175 receiverType = pointerType->getPointeeType();
2176 }
Chris Lattner71c01112007-10-10 23:42:28 +00002177 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2178 "bad receiver type");
Steve Naroffee1de132007-10-10 21:53:07 +00002179 ObjcInterfaceDecl* ClassDecl = static_cast<ObjcInterfaceType*>(
2180 receiverType.getTypePtr())->getDecl();
Steve Naroff7e461452007-10-16 20:39:36 +00002181 // FIXME: consider using InstanceMethodPool, since it will be faster
2182 // than the following method (which can do *many* linear searches). The
2183 // idea is to add class info to InstanceMethodPool...
Steve Naroff1e1c3912007-11-03 16:37:59 +00002184 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002185 if (!Method) {
Steve Naroffb1c7ad92007-11-11 00:10:47 +00002186 // If we have an implementation in scope, check "private" methods.
2187 if (ObjcImplementationDecl *ImpDecl =
2188 ObjcImplementations[ClassDecl->getIdentifier()])
2189 Method = ImpDecl->lookupInstanceMethod(Sel);
2190 }
2191 if (!Method) {
Steve Naroff7e461452007-10-16 20:39:36 +00002192 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2193 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002194 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002195 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002196 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002197 if (Sel.getNumArgs())
2198 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2199 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002200 }
Steve Narofffa465d12007-10-02 20:01:56 +00002201 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002202 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002203 ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002204}