blob: 14302aab08275593d741e43f6d33c73b6bc0a638 [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:
Steve Naroffcdee22d2007-11-27 17:58:44 +0000616 Diag(l, diag::ext_typecheck_passing_pointer_int,
617 lhsType.getAsString(), rhsType.getAsString(),
618 Fn->getSourceRange(), argExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000619 break;
620 case IntFromPointer:
621 Diag(l, diag::ext_typecheck_passing_pointer_int,
622 lhsType.getAsString(), rhsType.getAsString(),
623 Fn->getSourceRange(), argExpr->getSourceRange());
624 break;
625 case IncompatiblePointer:
626 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
627 rhsType.getAsString(), lhsType.getAsString(),
628 Fn->getSourceRange(), argExpr->getSourceRange());
629 break;
630 case CompatiblePointerDiscardsQualifiers:
631 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
632 rhsType.getAsString(), lhsType.getAsString(),
633 Fn->getSourceRange(), argExpr->getSourceRange());
634 break;
635 case Incompatible:
636 return Diag(l, diag::err_typecheck_passing_incompatible,
637 rhsType.getAsString(), lhsType.getAsString(),
638 Fn->getSourceRange(), argExpr->getSourceRange());
639 }
640 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000641 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
642 // Promote the arguments (C99 6.5.2.2p7).
643 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
644 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000645 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000646
647 DefaultArgumentPromotion(argExpr);
648 if (Args[i] != argExpr) // The expression was converted.
649 Args[i] = argExpr; // Make sure we store the converted expression.
650 }
651 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
652 // Even if the types checked, bail if the number of arguments don't match.
Chris Lattner4b009652007-07-25 00:24:17 +0000653 return true;
Steve Naroffdb65e052007-08-28 23:30:39 +0000654 }
655 } else if (isa<FunctionTypeNoProto>(funcT)) {
656 // Promote the arguments (C99 6.5.2.2p6).
657 for (unsigned i = 0; i < NumArgsInCall; i++) {
658 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000659 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000660
661 DefaultArgumentPromotion(argExpr);
662 if (Args[i] != argExpr) // The expression was converted.
663 Args[i] = argExpr; // Make sure we store the converted expression.
664 }
Chris Lattner4b009652007-07-25 00:24:17 +0000665 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000666 // Do special checking on direct calls to functions.
667 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
668 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
669 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000670 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
671 NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000672 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000673
Chris Lattner4b009652007-07-25 00:24:17 +0000674 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
675}
676
677Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000678ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000679 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000680 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000681 QualType literalType = QualType::getFromOpaquePtr(Ty);
682 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000683 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000684 Expr *literalExpr = static_cast<Expr*>(InitExpr);
685
686 // FIXME: add semantic analysis (C99 6.5.2.5).
687 return new CompoundLiteralExpr(literalType, literalExpr);
688}
689
690Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000691ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000692 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000693 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000694
Steve Naroff0acc9c92007-09-15 18:49:24 +0000695 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000696 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000697
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000698 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
699 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
700 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000701}
702
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000703bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty)
704{
705 assert(VectorTy->isVectorType() && "Not a vector type!");
706
707 if (Ty->isVectorType() || Ty->isIntegerType()) {
708 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
709 Context.getTypeSize(Ty, SourceLocation()))
710 return Diag(R.getBegin(),
711 Ty->isVectorType() ?
712 diag::err_invalid_conversion_between_vectors :
713 diag::err_invalid_conversion_between_vector_and_integer,
714 VectorTy.getAsString().c_str(),
715 Ty.getAsString().c_str(), R);
716 } else
717 return Diag(R.getBegin(),
718 diag::err_invalid_conversion_between_vector_and_scalar,
719 VectorTy.getAsString().c_str(),
720 Ty.getAsString().c_str(), R);
721
722 return false;
723}
724
Chris Lattner4b009652007-07-25 00:24:17 +0000725Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000726ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000727 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000728 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000729
730 Expr *castExpr = static_cast<Expr*>(Op);
731 QualType castType = QualType::getFromOpaquePtr(Ty);
732
Steve Naroff68adb482007-08-31 00:32:44 +0000733 UsualUnaryConversions(castExpr);
734
Chris Lattner4b009652007-07-25 00:24:17 +0000735 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
736 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000737 if (!castType->isVoidType()) { // Cast to void allows any expr type.
738 if (!castType->isScalarType())
739 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
740 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000741 if (!castExpr->getType()->isScalarType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000742 return Diag(castExpr->getLocStart(),
743 diag::err_typecheck_expect_scalar_operand,
744 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000745
746 if (castExpr->getType()->isVectorType()) {
747 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
748 castExpr->getType(), castType))
749 return true;
750 } else if (castType->isVectorType()) {
751 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
752 castType, castExpr->getType()))
753 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000754 }
Chris Lattner4b009652007-07-25 00:24:17 +0000755 }
756 return new CastExpr(castType, castExpr, LParenLoc);
757}
758
Steve Naroff144667e2007-10-18 05:13:08 +0000759// promoteExprToType - a helper function to ensure we create exactly one
760// ImplicitCastExpr.
761static void promoteExprToType(Expr *&expr, QualType type) {
762 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
763 impCast->setType(type);
764 else
765 expr = new ImplicitCastExpr(type, expr);
766 return;
767}
768
Chris Lattner98a425c2007-11-26 01:40:58 +0000769/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
770/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000771inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
772 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
773 UsualUnaryConversions(cond);
774 UsualUnaryConversions(lex);
775 UsualUnaryConversions(rex);
776 QualType condT = cond->getType();
777 QualType lexT = lex->getType();
778 QualType rexT = rex->getType();
779
780 // first, check the condition.
781 if (!condT->isScalarType()) { // C99 6.5.15p2
782 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
783 condT.getAsString());
784 return QualType();
785 }
786 // now check the two expressions.
787 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
788 UsualArithmeticConversions(lex, rex);
789 return lex->getType();
790 }
Chris Lattner71225142007-07-31 21:27:01 +0000791 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
792 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
Chris Lattner98a425c2007-11-26 01:40:58 +0000793 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner71225142007-07-31 21:27:01 +0000794 return lexT;
795
Chris Lattner4b009652007-07-25 00:24:17 +0000796 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
797 lexT.getAsString(), rexT.getAsString(),
798 lex->getSourceRange(), rex->getSourceRange());
799 return QualType();
800 }
801 }
802 // C99 6.5.15p3
Steve Naroff144667e2007-10-18 05:13:08 +0000803 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
804 promoteExprToType(rex, lexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000805 return lexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000806 }
807 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
808 promoteExprToType(lex, rexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000809 return rexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000810 }
Chris Lattner71225142007-07-31 21:27:01 +0000811 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
812 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
813 // get the "pointed to" types
814 QualType lhptee = LHSPT->getPointeeType();
815 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000816
Chris Lattner71225142007-07-31 21:27:01 +0000817 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
818 if (lhptee->isVoidType() &&
819 (rhptee->isObjectType() || rhptee->isIncompleteType()))
820 return lexT;
821 if (rhptee->isVoidType() &&
822 (lhptee->isObjectType() || lhptee->isIncompleteType()))
823 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000824
Steve Naroff85f0dc52007-10-15 20:41:53 +0000825 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
826 rhptee.getUnqualifiedType())) {
Chris Lattner71225142007-07-31 21:27:01 +0000827 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
828 lexT.getAsString(), rexT.getAsString(),
829 lex->getSourceRange(), rex->getSourceRange());
830 return lexT; // FIXME: this is an _ext - is this return o.k?
831 }
832 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000833 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
834 // differently qualified versions of compatible types, the result type is
835 // a pointer to an appropriately qualified version of the *composite*
836 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000837 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000838 }
Chris Lattner4b009652007-07-25 00:24:17 +0000839 }
Chris Lattner71225142007-07-31 21:27:01 +0000840
Chris Lattner4b009652007-07-25 00:24:17 +0000841 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
842 return lexT;
843
844 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
845 lexT.getAsString(), rexT.getAsString(),
846 lex->getSourceRange(), rex->getSourceRange());
847 return QualType();
848}
849
Steve Naroff87d58b42007-09-16 03:34:24 +0000850/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000851/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000852Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000853 SourceLocation ColonLoc,
854 ExprTy *Cond, ExprTy *LHS,
855 ExprTy *RHS) {
856 Expr *CondExpr = (Expr *) Cond;
857 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000858
859 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
860 // was the condition.
861 bool isLHSNull = LHSExpr == 0;
862 if (isLHSNull)
863 LHSExpr = CondExpr;
864
Chris Lattner4b009652007-07-25 00:24:17 +0000865 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
866 RHSExpr, QuestionLoc);
867 if (result.isNull())
868 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000869 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
870 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000871}
872
Steve Naroffdb65e052007-08-28 23:30:39 +0000873/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
874/// do not have a prototype. Integer promotions are performed on each
875/// argument, and arguments that have type float are promoted to double.
876void Sema::DefaultArgumentPromotion(Expr *&expr) {
877 QualType t = expr->getType();
878 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
879
880 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
881 promoteExprToType(expr, Context.IntTy);
882 if (t == Context.FloatTy)
883 promoteExprToType(expr, Context.DoubleTy);
884}
885
Chris Lattner4b009652007-07-25 00:24:17 +0000886/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
887void Sema::DefaultFunctionArrayConversion(Expr *&e) {
888 QualType t = e->getType();
889 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
890
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000891 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000892 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
893 t = e->getType();
894 }
895 if (t->isFunctionType())
896 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000897 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000898 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
899}
900
901/// UsualUnaryConversion - Performs various conversions that are common to most
902/// operators (C99 6.3). The conversions of array and function types are
903/// sometimes surpressed. For example, the array->pointer conversion doesn't
904/// apply if the array is an argument to the sizeof or address (&) operators.
905/// In these instances, this routine should *not* be called.
906void Sema::UsualUnaryConversions(Expr *&expr) {
907 QualType t = expr->getType();
908 assert(!t.isNull() && "UsualUnaryConversions - missing type");
909
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000910 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000911 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
912 t = expr->getType();
913 }
914 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
915 promoteExprToType(expr, Context.IntTy);
916 else
917 DefaultFunctionArrayConversion(expr);
918}
919
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000920/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000921/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
922/// routine returns the first non-arithmetic type found. The client is
923/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000924QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
925 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000926 if (!isCompAssign) {
927 UsualUnaryConversions(lhsExpr);
928 UsualUnaryConversions(rhsExpr);
929 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000930 // For conversion purposes, we ignore any qualifiers.
931 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000932 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
933 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000934
935 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000936 if (lhs == rhs)
937 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000938
939 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
940 // The caller can deal with this (e.g. pointer + int).
941 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000942 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000943
944 // At this point, we have two different arithmetic types.
945
946 // Handle complex types first (C99 6.3.1.8p1).
947 if (lhs->isComplexType() || rhs->isComplexType()) {
948 // if we have an integer operand, the result is the complex type.
949 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000950 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
951 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000952 }
953 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000954 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
955 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000956 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000957 // This handles complex/complex, complex/float, or float/complex.
958 // When both operands are complex, the shorter operand is converted to the
959 // type of the longer, and that is the type of the result. This corresponds
960 // to what is done when combining two real floating-point operands.
961 // The fun begins when size promotion occur across type domains.
962 // From H&S 6.3.4: When one operand is complex and the other is a real
963 // floating-point type, the less precise type is converted, within it's
964 // real or complex domain, to the precision of the other type. For example,
965 // when combining a "long double" with a "double _Complex", the
966 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000967 int result = Context.compareFloatingType(lhs, rhs);
968
969 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000970 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
971 if (!isCompAssign)
972 promoteExprToType(rhsExpr, rhs);
973 } else if (result < 0) { // The right side is bigger, convert lhs.
974 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
975 if (!isCompAssign)
976 promoteExprToType(lhsExpr, lhs);
977 }
978 // At this point, lhs and rhs have the same rank/size. Now, make sure the
979 // domains match. This is a requirement for our implementation, C99
980 // does not require this promotion.
981 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
982 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000983 if (!isCompAssign)
984 promoteExprToType(lhsExpr, rhs);
985 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000986 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000987 if (!isCompAssign)
988 promoteExprToType(rhsExpr, lhs);
989 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000990 }
Chris Lattner4b009652007-07-25 00:24:17 +0000991 }
Steve Naroff3b6157f2007-08-27 21:43:43 +0000992 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +0000993 }
994 // Now handle "real" floating types (i.e. float, double, long double).
995 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
996 // if we have an integer operand, the result is the real floating type.
997 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000998 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
999 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001000 }
1001 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001002 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
1003 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001004 }
1005 // We have two real floating types, float/complex combos were handled above.
1006 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +00001007 int result = Context.compareFloatingType(lhs, rhs);
1008
1009 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001010 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1011 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001012 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001013 if (result < 0) { // convert the lhs
1014 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1015 return rhs;
1016 }
1017 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001018 }
1019 // Finally, we have two differing integer types.
1020 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001021 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1022 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001023 }
Steve Naroff8f708362007-08-24 19:07:16 +00001024 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1025 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001026}
1027
1028// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1029// being closely modeled after the C99 spec:-). The odd characteristic of this
1030// routine is it effectively iqnores the qualifiers on the top level pointee.
1031// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1032// FIXME: add a couple examples in this comment.
1033Sema::AssignmentCheckResult
1034Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1035 QualType lhptee, rhptee;
1036
1037 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001038 lhptee = lhsType->getAsPointerType()->getPointeeType();
1039 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001040
1041 // make sure we operate on the canonical type
1042 lhptee = lhptee.getCanonicalType();
1043 rhptee = rhptee.getCanonicalType();
1044
1045 AssignmentCheckResult r = Compatible;
1046
1047 // C99 6.5.16.1p1: This following citation is common to constraints
1048 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1049 // qualifiers of the type *pointed to* by the right;
1050 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1051 rhptee.getQualifiers())
1052 r = CompatiblePointerDiscardsQualifiers;
1053
1054 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1055 // incomplete type and the other is a pointer to a qualified or unqualified
1056 // version of void...
1057 if (lhptee.getUnqualifiedType()->isVoidType() &&
1058 (rhptee->isObjectType() || rhptee->isIncompleteType()))
1059 ;
1060 else if (rhptee.getUnqualifiedType()->isVoidType() &&
1061 (lhptee->isObjectType() || lhptee->isIncompleteType()))
1062 ;
1063 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1064 // unqualified versions of compatible types, ...
Steve Naroff85f0dc52007-10-15 20:41:53 +00001065 else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1066 rhptee.getUnqualifiedType()))
Chris Lattner4b009652007-07-25 00:24:17 +00001067 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1068 return r;
1069}
1070
1071/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1072/// has code to accommodate several GCC extensions when type checking
1073/// pointers. Here are some objectionable examples that GCC considers warnings:
1074///
1075/// int a, *pint;
1076/// short *pshort;
1077/// struct foo *pfoo;
1078///
1079/// pint = pshort; // warning: assignment from incompatible pointer type
1080/// a = pint; // warning: assignment makes integer from pointer without a cast
1081/// pint = a; // warning: assignment makes pointer from integer without a cast
1082/// pint = pfoo; // warning: assignment from incompatible pointer type
1083///
1084/// As a result, the code for dealing with pointers is more complex than the
1085/// C99 spec dictates.
1086/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1087///
1088Sema::AssignmentCheckResult
1089Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Steve Naroffeed76842007-11-13 00:31:42 +00001090 if (lhsType.getCanonicalType().getUnqualifiedType() ==
1091 rhsType.getCanonicalType().getUnqualifiedType())
Chris Lattnera703c2e2007-10-29 05:15:40 +00001092 return Compatible; // common case, fast path...
Chris Lattner4b009652007-07-25 00:24:17 +00001093
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001094 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001095 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001096 return Compatible;
1097 } else if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001098 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1099 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1100 return Incompatible;
1101 }
1102 return Compatible;
1103 } else if (lhsType->isPointerType()) {
1104 if (rhsType->isIntegerType())
1105 return PointerFromInt;
1106
1107 if (rhsType->isPointerType())
1108 return CheckPointerTypesForAssignment(lhsType, rhsType);
1109 } else if (rhsType->isPointerType()) {
1110 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1111 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1112 return IntFromPointer;
1113
1114 if (lhsType->isPointerType())
1115 return CheckPointerTypesForAssignment(lhsType, rhsType);
1116 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001117 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001118 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001119 }
1120 return Incompatible;
1121}
1122
1123Sema::AssignmentCheckResult
1124Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001125 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1126 // a null pointer constant.
1127 if (lhsType->isPointerType() && rExpr->isNullPointerConstant(Context)) {
1128 promoteExprToType(rExpr, lhsType);
1129 return Compatible;
1130 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001131 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001132 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001133 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001134 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001135 //
1136 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1137 // are better understood.
1138 if (!lhsType->isReferenceType())
1139 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001140
1141 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +00001142
Steve Naroff0f32f432007-08-24 22:33:52 +00001143 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1144
1145 // C99 6.5.16.1p2: The value of the right operand is converted to the
1146 // type of the assignment expression.
1147 if (rExpr->getType() != lhsType)
1148 promoteExprToType(rExpr, lhsType);
1149 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001150}
1151
1152Sema::AssignmentCheckResult
1153Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1154 return CheckAssignmentConstraints(lhsType, rhsType);
1155}
1156
1157inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1158 Diag(loc, diag::err_typecheck_invalid_operands,
1159 lex->getType().getAsString(), rex->getType().getAsString(),
1160 lex->getSourceRange(), rex->getSourceRange());
1161}
1162
1163inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1164 Expr *&rex) {
1165 QualType lhsType = lex->getType(), rhsType = rex->getType();
1166
1167 // make sure the vector types are identical.
1168 if (lhsType == rhsType)
1169 return lhsType;
1170 // You cannot convert between vector values of different size.
1171 Diag(loc, diag::err_typecheck_vector_not_convertable,
1172 lex->getType().getAsString(), rex->getType().getAsString(),
1173 lex->getSourceRange(), rex->getSourceRange());
1174 return QualType();
1175}
1176
1177inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001178 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001179{
1180 QualType lhsType = lex->getType(), rhsType = rex->getType();
1181
1182 if (lhsType->isVectorType() || rhsType->isVectorType())
1183 return CheckVectorOperands(loc, lex, rex);
1184
Steve Naroff8f708362007-08-24 19:07:16 +00001185 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001186
Chris Lattner4b009652007-07-25 00:24:17 +00001187 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001188 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001189 InvalidOperands(loc, lex, rex);
1190 return QualType();
1191}
1192
1193inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001194 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001195{
1196 QualType lhsType = lex->getType(), rhsType = rex->getType();
1197
Steve Naroff8f708362007-08-24 19:07:16 +00001198 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001199
Chris Lattner4b009652007-07-25 00:24:17 +00001200 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001201 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001202 InvalidOperands(loc, lex, rex);
1203 return QualType();
1204}
1205
1206inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001207 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001208{
1209 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1210 return CheckVectorOperands(loc, lex, rex);
1211
Steve Naroff8f708362007-08-24 19:07:16 +00001212 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001213
1214 // handle the common case first (both operands are arithmetic).
1215 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001216 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001217
1218 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1219 return lex->getType();
1220 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1221 return rex->getType();
1222 InvalidOperands(loc, lex, rex);
1223 return QualType();
1224}
1225
1226inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001227 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001228{
1229 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1230 return CheckVectorOperands(loc, lex, rex);
1231
Steve Naroff8f708362007-08-24 19:07:16 +00001232 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001233
1234 // handle the common case first (both operands are arithmetic).
1235 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001236 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001237
1238 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001239 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001240 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1241 return Context.getPointerDiffType();
1242 InvalidOperands(loc, lex, rex);
1243 return QualType();
1244}
1245
1246inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001247 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001248{
1249 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1250 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001251 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001252
1253 // handle the common case first (both operands are arithmetic).
1254 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001255 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001256 InvalidOperands(loc, lex, rex);
1257 return QualType();
1258}
1259
Chris Lattner254f3bc2007-08-26 01:18:55 +00001260inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1261 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001262{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001263 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001264 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1265 UsualArithmeticConversions(lex, rex);
1266 else {
1267 UsualUnaryConversions(lex);
1268 UsualUnaryConversions(rex);
1269 }
Chris Lattner4b009652007-07-25 00:24:17 +00001270 QualType lType = lex->getType();
1271 QualType rType = rex->getType();
1272
Ted Kremenek486509e2007-10-29 17:13:39 +00001273 // For non-floating point types, check for self-comparisons of the form
1274 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1275 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001276 if (!lType->isFloatingType()) {
1277 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1278 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1279 if (DRL->getDecl() == DRR->getDecl())
1280 Diag(loc, diag::warn_selfcomparison);
1281 }
1282
Chris Lattner254f3bc2007-08-26 01:18:55 +00001283 if (isRelational) {
1284 if (lType->isRealType() && rType->isRealType())
1285 return Context.IntTy;
1286 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001287 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001288 if (lType->isFloatingType()) {
1289 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001290 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001291 }
1292
Chris Lattner254f3bc2007-08-26 01:18:55 +00001293 if (lType->isArithmeticType() && rType->isArithmeticType())
1294 return Context.IntTy;
1295 }
Chris Lattner4b009652007-07-25 00:24:17 +00001296
Chris Lattner22be8422007-08-26 01:10:14 +00001297 bool LHSIsNull = lex->isNullPointerConstant(Context);
1298 bool RHSIsNull = rex->isNullPointerConstant(Context);
1299
Chris Lattner254f3bc2007-08-26 01:18:55 +00001300 // All of the following pointer related warnings are GCC extensions, except
1301 // when handling null pointer constants. One day, we can consider making them
1302 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001303 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff3b435622007-11-13 14:57:38 +00001304
1305 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1306 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1307 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroff85f0dc52007-10-15 20:41:53 +00001308 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1309 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001310 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1311 lType.getAsString(), rType.getAsString(),
1312 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001313 }
Chris Lattner22be8422007-08-26 01:10:14 +00001314 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001315 return Context.IntTy;
1316 }
1317 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001318 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001319 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1320 lType.getAsString(), rType.getAsString(),
1321 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001322 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001323 return Context.IntTy;
1324 }
1325 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001326 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001327 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1328 lType.getAsString(), rType.getAsString(),
1329 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001330 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001331 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001332 }
1333 InvalidOperands(loc, lex, rex);
1334 return QualType();
1335}
1336
Chris Lattner4b009652007-07-25 00:24:17 +00001337inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001338 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001339{
1340 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1341 return CheckVectorOperands(loc, lex, rex);
1342
Steve Naroff8f708362007-08-24 19:07:16 +00001343 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001344
1345 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001346 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001347 InvalidOperands(loc, lex, rex);
1348 return QualType();
1349}
1350
1351inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1352 Expr *&lex, Expr *&rex, SourceLocation loc)
1353{
1354 UsualUnaryConversions(lex);
1355 UsualUnaryConversions(rex);
1356
1357 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1358 return Context.IntTy;
1359 InvalidOperands(loc, lex, rex);
1360 return QualType();
1361}
1362
1363inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001364 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001365{
1366 QualType lhsType = lex->getType();
1367 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1368 bool hadError = false;
1369 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1370
1371 switch (mlval) { // C99 6.5.16p2
1372 case Expr::MLV_Valid:
1373 break;
1374 case Expr::MLV_ConstQualified:
1375 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1376 hadError = true;
1377 break;
1378 case Expr::MLV_ArrayType:
1379 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1380 lhsType.getAsString(), lex->getSourceRange());
1381 return QualType();
1382 case Expr::MLV_NotObjectType:
1383 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1384 lhsType.getAsString(), lex->getSourceRange());
1385 return QualType();
1386 case Expr::MLV_InvalidExpression:
1387 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1388 lex->getSourceRange());
1389 return QualType();
1390 case Expr::MLV_IncompleteType:
1391 case Expr::MLV_IncompleteVoidType:
1392 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1393 lhsType.getAsString(), lex->getSourceRange());
1394 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001395 case Expr::MLV_DuplicateVectorComponents:
1396 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1397 lex->getSourceRange());
1398 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001399 }
1400 AssignmentCheckResult result;
1401
1402 if (compoundType.isNull())
1403 result = CheckSingleAssignmentConstraints(lhsType, rex);
1404 else
1405 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001406
Chris Lattner4b009652007-07-25 00:24:17 +00001407 // decode the result (notice that extensions still return a type).
1408 switch (result) {
1409 case Compatible:
1410 break;
1411 case Incompatible:
1412 Diag(loc, diag::err_typecheck_assign_incompatible,
1413 lhsType.getAsString(), rhsType.getAsString(),
1414 lex->getSourceRange(), rex->getSourceRange());
1415 hadError = true;
1416 break;
1417 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +00001418 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1419 lhsType.getAsString(), rhsType.getAsString(),
1420 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001421 break;
1422 case IntFromPointer:
1423 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1424 lhsType.getAsString(), rhsType.getAsString(),
1425 lex->getSourceRange(), rex->getSourceRange());
1426 break;
1427 case IncompatiblePointer:
1428 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1429 lhsType.getAsString(), rhsType.getAsString(),
1430 lex->getSourceRange(), rex->getSourceRange());
1431 break;
1432 case CompatiblePointerDiscardsQualifiers:
1433 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1434 lhsType.getAsString(), rhsType.getAsString(),
1435 lex->getSourceRange(), rex->getSourceRange());
1436 break;
1437 }
1438 // C99 6.5.16p3: The type of an assignment expression is the type of the
1439 // left operand unless the left operand has qualified type, in which case
1440 // it is the unqualified version of the type of the left operand.
1441 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1442 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001443 // C++ 5.17p1: the type of the assignment expression is that of its left
1444 // oprdu.
Chris Lattner4b009652007-07-25 00:24:17 +00001445 return hadError ? QualType() : lhsType.getUnqualifiedType();
1446}
1447
1448inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1449 Expr *&lex, Expr *&rex, SourceLocation loc) {
1450 UsualUnaryConversions(rex);
1451 return rex->getType();
1452}
1453
1454/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1455/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1456QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1457 QualType resType = op->getType();
1458 assert(!resType.isNull() && "no type for increment/decrement expression");
1459
Steve Naroffd30e1932007-08-24 17:20:07 +00001460 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001461 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001462 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1463 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1464 resType.getAsString(), op->getSourceRange());
1465 return QualType();
1466 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001467 } else if (!resType->isRealType()) {
1468 if (resType->isComplexType())
1469 // C99 does not support ++/-- on complex types.
1470 Diag(OpLoc, diag::ext_integer_increment_complex,
1471 resType.getAsString(), op->getSourceRange());
1472 else {
1473 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1474 resType.getAsString(), op->getSourceRange());
1475 return QualType();
1476 }
Chris Lattner4b009652007-07-25 00:24:17 +00001477 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001478 // At this point, we know we have a real, complex or pointer type.
1479 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001480 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1481 if (mlval != Expr::MLV_Valid) {
1482 // FIXME: emit a more precise diagnostic...
1483 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1484 op->getSourceRange());
1485 return QualType();
1486 }
1487 return resType;
1488}
1489
1490/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1491/// This routine allows us to typecheck complex/recursive expressions
1492/// where the declaration is needed for type checking. Here are some
1493/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1494static Decl *getPrimaryDeclaration(Expr *e) {
1495 switch (e->getStmtClass()) {
1496 case Stmt::DeclRefExprClass:
1497 return cast<DeclRefExpr>(e)->getDecl();
1498 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001499 // Fields cannot be declared with a 'register' storage class.
1500 // &X->f is always ok, even if X is declared register.
1501 if (cast<MemberExpr>(e)->isArrow())
1502 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001503 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1504 case Stmt::ArraySubscriptExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001505 // &X[4] and &4[X] is invalid if X is invalid.
Chris Lattner4b009652007-07-25 00:24:17 +00001506 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +00001507 case Stmt::UnaryOperatorClass:
1508 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1509 case Stmt::ParenExprClass:
1510 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001511 case Stmt::ImplicitCastExprClass:
1512 // &X[4] when X is an array, has an implicit cast from array to pointer.
1513 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001514 default:
1515 return 0;
1516 }
1517}
1518
1519/// CheckAddressOfOperand - The operand of & must be either a function
1520/// designator or an lvalue designating an object. If it is an lvalue, the
1521/// object cannot be declared with storage class register or be a bit field.
1522/// Note: The usual conversions are *not* applied to the operand of the &
1523/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1524QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1525 Decl *dcl = getPrimaryDeclaration(op);
1526 Expr::isLvalueResult lval = op->isLvalue();
1527
1528 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001529 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1530 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001531 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1532 op->getSourceRange());
1533 return QualType();
1534 }
1535 } else if (dcl) {
1536 // We have an lvalue with a decl. Make sure the decl is not declared
1537 // with the register storage-class specifier.
1538 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1539 if (vd->getStorageClass() == VarDecl::Register) {
1540 Diag(OpLoc, diag::err_typecheck_address_of_register,
1541 op->getSourceRange());
1542 return QualType();
1543 }
1544 } else
1545 assert(0 && "Unknown/unexpected decl type");
1546
1547 // FIXME: add check for bitfields!
1548 }
1549 // If the operand has type "type", the result has type "pointer to type".
1550 return Context.getPointerType(op->getType());
1551}
1552
1553QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1554 UsualUnaryConversions(op);
1555 QualType qType = op->getType();
1556
Chris Lattner7931f4a2007-07-31 16:53:04 +00001557 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001558 QualType ptype = PT->getPointeeType();
1559 // C99 6.5.3.2p4. "if it points to an object,...".
1560 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1561 // GCC compat: special case 'void *' (treat as warning).
1562 if (ptype->isVoidType()) {
1563 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1564 qType.getAsString(), op->getSourceRange());
1565 } else {
1566 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1567 ptype.getAsString(), op->getSourceRange());
1568 return QualType();
1569 }
1570 }
1571 return ptype;
1572 }
1573 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1574 qType.getAsString(), op->getSourceRange());
1575 return QualType();
1576}
1577
1578static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1579 tok::TokenKind Kind) {
1580 BinaryOperator::Opcode Opc;
1581 switch (Kind) {
1582 default: assert(0 && "Unknown binop!");
1583 case tok::star: Opc = BinaryOperator::Mul; break;
1584 case tok::slash: Opc = BinaryOperator::Div; break;
1585 case tok::percent: Opc = BinaryOperator::Rem; break;
1586 case tok::plus: Opc = BinaryOperator::Add; break;
1587 case tok::minus: Opc = BinaryOperator::Sub; break;
1588 case tok::lessless: Opc = BinaryOperator::Shl; break;
1589 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1590 case tok::lessequal: Opc = BinaryOperator::LE; break;
1591 case tok::less: Opc = BinaryOperator::LT; break;
1592 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1593 case tok::greater: Opc = BinaryOperator::GT; break;
1594 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1595 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1596 case tok::amp: Opc = BinaryOperator::And; break;
1597 case tok::caret: Opc = BinaryOperator::Xor; break;
1598 case tok::pipe: Opc = BinaryOperator::Or; break;
1599 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1600 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1601 case tok::equal: Opc = BinaryOperator::Assign; break;
1602 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1603 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1604 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1605 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1606 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1607 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1608 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1609 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1610 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1611 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1612 case tok::comma: Opc = BinaryOperator::Comma; break;
1613 }
1614 return Opc;
1615}
1616
1617static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1618 tok::TokenKind Kind) {
1619 UnaryOperator::Opcode Opc;
1620 switch (Kind) {
1621 default: assert(0 && "Unknown unary op!");
1622 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1623 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1624 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1625 case tok::star: Opc = UnaryOperator::Deref; break;
1626 case tok::plus: Opc = UnaryOperator::Plus; break;
1627 case tok::minus: Opc = UnaryOperator::Minus; break;
1628 case tok::tilde: Opc = UnaryOperator::Not; break;
1629 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1630 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1631 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1632 case tok::kw___real: Opc = UnaryOperator::Real; break;
1633 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1634 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1635 }
1636 return Opc;
1637}
1638
1639// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001640Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001641 ExprTy *LHS, ExprTy *RHS) {
1642 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1643 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1644
Steve Naroff87d58b42007-09-16 03:34:24 +00001645 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1646 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001647
1648 QualType ResultTy; // Result type of the binary operator.
1649 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1650
1651 switch (Opc) {
1652 default:
1653 assert(0 && "Unknown binary expr!");
1654 case BinaryOperator::Assign:
1655 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1656 break;
1657 case BinaryOperator::Mul:
1658 case BinaryOperator::Div:
1659 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1660 break;
1661 case BinaryOperator::Rem:
1662 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1663 break;
1664 case BinaryOperator::Add:
1665 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1666 break;
1667 case BinaryOperator::Sub:
1668 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1669 break;
1670 case BinaryOperator::Shl:
1671 case BinaryOperator::Shr:
1672 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1673 break;
1674 case BinaryOperator::LE:
1675 case BinaryOperator::LT:
1676 case BinaryOperator::GE:
1677 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001678 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001679 break;
1680 case BinaryOperator::EQ:
1681 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001682 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001683 break;
1684 case BinaryOperator::And:
1685 case BinaryOperator::Xor:
1686 case BinaryOperator::Or:
1687 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1688 break;
1689 case BinaryOperator::LAnd:
1690 case BinaryOperator::LOr:
1691 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1692 break;
1693 case BinaryOperator::MulAssign:
1694 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001695 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001696 if (!CompTy.isNull())
1697 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1698 break;
1699 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001700 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001701 if (!CompTy.isNull())
1702 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1703 break;
1704 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001705 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001706 if (!CompTy.isNull())
1707 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1708 break;
1709 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001710 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001711 if (!CompTy.isNull())
1712 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1713 break;
1714 case BinaryOperator::ShlAssign:
1715 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001716 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001717 if (!CompTy.isNull())
1718 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1719 break;
1720 case BinaryOperator::AndAssign:
1721 case BinaryOperator::XorAssign:
1722 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001723 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001724 if (!CompTy.isNull())
1725 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1726 break;
1727 case BinaryOperator::Comma:
1728 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1729 break;
1730 }
1731 if (ResultTy.isNull())
1732 return true;
1733 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001734 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001735 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001736 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001737}
1738
1739// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001740Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001741 ExprTy *input) {
1742 Expr *Input = (Expr*)input;
1743 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1744 QualType resultType;
1745 switch (Opc) {
1746 default:
1747 assert(0 && "Unimplemented unary expr!");
1748 case UnaryOperator::PreInc:
1749 case UnaryOperator::PreDec:
1750 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1751 break;
1752 case UnaryOperator::AddrOf:
1753 resultType = CheckAddressOfOperand(Input, OpLoc);
1754 break;
1755 case UnaryOperator::Deref:
1756 resultType = CheckIndirectionOperand(Input, OpLoc);
1757 break;
1758 case UnaryOperator::Plus:
1759 case UnaryOperator::Minus:
1760 UsualUnaryConversions(Input);
1761 resultType = Input->getType();
1762 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1763 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1764 resultType.getAsString());
1765 break;
1766 case UnaryOperator::Not: // bitwise complement
1767 UsualUnaryConversions(Input);
1768 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001769 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1770 if (!resultType->isIntegerType()) {
1771 if (resultType->isComplexType())
1772 // C99 does not support '~' for complex conjugation.
1773 Diag(OpLoc, diag::ext_integer_complement_complex,
1774 resultType.getAsString());
1775 else
1776 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1777 resultType.getAsString());
1778 }
Chris Lattner4b009652007-07-25 00:24:17 +00001779 break;
1780 case UnaryOperator::LNot: // logical negation
1781 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1782 DefaultFunctionArrayConversion(Input);
1783 resultType = Input->getType();
1784 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1785 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1786 resultType.getAsString());
1787 // LNot always has type int. C99 6.5.3.3p5.
1788 resultType = Context.IntTy;
1789 break;
1790 case UnaryOperator::SizeOf:
1791 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1792 break;
1793 case UnaryOperator::AlignOf:
1794 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1795 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001796 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001797 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001798 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001799 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001800 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001801 resultType = Input->getType();
1802 break;
1803 }
1804 if (resultType.isNull())
1805 return true;
1806 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1807}
1808
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001809/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1810Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001811 SourceLocation LabLoc,
1812 IdentifierInfo *LabelII) {
1813 // Look up the record for this label identifier.
1814 LabelStmt *&LabelDecl = LabelMap[LabelII];
1815
1816 // If we haven't seen this label yet, create a forward reference.
1817 if (LabelDecl == 0)
1818 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1819
1820 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001821 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1822 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001823}
1824
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001825Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00001826 SourceLocation RPLoc) { // "({..})"
1827 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1828 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1829 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1830
1831 // FIXME: there are a variety of strange constraints to enforce here, for
1832 // example, it is not possible to goto into a stmt expression apparently.
1833 // More semantic analysis is needed.
1834
1835 // FIXME: the last statement in the compount stmt has its value used. We
1836 // should not warn about it being unused.
1837
1838 // If there are sub stmts in the compound stmt, take the type of the last one
1839 // as the type of the stmtexpr.
1840 QualType Ty = Context.VoidTy;
1841
1842 if (!Compound->body_empty())
1843 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1844 Ty = LastExpr->getType();
1845
1846 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1847}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001848
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001849Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001850 SourceLocation TypeLoc,
1851 TypeTy *argty,
1852 OffsetOfComponent *CompPtr,
1853 unsigned NumComponents,
1854 SourceLocation RPLoc) {
1855 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1856 assert(!ArgTy.isNull() && "Missing type argument!");
1857
1858 // We must have at least one component that refers to the type, and the first
1859 // one is known to be a field designator. Verify that the ArgTy represents
1860 // a struct/union/class.
1861 if (!ArgTy->isRecordType())
1862 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1863
1864 // Otherwise, create a compound literal expression as the base, and
1865 // iteratively process the offsetof designators.
1866 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1867
Chris Lattnerb37522e2007-08-31 21:49:13 +00001868 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1869 // GCC extension, diagnose them.
1870 if (NumComponents != 1)
1871 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1872 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1873
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001874 for (unsigned i = 0; i != NumComponents; ++i) {
1875 const OffsetOfComponent &OC = CompPtr[i];
1876 if (OC.isBrackets) {
1877 // Offset of an array sub-field. TODO: Should we allow vector elements?
1878 const ArrayType *AT = Res->getType()->getAsArrayType();
1879 if (!AT) {
1880 delete Res;
1881 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1882 Res->getType().getAsString());
1883 }
1884
Chris Lattner2af6a802007-08-30 17:59:59 +00001885 // FIXME: C++: Verify that operator[] isn't overloaded.
1886
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001887 // C99 6.5.2.1p1
1888 Expr *Idx = static_cast<Expr*>(OC.U.E);
1889 if (!Idx->getType()->isIntegerType())
1890 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1891 Idx->getSourceRange());
1892
1893 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1894 continue;
1895 }
1896
1897 const RecordType *RC = Res->getType()->getAsRecordType();
1898 if (!RC) {
1899 delete Res;
1900 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1901 Res->getType().getAsString());
1902 }
1903
1904 // Get the decl corresponding to this.
1905 RecordDecl *RD = RC->getDecl();
1906 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1907 if (!MemberDecl)
1908 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1909 OC.U.IdentInfo->getName(),
1910 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00001911
1912 // FIXME: C++: Verify that MemberDecl isn't a static field.
1913 // FIXME: Verify that MemberDecl isn't a bitfield.
1914
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001915 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1916 }
1917
1918 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1919 BuiltinLoc);
1920}
1921
1922
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001923Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001924 TypeTy *arg1, TypeTy *arg2,
1925 SourceLocation RPLoc) {
1926 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1927 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1928
1929 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1930
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001931 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001932}
1933
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001934Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00001935 ExprTy *expr1, ExprTy *expr2,
1936 SourceLocation RPLoc) {
1937 Expr *CondExpr = static_cast<Expr*>(cond);
1938 Expr *LHSExpr = static_cast<Expr*>(expr1);
1939 Expr *RHSExpr = static_cast<Expr*>(expr2);
1940
1941 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1942
1943 // The conditional expression is required to be a constant expression.
1944 llvm::APSInt condEval(32);
1945 SourceLocation ExpLoc;
1946 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1947 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1948 CondExpr->getSourceRange());
1949
1950 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1951 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1952 RHSExpr->getType();
1953 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1954}
1955
Anders Carlsson36760332007-10-15 20:28:48 +00001956Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
1957 ExprTy *expr, TypeTy *type,
1958 SourceLocation RPLoc)
1959{
1960 Expr *E = static_cast<Expr*>(expr);
1961 QualType T = QualType::getFromOpaquePtr(type);
1962
1963 InitBuiltinVaListType();
1964
1965 Sema::AssignmentCheckResult result;
1966
1967 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
1968 E->getType());
1969 if (result != Compatible)
1970 return Diag(E->getLocStart(),
1971 diag::err_first_argument_to_va_arg_not_of_type_va_list,
1972 E->getType().getAsString(),
1973 E->getSourceRange());
1974
1975 // FIXME: Warn if a non-POD type is passed in.
1976
1977 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
1978}
1979
Anders Carlssona66cad42007-08-21 17:43:55 +00001980// TODO: Move this to SemaObjC.cpp
Steve Naroff0add5d22007-11-03 11:27:19 +00001981Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation AtLoc,
1982 ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00001983 StringLiteral* S = static_cast<StringLiteral *>(string);
1984
1985 if (CheckBuiltinCFStringArgument(S))
1986 return true;
1987
Steve Narofff2e30312007-10-15 23:35:17 +00001988 if (Context.getObjcConstantStringInterface().isNull()) {
1989 // Initialize the constant string interface lazily. This assumes
1990 // the NSConstantString interface is seen in this translation unit.
1991 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
1992 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
1993 SourceLocation(), TUScope);
Steve Naroff134c3502007-10-16 00:00:18 +00001994 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff96f136d2007-10-18 23:53:51 +00001995 if (!strIFace)
1996 return Diag(S->getLocStart(), diag::err_undef_interface,
1997 NSIdent->getName());
Steve Naroff134c3502007-10-16 00:00:18 +00001998 Context.setObjcConstantStringInterface(strIFace);
Steve Narofff2e30312007-10-15 23:35:17 +00001999 }
2000 QualType t = Context.getObjcConstantStringInterface();
Anders Carlssona66cad42007-08-21 17:43:55 +00002001 t = Context.getPointerType(t);
Steve Naroff0add5d22007-11-03 11:27:19 +00002002 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlssona66cad42007-08-21 17:43:55 +00002003}
Anders Carlsson8be1d402007-08-22 15:14:15 +00002004
2005Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattnercfd61c82007-10-16 22:51:17 +00002006 SourceLocation EncodeLoc,
Anders Carlsson8be1d402007-08-22 15:14:15 +00002007 SourceLocation LParenLoc,
2008 TypeTy *Ty,
2009 SourceLocation RParenLoc) {
2010 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
2011
2012 QualType t = Context.getPointerType(Context.CharTy);
2013 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
2014}
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002015
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002016Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
2017 SourceLocation AtLoc,
Fariborz Jahanian957448a2007-10-16 23:21:02 +00002018 SourceLocation SelLoc,
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002019 SourceLocation LParenLoc,
2020 SourceLocation RParenLoc) {
Steve Naroffae84af82007-10-31 18:42:27 +00002021 QualType t = Context.getObjcSelType();
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002022 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
2023}
2024
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002025Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
2026 SourceLocation AtLoc,
2027 SourceLocation ProtoLoc,
2028 SourceLocation LParenLoc,
2029 SourceLocation RParenLoc) {
2030 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
2031 if (!PDecl) {
2032 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
2033 return true;
2034 }
2035
2036 QualType t = GetObjcProtoType(AtLoc);
Fariborz Jahanian20b40e42007-10-18 22:59:23 +00002037 if (t.isNull())
2038 return true;
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002039 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
2040}
Steve Naroff52664182007-10-16 23:12:48 +00002041
2042bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2043 ObjcMethodDecl *Method) {
2044 bool anyIncompatibleArgs = false;
2045
2046 for (unsigned i = 0; i < NumArgs; i++) {
2047 Expr *argExpr = Args[i];
2048 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2049
2050 QualType lhsType = Method->getParamDecl(i)->getType();
2051 QualType rhsType = argExpr->getType();
2052
2053 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2054 if (const ArrayType *ary = lhsType->getAsArrayType())
2055 lhsType = Context.getPointerType(ary->getElementType());
2056 else if (lhsType->isFunctionType())
2057 lhsType = Context.getPointerType(lhsType);
2058
2059 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2060 argExpr);
2061 if (Args[i] != argExpr) // The expression was converted.
2062 Args[i] = argExpr; // Make sure we store the converted expression.
2063 SourceLocation l = argExpr->getLocStart();
2064
2065 // decode the result (notice that AST's are still created for extensions).
2066 switch (result) {
2067 case Compatible:
2068 break;
2069 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +00002070 Diag(l, diag::ext_typecheck_sending_pointer_int,
2071 lhsType.getAsString(), rhsType.getAsString(),
2072 argExpr->getSourceRange());
Steve Naroff52664182007-10-16 23:12:48 +00002073 break;
2074 case IntFromPointer:
2075 Diag(l, diag::ext_typecheck_sending_pointer_int,
2076 lhsType.getAsString(), rhsType.getAsString(),
2077 argExpr->getSourceRange());
2078 break;
2079 case IncompatiblePointer:
2080 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2081 rhsType.getAsString(), lhsType.getAsString(),
2082 argExpr->getSourceRange());
2083 break;
2084 case CompatiblePointerDiscardsQualifiers:
2085 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2086 rhsType.getAsString(), lhsType.getAsString(),
2087 argExpr->getSourceRange());
2088 break;
2089 case Incompatible:
2090 Diag(l, diag::err_typecheck_sending_incompatible,
2091 rhsType.getAsString(), lhsType.getAsString(),
2092 argExpr->getSourceRange());
2093 anyIncompatibleArgs = true;
2094 }
2095 }
2096 return anyIncompatibleArgs;
2097}
2098
Steve Naroff4ed9d662007-09-27 14:38:14 +00002099// ActOnClassMessage - used for both unary and keyword messages.
2100// ArgExprs is optional - if it is present, the number of expressions
2101// is obtained from Sel.getNumArgs().
2102Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002103 Scope *S,
Steve Narofffa465d12007-10-02 20:01:56 +00002104 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002105 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002106{
Steve Narofffa465d12007-10-02 20:01:56 +00002107 assert(receiverName && "missing receiver class name");
Steve Naroffc39ca262007-09-18 23:55:05 +00002108
Steve Naroff52664182007-10-16 23:12:48 +00002109 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002110 ObjcInterfaceDecl* ClassDecl = 0;
2111 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2112 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahanian342f3602007-11-12 20:20:37 +00002113 if (ClassDecl && CurMethodDecl->isInstance()) {
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002114 IdentifierInfo &II = Context.Idents.get("self");
2115 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II,
2116 false);
2117 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2118 superTy = Context.getPointerType(superTy);
2119 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2120 SourceLocation(), ReceiverExpr.Val);
2121
2122 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002123 Args, NumArgs);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002124 }
2125 // class method
2126 if (ClassDecl)
2127 receiverName = ClassDecl->getIdentifier();
2128 }
2129 else
2130 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Narofffa465d12007-10-02 20:01:56 +00002131 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002132 QualType returnType;
Steve Naroff75c4baf2007-11-05 15:27:52 +00002133
2134 // Before we give up, check if the selector is an instance method.
2135 if (!Method)
2136 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002137 if (!Method) {
2138 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2139 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002140 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002141 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002142 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002143 if (Sel.getNumArgs()) {
2144 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2145 return true;
2146 }
Steve Naroff7e461452007-10-16 20:39:36 +00002147 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002148 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
Steve Naroff9f176d12007-11-15 13:05:42 +00002149 lbrac, rbrac, ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002150}
2151
Steve Naroff4ed9d662007-09-27 14:38:14 +00002152// ActOnInstanceMessage - used for both unary and keyword messages.
2153// ArgExprs is optional - if it is present, the number of expressions
2154// is obtained from Sel.getNumArgs().
2155Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroff6cb1d362007-09-28 22:22:11 +00002156 ExprTy *receiver, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002157 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff4ed9d662007-09-27 14:38:14 +00002158{
Steve Naroffc39ca262007-09-18 23:55:05 +00002159 assert(receiver && "missing receiver expression");
2160
Steve Naroff52664182007-10-16 23:12:48 +00002161 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroffc39ca262007-09-18 23:55:05 +00002162 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Narofffa465d12007-10-02 20:01:56 +00002163 QualType receiverType = RExpr->getType();
Steve Naroffee1de132007-10-10 21:53:07 +00002164 QualType returnType;
Steve Naroff1e1c3912007-11-03 16:37:59 +00002165 ObjcMethodDecl *Method;
Steve Naroffee1de132007-10-10 21:53:07 +00002166
Steve Naroff0091d142007-11-11 17:52:25 +00002167 if (receiverType == Context.getObjcIdType() ||
2168 receiverType == Context.getObjcClassType()) {
Steve Naroff1e1c3912007-11-03 16:37:59 +00002169 Method = InstanceMethodPool[Sel].Method;
Steve Naroffd0cfcd02007-11-13 04:10:18 +00002170 // If we didn't find an public method, look for a private one.
2171 if (!Method && CurMethodDecl) {
2172 NamedDecl *impCxt = CurMethodDecl->getMethodContext();
2173 if (ObjcImplementationDecl *IMD =
2174 dyn_cast<ObjcImplementationDecl>(impCxt)) {
2175 if (receiverType == Context.getObjcIdType())
2176 Method = IMD->lookupInstanceMethod(Sel);
2177 else
2178 Method = IMD->lookupClassMethod(Sel);
2179 } else if (ObjcCategoryImplDecl *CID =
2180 dyn_cast<ObjcCategoryImplDecl>(impCxt)) {
2181 if (receiverType == Context.getObjcIdType())
2182 Method = CID->lookupInstanceMethod(Sel);
2183 else
2184 Method = CID->lookupClassMethod(Sel);
2185 }
2186 }
Steve Naroff7e461452007-10-16 20:39:36 +00002187 if (!Method) {
2188 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2189 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002190 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002191 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002192 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002193 if (Sel.getNumArgs())
2194 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2195 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002196 }
Steve Naroffee1de132007-10-10 21:53:07 +00002197 } else {
Chris Lattner71c01112007-10-10 23:42:28 +00002198 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2199 // revisited. how do we get the ClassDecl from the receiver expression?
Steve Naroffee1de132007-10-10 21:53:07 +00002200 while (receiverType->isPointerType()) {
Chris Lattner71c01112007-10-10 23:42:28 +00002201 PointerType *pointerType =
2202 static_cast<PointerType*>(receiverType.getTypePtr());
Steve Naroffee1de132007-10-10 21:53:07 +00002203 receiverType = pointerType->getPointeeType();
2204 }
Chris Lattner71c01112007-10-10 23:42:28 +00002205 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2206 "bad receiver type");
Steve Naroffee1de132007-10-10 21:53:07 +00002207 ObjcInterfaceDecl* ClassDecl = static_cast<ObjcInterfaceType*>(
2208 receiverType.getTypePtr())->getDecl();
Steve Naroff7e461452007-10-16 20:39:36 +00002209 // FIXME: consider using InstanceMethodPool, since it will be faster
2210 // than the following method (which can do *many* linear searches). The
2211 // idea is to add class info to InstanceMethodPool...
Steve Naroff1e1c3912007-11-03 16:37:59 +00002212 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002213 if (!Method) {
Steve Naroffb1c7ad92007-11-11 00:10:47 +00002214 // If we have an implementation in scope, check "private" methods.
2215 if (ObjcImplementationDecl *ImpDecl =
2216 ObjcImplementations[ClassDecl->getIdentifier()])
2217 Method = ImpDecl->lookupInstanceMethod(Sel);
2218 }
2219 if (!Method) {
Steve Naroff7e461452007-10-16 20:39:36 +00002220 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2221 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002222 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002223 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002224 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002225 if (Sel.getNumArgs())
2226 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2227 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002228 }
Steve Narofffa465d12007-10-02 20:01:56 +00002229 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002230 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002231 ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002232}