blob: 336dca716e47818a90b398f57b4af52322881dbf [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
Ted Kremenekddedbe22007-11-29 00:56:49 +0000191 // isExact will be set by GetFloatValue().
192 bool isExact = false;
193
194 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
195 Ty, Tok.getLocation());
196
Chris Lattner1de66eb2007-08-26 03:42:43 +0000197 } else if (!Literal.isIntegerLiteral()) {
198 return ExprResult(true);
199 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000200 QualType t;
201
Neil Booth7421e9c2007-08-29 22:00:19 +0000202 // long long is a C99 feature.
203 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000204 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000205 Diag(Tok.getLocation(), diag::ext_longlong);
206
Chris Lattner4b009652007-07-25 00:24:17 +0000207 // Get the value in the widest-possible width.
208 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
209
210 if (Literal.GetIntegerValue(ResultVal)) {
211 // If this value didn't fit into uintmax_t, warn and force to ull.
212 Diag(Tok.getLocation(), diag::warn_integer_too_large);
213 t = Context.UnsignedLongLongTy;
214 assert(Context.getTypeSize(t, Tok.getLocation()) ==
215 ResultVal.getBitWidth() && "long long is not intmax_t?");
216 } else {
217 // If this value fits into a ULL, try to figure out what else it fits into
218 // according to the rules of C99 6.4.4.1p5.
219
220 // Octal, Hexadecimal, and integers with a U suffix are allowed to
221 // be an unsigned int.
222 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
223
224 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000225 if (!Literal.isLong && !Literal.isLongLong) {
226 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000227 unsigned IntSize = static_cast<unsigned>(
228 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000229 // Does it fit in a unsigned int?
230 if (ResultVal.isIntN(IntSize)) {
231 // Does it fit in a signed int?
232 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
233 t = Context.IntTy;
234 else if (AllowUnsigned)
235 t = Context.UnsignedIntTy;
236 }
237
238 if (!t.isNull())
239 ResultVal.trunc(IntSize);
240 }
241
242 // Are long/unsigned long possibilities?
243 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000244 unsigned LongSize = static_cast<unsigned>(
245 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000246
247 // Does it fit in a unsigned long?
248 if (ResultVal.isIntN(LongSize)) {
249 // Does it fit in a signed long?
250 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
251 t = Context.LongTy;
252 else if (AllowUnsigned)
253 t = Context.UnsignedLongTy;
254 }
255 if (!t.isNull())
256 ResultVal.trunc(LongSize);
257 }
258
259 // Finally, check long long if needed.
260 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000261 unsigned LongLongSize = static_cast<unsigned>(
262 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000263
264 // Does it fit in a unsigned long long?
265 if (ResultVal.isIntN(LongLongSize)) {
266 // Does it fit in a signed long long?
267 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
268 t = Context.LongLongTy;
269 else if (AllowUnsigned)
270 t = Context.UnsignedLongLongTy;
271 }
272 }
273
274 // If we still couldn't decide a type, we probably have something that
275 // does not fit in a signed long long, but has no U suffix.
276 if (t.isNull()) {
277 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
278 t = Context.UnsignedLongLongTy;
279 }
280 }
281
Chris Lattner1de66eb2007-08-26 03:42:43 +0000282 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000283 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000284
285 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
286 if (Literal.isImaginary)
287 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
288
289 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000290}
291
Steve Naroff87d58b42007-09-16 03:34:24 +0000292Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000293 ExprTy *Val) {
294 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000295 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000296 return new ParenExpr(L, R, e);
297}
298
299/// The UsualUnaryConversions() function is *not* called by this routine.
300/// See C99 6.3.2.1p[2-4] for more details.
301QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
302 SourceLocation OpLoc, bool isSizeof) {
303 // C99 6.5.3.4p1:
304 if (isa<FunctionType>(exprType) && isSizeof)
305 // alignof(function) is allowed.
306 Diag(OpLoc, diag::ext_sizeof_function_type);
307 else if (exprType->isVoidType())
308 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
309 else if (exprType->isIncompleteType()) {
310 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
311 diag::err_alignof_incomplete_type,
312 exprType.getAsString());
313 return QualType(); // error
314 }
315 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
316 return Context.getSizeType();
317}
318
319Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000320ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000321 SourceLocation LPLoc, TypeTy *Ty,
322 SourceLocation RPLoc) {
323 // If error parsing type, ignore.
324 if (Ty == 0) return true;
325
326 // Verify that this is a valid expression.
327 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
328
329 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
330
331 if (resultType.isNull())
332 return true;
333 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
334}
335
Chris Lattner5110ad52007-08-24 21:41:10 +0000336QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000337 DefaultFunctionArrayConversion(V);
338
Chris Lattnera16e42d2007-08-26 05:39:26 +0000339 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000340 if (const ComplexType *CT = V->getType()->getAsComplexType())
341 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000342
343 // Otherwise they pass through real integer and floating point types here.
344 if (V->getType()->isArithmeticType())
345 return V->getType();
346
347 // Reject anything else.
348 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
349 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000350}
351
352
Chris Lattner4b009652007-07-25 00:24:17 +0000353
Steve Naroff87d58b42007-09-16 03:34:24 +0000354Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000355 tok::TokenKind Kind,
356 ExprTy *Input) {
357 UnaryOperator::Opcode Opc;
358 switch (Kind) {
359 default: assert(0 && "Unknown unary op!");
360 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
361 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
362 }
363 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
364 if (result.isNull())
365 return true;
366 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
367}
368
369Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000370ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000371 ExprTy *Idx, SourceLocation RLoc) {
372 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
373
374 // Perform default conversions.
375 DefaultFunctionArrayConversion(LHSExp);
376 DefaultFunctionArrayConversion(RHSExp);
377
378 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
379
380 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000381 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000382 // in the subscript position. As a result, we need to derive the array base
383 // and index from the expression types.
384 Expr *BaseExpr, *IndexExpr;
385 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000386 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000387 BaseExpr = LHSExp;
388 IndexExpr = RHSExp;
389 // FIXME: need to deal with const...
390 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000391 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000392 // Handle the uncommon case of "123[Ptr]".
393 BaseExpr = RHSExp;
394 IndexExpr = LHSExp;
395 // FIXME: need to deal with const...
396 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000397 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
398 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000399 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000400
401 // Component access limited to variables (reject vec4.rg[1]).
402 if (!isa<DeclRefExpr>(BaseExpr))
403 return Diag(LLoc, diag::err_ocuvector_component_access,
404 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000405 // FIXME: need to deal with const...
406 ResultType = VTy->getElementType();
407 } else {
408 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
409 RHSExp->getSourceRange());
410 }
411 // C99 6.5.2.1p1
412 if (!IndexExpr->getType()->isIntegerType())
413 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
414 IndexExpr->getSourceRange());
415
416 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
417 // the following check catches trying to index a pointer to a function (e.g.
418 // void (*)(int)). Functions are not objects in C99.
419 if (!ResultType->isObjectType())
420 return Diag(BaseExpr->getLocStart(),
421 diag::err_typecheck_subscript_not_object,
422 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
423
424 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
425}
426
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000427QualType Sema::
428CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
429 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000430 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000431
432 // The vector accessor can't exceed the number of elements.
433 const char *compStr = CompName.getName();
434 if (strlen(compStr) > vecType->getNumElements()) {
435 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
436 baseType.getAsString(), SourceRange(CompLoc));
437 return QualType();
438 }
439 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000440 if (vecType->getPointAccessorIdx(*compStr) != -1) {
441 do
442 compStr++;
443 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
444 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
445 do
446 compStr++;
447 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
448 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
449 do
450 compStr++;
451 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
452 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000453
454 if (*compStr) {
455 // We didn't get to the end of the string. This means the component names
456 // didn't come from the same set *or* we encountered an illegal name.
457 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
458 std::string(compStr,compStr+1), SourceRange(CompLoc));
459 return QualType();
460 }
461 // Each component accessor can't exceed the vector type.
462 compStr = CompName.getName();
463 while (*compStr) {
464 if (vecType->isAccessorWithinNumElements(*compStr))
465 compStr++;
466 else
467 break;
468 }
469 if (*compStr) {
470 // We didn't get to the end of the string. This means a component accessor
471 // exceeds the number of elements in the vector.
472 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
473 baseType.getAsString(), SourceRange(CompLoc));
474 return QualType();
475 }
476 // The component accessor looks fine - now we need to compute the actual type.
477 // The vector type is implied by the component accessor. For example,
478 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
479 unsigned CompSize = strlen(CompName.getName());
480 if (CompSize == 1)
481 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000482
483 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
484 // Now look up the TypeDefDecl from the vector type. Without this,
485 // diagostics look bad. We want OCU vector types to appear built-in.
486 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
487 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
488 return Context.getTypedefType(OCUVectorDecls[i]);
489 }
490 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000491}
492
Chris Lattner4b009652007-07-25 00:24:17 +0000493Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000494ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000495 tok::TokenKind OpKind, SourceLocation MemberLoc,
496 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000497 Expr *BaseExpr = static_cast<Expr *>(Base);
498 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000499
Steve Naroff2cb66382007-07-26 03:11:44 +0000500 QualType BaseType = BaseExpr->getType();
501 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000502
Chris Lattner4b009652007-07-25 00:24:17 +0000503 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000504 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000505 BaseType = PT->getPointeeType();
506 else
507 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
508 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000509 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000510 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000511 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000512 RecordDecl *RDecl = RTy->getDecl();
513 if (RTy->isIncompleteType())
514 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
515 BaseExpr->getSourceRange());
516 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000517 FieldDecl *MemberDecl = RDecl->getMember(&Member);
518 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000519 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
520 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000521 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
522 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000523 // Component access limited to variables (reject vec4.rg.g).
524 if (!isa<DeclRefExpr>(BaseExpr))
525 return Diag(OpLoc, diag::err_ocuvector_component_access,
526 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000527 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
528 if (ret.isNull())
529 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000530 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000531 } else if (BaseType->isObjcInterfaceType()) {
532 ObjcInterfaceDecl *IFace;
533 if (isa<ObjcInterfaceType>(BaseType.getCanonicalType()))
534 IFace = dyn_cast<ObjcInterfaceType>(BaseType)->getDecl();
535 else
536 IFace = dyn_cast<ObjcQualifiedInterfaceType>(BaseType)
537 ->getInterfaceType()->getDecl();
538 ObjcInterfaceDecl *clsDeclared;
539 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
540 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
541 OpKind==tok::arrow);
542 }
543 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
544 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000545}
546
Steve Naroff87d58b42007-09-16 03:34:24 +0000547/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000548/// This provides the location of the left/right parens and a list of comma
549/// locations.
550Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000551ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000552 ExprTy **args, unsigned NumArgsInCall,
553 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
554 Expr *Fn = static_cast<Expr *>(fn);
555 Expr **Args = reinterpret_cast<Expr**>(args);
556 assert(Fn && "no function call expression");
557
558 UsualUnaryConversions(Fn);
559 QualType funcType = Fn->getType();
560
561 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
562 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000563 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000564 if (PT == 0)
565 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
566 SourceRange(Fn->getLocStart(), RParenLoc));
567
Chris Lattner71225142007-07-31 21:27:01 +0000568 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000569 if (funcT == 0)
570 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
571 SourceRange(Fn->getLocStart(), RParenLoc));
572
573 // If a prototype isn't declared, the parser implicitly defines a func decl
574 QualType resultType = funcT->getResultType();
575
576 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
577 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
578 // assignment, to the types of the corresponding parameter, ...
579
580 unsigned NumArgsInProto = proto->getNumArgs();
581 unsigned NumArgsToCheck = NumArgsInCall;
582
583 if (NumArgsInCall < NumArgsInProto)
584 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
585 Fn->getSourceRange());
586 else if (NumArgsInCall > NumArgsInProto) {
587 if (!proto->isVariadic()) {
588 Diag(Args[NumArgsInProto]->getLocStart(),
589 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
590 SourceRange(Args[NumArgsInProto]->getLocStart(),
591 Args[NumArgsInCall-1]->getLocEnd()));
592 }
593 NumArgsToCheck = NumArgsInProto;
594 }
595 // Continue to check argument types (even if we have too few/many args).
596 for (unsigned i = 0; i < NumArgsToCheck; i++) {
597 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000598 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000599
600 QualType lhsType = proto->getArgType(i);
601 QualType rhsType = argExpr->getType();
602
Steve Naroff75644062007-07-25 20:45:33 +0000603 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000604 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000605 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000606 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000607 lhsType = Context.getPointerType(lhsType);
608
609 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
610 argExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000611 if (Args[i] != argExpr) // The expression was converted.
612 Args[i] = argExpr; // Make sure we store the converted expression.
Chris Lattner4b009652007-07-25 00:24:17 +0000613 SourceLocation l = argExpr->getLocStart();
614
615 // decode the result (notice that AST's are still created for extensions).
616 switch (result) {
617 case Compatible:
618 break;
619 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +0000620 Diag(l, diag::ext_typecheck_passing_pointer_int,
621 lhsType.getAsString(), rhsType.getAsString(),
622 Fn->getSourceRange(), argExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000623 break;
624 case IntFromPointer:
625 Diag(l, diag::ext_typecheck_passing_pointer_int,
626 lhsType.getAsString(), rhsType.getAsString(),
627 Fn->getSourceRange(), argExpr->getSourceRange());
628 break;
629 case IncompatiblePointer:
630 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
631 rhsType.getAsString(), lhsType.getAsString(),
632 Fn->getSourceRange(), argExpr->getSourceRange());
633 break;
634 case CompatiblePointerDiscardsQualifiers:
635 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
636 rhsType.getAsString(), lhsType.getAsString(),
637 Fn->getSourceRange(), argExpr->getSourceRange());
638 break;
639 case Incompatible:
640 return Diag(l, diag::err_typecheck_passing_incompatible,
641 rhsType.getAsString(), lhsType.getAsString(),
642 Fn->getSourceRange(), argExpr->getSourceRange());
643 }
644 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000645 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
646 // Promote the arguments (C99 6.5.2.2p7).
647 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
648 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000649 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000650
651 DefaultArgumentPromotion(argExpr);
652 if (Args[i] != argExpr) // The expression was converted.
653 Args[i] = argExpr; // Make sure we store the converted expression.
654 }
655 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
656 // Even if the types checked, bail if the number of arguments don't match.
Chris Lattner4b009652007-07-25 00:24:17 +0000657 return true;
Steve Naroffdb65e052007-08-28 23:30:39 +0000658 }
659 } else if (isa<FunctionTypeNoProto>(funcT)) {
660 // Promote the arguments (C99 6.5.2.2p6).
661 for (unsigned i = 0; i < NumArgsInCall; i++) {
662 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000663 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000664
665 DefaultArgumentPromotion(argExpr);
666 if (Args[i] != argExpr) // The expression was converted.
667 Args[i] = argExpr; // Make sure we store the converted expression.
668 }
Chris Lattner4b009652007-07-25 00:24:17 +0000669 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000670 // Do special checking on direct calls to functions.
671 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
672 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
673 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000674 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
675 NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000676 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000677
Chris Lattner4b009652007-07-25 00:24:17 +0000678 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
679}
680
681Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000682ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000683 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000684 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000685 QualType literalType = QualType::getFromOpaquePtr(Ty);
686 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000687 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000688 Expr *literalExpr = static_cast<Expr*>(InitExpr);
689
690 // FIXME: add semantic analysis (C99 6.5.2.5).
691 return new CompoundLiteralExpr(literalType, literalExpr);
692}
693
694Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000695ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000696 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000697 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000698
Steve Naroff0acc9c92007-09-15 18:49:24 +0000699 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000700 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000701
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000702 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
703 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
704 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000705}
706
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000707bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty)
708{
709 assert(VectorTy->isVectorType() && "Not a vector type!");
710
711 if (Ty->isVectorType() || Ty->isIntegerType()) {
712 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
713 Context.getTypeSize(Ty, SourceLocation()))
714 return Diag(R.getBegin(),
715 Ty->isVectorType() ?
716 diag::err_invalid_conversion_between_vectors :
717 diag::err_invalid_conversion_between_vector_and_integer,
718 VectorTy.getAsString().c_str(),
719 Ty.getAsString().c_str(), R);
720 } else
721 return Diag(R.getBegin(),
722 diag::err_invalid_conversion_between_vector_and_scalar,
723 VectorTy.getAsString().c_str(),
724 Ty.getAsString().c_str(), R);
725
726 return false;
727}
728
Chris Lattner4b009652007-07-25 00:24:17 +0000729Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000730ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000731 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000732 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000733
734 Expr *castExpr = static_cast<Expr*>(Op);
735 QualType castType = QualType::getFromOpaquePtr(Ty);
736
Steve Naroff68adb482007-08-31 00:32:44 +0000737 UsualUnaryConversions(castExpr);
738
Chris Lattner4b009652007-07-25 00:24:17 +0000739 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
740 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000741 if (!castType->isVoidType()) { // Cast to void allows any expr type.
742 if (!castType->isScalarType())
743 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
744 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000745 if (!castExpr->getType()->isScalarType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000746 return Diag(castExpr->getLocStart(),
747 diag::err_typecheck_expect_scalar_operand,
748 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000749
750 if (castExpr->getType()->isVectorType()) {
751 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
752 castExpr->getType(), castType))
753 return true;
754 } else if (castType->isVectorType()) {
755 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
756 castType, castExpr->getType()))
757 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000758 }
Chris Lattner4b009652007-07-25 00:24:17 +0000759 }
760 return new CastExpr(castType, castExpr, LParenLoc);
761}
762
Steve Naroff144667e2007-10-18 05:13:08 +0000763// promoteExprToType - a helper function to ensure we create exactly one
764// ImplicitCastExpr.
765static void promoteExprToType(Expr *&expr, QualType type) {
766 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
767 impCast->setType(type);
768 else
769 expr = new ImplicitCastExpr(type, expr);
770 return;
771}
772
Chris Lattner98a425c2007-11-26 01:40:58 +0000773/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
774/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000775inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
776 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
777 UsualUnaryConversions(cond);
778 UsualUnaryConversions(lex);
779 UsualUnaryConversions(rex);
780 QualType condT = cond->getType();
781 QualType lexT = lex->getType();
782 QualType rexT = rex->getType();
783
784 // first, check the condition.
785 if (!condT->isScalarType()) { // C99 6.5.15p2
786 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
787 condT.getAsString());
788 return QualType();
789 }
790 // now check the two expressions.
791 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
792 UsualArithmeticConversions(lex, rex);
793 return lex->getType();
794 }
Chris Lattner71225142007-07-31 21:27:01 +0000795 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
796 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
Chris Lattner98a425c2007-11-26 01:40:58 +0000797 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner71225142007-07-31 21:27:01 +0000798 return lexT;
799
Chris Lattner4b009652007-07-25 00:24:17 +0000800 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
801 lexT.getAsString(), rexT.getAsString(),
802 lex->getSourceRange(), rex->getSourceRange());
803 return QualType();
804 }
805 }
806 // C99 6.5.15p3
Steve Naroff144667e2007-10-18 05:13:08 +0000807 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
808 promoteExprToType(rex, lexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000809 return lexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000810 }
811 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
812 promoteExprToType(lex, rexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000813 return rexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000814 }
Chris Lattner71225142007-07-31 21:27:01 +0000815 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
816 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
817 // get the "pointed to" types
818 QualType lhptee = LHSPT->getPointeeType();
819 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000820
Chris Lattner71225142007-07-31 21:27:01 +0000821 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
822 if (lhptee->isVoidType() &&
823 (rhptee->isObjectType() || rhptee->isIncompleteType()))
824 return lexT;
825 if (rhptee->isVoidType() &&
826 (lhptee->isObjectType() || lhptee->isIncompleteType()))
827 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000828
Steve Naroff85f0dc52007-10-15 20:41:53 +0000829 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
830 rhptee.getUnqualifiedType())) {
Chris Lattner71225142007-07-31 21:27:01 +0000831 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
832 lexT.getAsString(), rexT.getAsString(),
833 lex->getSourceRange(), rex->getSourceRange());
834 return lexT; // FIXME: this is an _ext - is this return o.k?
835 }
836 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000837 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
838 // differently qualified versions of compatible types, the result type is
839 // a pointer to an appropriately qualified version of the *composite*
840 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000841 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000842 }
Chris Lattner4b009652007-07-25 00:24:17 +0000843 }
Chris Lattner71225142007-07-31 21:27:01 +0000844
Chris Lattner4b009652007-07-25 00:24:17 +0000845 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
846 return lexT;
847
848 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
849 lexT.getAsString(), rexT.getAsString(),
850 lex->getSourceRange(), rex->getSourceRange());
851 return QualType();
852}
853
Steve Naroff87d58b42007-09-16 03:34:24 +0000854/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000855/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000856Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000857 SourceLocation ColonLoc,
858 ExprTy *Cond, ExprTy *LHS,
859 ExprTy *RHS) {
860 Expr *CondExpr = (Expr *) Cond;
861 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000862
863 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
864 // was the condition.
865 bool isLHSNull = LHSExpr == 0;
866 if (isLHSNull)
867 LHSExpr = CondExpr;
868
Chris Lattner4b009652007-07-25 00:24:17 +0000869 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
870 RHSExpr, QuestionLoc);
871 if (result.isNull())
872 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000873 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
874 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000875}
876
Steve Naroffdb65e052007-08-28 23:30:39 +0000877/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
878/// do not have a prototype. Integer promotions are performed on each
879/// argument, and arguments that have type float are promoted to double.
880void Sema::DefaultArgumentPromotion(Expr *&expr) {
881 QualType t = expr->getType();
882 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
883
884 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
885 promoteExprToType(expr, Context.IntTy);
886 if (t == Context.FloatTy)
887 promoteExprToType(expr, Context.DoubleTy);
888}
889
Chris Lattner4b009652007-07-25 00:24:17 +0000890/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
891void Sema::DefaultFunctionArrayConversion(Expr *&e) {
892 QualType t = e->getType();
893 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
894
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000895 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000896 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
897 t = e->getType();
898 }
899 if (t->isFunctionType())
900 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000901 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000902 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
903}
904
905/// UsualUnaryConversion - Performs various conversions that are common to most
906/// operators (C99 6.3). The conversions of array and function types are
907/// sometimes surpressed. For example, the array->pointer conversion doesn't
908/// apply if the array is an argument to the sizeof or address (&) operators.
909/// In these instances, this routine should *not* be called.
910void Sema::UsualUnaryConversions(Expr *&expr) {
911 QualType t = expr->getType();
912 assert(!t.isNull() && "UsualUnaryConversions - missing type");
913
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000914 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000915 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
916 t = expr->getType();
917 }
918 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
919 promoteExprToType(expr, Context.IntTy);
920 else
921 DefaultFunctionArrayConversion(expr);
922}
923
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000924/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000925/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
926/// routine returns the first non-arithmetic type found. The client is
927/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000928QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
929 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000930 if (!isCompAssign) {
931 UsualUnaryConversions(lhsExpr);
932 UsualUnaryConversions(rhsExpr);
933 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000934 // For conversion purposes, we ignore any qualifiers.
935 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000936 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
937 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000938
939 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000940 if (lhs == rhs)
941 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000942
943 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
944 // The caller can deal with this (e.g. pointer + int).
945 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000946 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000947
948 // At this point, we have two different arithmetic types.
949
950 // Handle complex types first (C99 6.3.1.8p1).
951 if (lhs->isComplexType() || rhs->isComplexType()) {
952 // if we have an integer operand, the result is the complex type.
953 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000954 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
955 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000956 }
957 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000958 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
959 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000960 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000961 // This handles complex/complex, complex/float, or float/complex.
962 // When both operands are complex, the shorter operand is converted to the
963 // type of the longer, and that is the type of the result. This corresponds
964 // to what is done when combining two real floating-point operands.
965 // The fun begins when size promotion occur across type domains.
966 // From H&S 6.3.4: When one operand is complex and the other is a real
967 // floating-point type, the less precise type is converted, within it's
968 // real or complex domain, to the precision of the other type. For example,
969 // when combining a "long double" with a "double _Complex", the
970 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000971 int result = Context.compareFloatingType(lhs, rhs);
972
973 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000974 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
975 if (!isCompAssign)
976 promoteExprToType(rhsExpr, rhs);
977 } else if (result < 0) { // The right side is bigger, convert lhs.
978 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
979 if (!isCompAssign)
980 promoteExprToType(lhsExpr, lhs);
981 }
982 // At this point, lhs and rhs have the same rank/size. Now, make sure the
983 // domains match. This is a requirement for our implementation, C99
984 // does not require this promotion.
985 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
986 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000987 if (!isCompAssign)
988 promoteExprToType(lhsExpr, rhs);
989 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000990 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000991 if (!isCompAssign)
992 promoteExprToType(rhsExpr, lhs);
993 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000994 }
Chris Lattner4b009652007-07-25 00:24:17 +0000995 }
Steve Naroff3b6157f2007-08-27 21:43:43 +0000996 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +0000997 }
998 // Now handle "real" floating types (i.e. float, double, long double).
999 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1000 // if we have an integer operand, the result is the real floating type.
1001 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001002 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1003 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001004 }
1005 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001006 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
1007 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001008 }
1009 // We have two real floating types, float/complex combos were handled above.
1010 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +00001011 int result = Context.compareFloatingType(lhs, rhs);
1012
1013 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001014 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1015 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001016 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001017 if (result < 0) { // convert the lhs
1018 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1019 return rhs;
1020 }
1021 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001022 }
1023 // Finally, we have two differing integer types.
1024 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001025 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1026 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001027 }
Steve Naroff8f708362007-08-24 19:07:16 +00001028 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1029 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001030}
1031
1032// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1033// being closely modeled after the C99 spec:-). The odd characteristic of this
1034// routine is it effectively iqnores the qualifiers on the top level pointee.
1035// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1036// FIXME: add a couple examples in this comment.
1037Sema::AssignmentCheckResult
1038Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1039 QualType lhptee, rhptee;
1040
1041 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001042 lhptee = lhsType->getAsPointerType()->getPointeeType();
1043 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001044
1045 // make sure we operate on the canonical type
1046 lhptee = lhptee.getCanonicalType();
1047 rhptee = rhptee.getCanonicalType();
1048
1049 AssignmentCheckResult r = Compatible;
1050
1051 // C99 6.5.16.1p1: This following citation is common to constraints
1052 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1053 // qualifiers of the type *pointed to* by the right;
1054 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1055 rhptee.getQualifiers())
1056 r = CompatiblePointerDiscardsQualifiers;
1057
1058 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1059 // incomplete type and the other is a pointer to a qualified or unqualified
1060 // version of void...
1061 if (lhptee.getUnqualifiedType()->isVoidType() &&
1062 (rhptee->isObjectType() || rhptee->isIncompleteType()))
1063 ;
1064 else if (rhptee.getUnqualifiedType()->isVoidType() &&
1065 (lhptee->isObjectType() || lhptee->isIncompleteType()))
1066 ;
1067 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1068 // unqualified versions of compatible types, ...
Steve Naroff85f0dc52007-10-15 20:41:53 +00001069 else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1070 rhptee.getUnqualifiedType()))
Chris Lattner4b009652007-07-25 00:24:17 +00001071 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1072 return r;
1073}
1074
1075/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1076/// has code to accommodate several GCC extensions when type checking
1077/// pointers. Here are some objectionable examples that GCC considers warnings:
1078///
1079/// int a, *pint;
1080/// short *pshort;
1081/// struct foo *pfoo;
1082///
1083/// pint = pshort; // warning: assignment from incompatible pointer type
1084/// a = pint; // warning: assignment makes integer from pointer without a cast
1085/// pint = a; // warning: assignment makes pointer from integer without a cast
1086/// pint = pfoo; // warning: assignment from incompatible pointer type
1087///
1088/// As a result, the code for dealing with pointers is more complex than the
1089/// C99 spec dictates.
1090/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1091///
1092Sema::AssignmentCheckResult
1093Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Steve Naroffeed76842007-11-13 00:31:42 +00001094 if (lhsType.getCanonicalType().getUnqualifiedType() ==
1095 rhsType.getCanonicalType().getUnqualifiedType())
Chris Lattnera703c2e2007-10-29 05:15:40 +00001096 return Compatible; // common case, fast path...
Chris Lattner4b009652007-07-25 00:24:17 +00001097
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001098 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001099 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001100 return Compatible;
1101 } else if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001102 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1103 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1104 return Incompatible;
1105 }
1106 return Compatible;
1107 } else if (lhsType->isPointerType()) {
1108 if (rhsType->isIntegerType())
1109 return PointerFromInt;
1110
1111 if (rhsType->isPointerType())
1112 return CheckPointerTypesForAssignment(lhsType, rhsType);
1113 } else if (rhsType->isPointerType()) {
1114 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1115 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1116 return IntFromPointer;
1117
1118 if (lhsType->isPointerType())
1119 return CheckPointerTypesForAssignment(lhsType, rhsType);
1120 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001121 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001122 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001123 }
1124 return Incompatible;
1125}
1126
1127Sema::AssignmentCheckResult
1128Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001129 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1130 // a null pointer constant.
1131 if (lhsType->isPointerType() && rExpr->isNullPointerConstant(Context)) {
1132 promoteExprToType(rExpr, lhsType);
1133 return Compatible;
1134 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001135 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001136 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001137 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001138 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001139 //
1140 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1141 // are better understood.
1142 if (!lhsType->isReferenceType())
1143 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001144
1145 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +00001146
Steve Naroff0f32f432007-08-24 22:33:52 +00001147 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1148
1149 // C99 6.5.16.1p2: The value of the right operand is converted to the
1150 // type of the assignment expression.
1151 if (rExpr->getType() != lhsType)
1152 promoteExprToType(rExpr, lhsType);
1153 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001154}
1155
1156Sema::AssignmentCheckResult
1157Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1158 return CheckAssignmentConstraints(lhsType, rhsType);
1159}
1160
1161inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1162 Diag(loc, diag::err_typecheck_invalid_operands,
1163 lex->getType().getAsString(), rex->getType().getAsString(),
1164 lex->getSourceRange(), rex->getSourceRange());
1165}
1166
1167inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1168 Expr *&rex) {
1169 QualType lhsType = lex->getType(), rhsType = rex->getType();
1170
1171 // make sure the vector types are identical.
1172 if (lhsType == rhsType)
1173 return lhsType;
1174 // You cannot convert between vector values of different size.
1175 Diag(loc, diag::err_typecheck_vector_not_convertable,
1176 lex->getType().getAsString(), rex->getType().getAsString(),
1177 lex->getSourceRange(), rex->getSourceRange());
1178 return QualType();
1179}
1180
1181inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001182 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001183{
1184 QualType lhsType = lex->getType(), rhsType = rex->getType();
1185
1186 if (lhsType->isVectorType() || rhsType->isVectorType())
1187 return CheckVectorOperands(loc, lex, rex);
1188
Steve Naroff8f708362007-08-24 19:07:16 +00001189 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001190
Chris Lattner4b009652007-07-25 00:24:17 +00001191 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001192 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001193 InvalidOperands(loc, lex, rex);
1194 return QualType();
1195}
1196
1197inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001198 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001199{
1200 QualType lhsType = lex->getType(), rhsType = rex->getType();
1201
Steve Naroff8f708362007-08-24 19:07:16 +00001202 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001203
Chris Lattner4b009652007-07-25 00:24:17 +00001204 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001205 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001206 InvalidOperands(loc, lex, rex);
1207 return QualType();
1208}
1209
1210inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001211 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001212{
1213 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1214 return CheckVectorOperands(loc, lex, rex);
1215
Steve Naroff8f708362007-08-24 19:07:16 +00001216 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001217
1218 // handle the common case first (both operands are arithmetic).
1219 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001220 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001221
1222 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1223 return lex->getType();
1224 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1225 return rex->getType();
1226 InvalidOperands(loc, lex, rex);
1227 return QualType();
1228}
1229
1230inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001231 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001232{
1233 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1234 return CheckVectorOperands(loc, lex, rex);
1235
Steve Naroff8f708362007-08-24 19:07:16 +00001236 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001237
1238 // handle the common case first (both operands are arithmetic).
1239 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001240 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001241
1242 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001243 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001244 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1245 return Context.getPointerDiffType();
1246 InvalidOperands(loc, lex, rex);
1247 return QualType();
1248}
1249
1250inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001251 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001252{
1253 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1254 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001255 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001256
1257 // handle the common case first (both operands are arithmetic).
1258 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001259 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001260 InvalidOperands(loc, lex, rex);
1261 return QualType();
1262}
1263
Chris Lattner254f3bc2007-08-26 01:18:55 +00001264inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1265 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001266{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001267 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001268 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1269 UsualArithmeticConversions(lex, rex);
1270 else {
1271 UsualUnaryConversions(lex);
1272 UsualUnaryConversions(rex);
1273 }
Chris Lattner4b009652007-07-25 00:24:17 +00001274 QualType lType = lex->getType();
1275 QualType rType = rex->getType();
1276
Ted Kremenek486509e2007-10-29 17:13:39 +00001277 // For non-floating point types, check for self-comparisons of the form
1278 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1279 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001280 if (!lType->isFloatingType()) {
1281 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1282 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1283 if (DRL->getDecl() == DRR->getDecl())
1284 Diag(loc, diag::warn_selfcomparison);
1285 }
1286
Chris Lattner254f3bc2007-08-26 01:18:55 +00001287 if (isRelational) {
1288 if (lType->isRealType() && rType->isRealType())
1289 return Context.IntTy;
1290 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001291 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001292 if (lType->isFloatingType()) {
1293 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001294 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001295 }
1296
Chris Lattner254f3bc2007-08-26 01:18:55 +00001297 if (lType->isArithmeticType() && rType->isArithmeticType())
1298 return Context.IntTy;
1299 }
Chris Lattner4b009652007-07-25 00:24:17 +00001300
Chris Lattner22be8422007-08-26 01:10:14 +00001301 bool LHSIsNull = lex->isNullPointerConstant(Context);
1302 bool RHSIsNull = rex->isNullPointerConstant(Context);
1303
Chris Lattner254f3bc2007-08-26 01:18:55 +00001304 // All of the following pointer related warnings are GCC extensions, except
1305 // when handling null pointer constants. One day, we can consider making them
1306 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001307 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff3b435622007-11-13 14:57:38 +00001308
1309 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1310 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1311 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroff85f0dc52007-10-15 20:41:53 +00001312 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1313 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001314 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1315 lType.getAsString(), rType.getAsString(),
1316 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001317 }
Chris Lattner22be8422007-08-26 01:10:14 +00001318 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001319 return Context.IntTy;
1320 }
1321 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001322 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001323 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1324 lType.getAsString(), rType.getAsString(),
1325 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001326 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001327 return Context.IntTy;
1328 }
1329 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001330 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001331 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1332 lType.getAsString(), rType.getAsString(),
1333 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001334 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001335 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001336 }
1337 InvalidOperands(loc, lex, rex);
1338 return QualType();
1339}
1340
Chris Lattner4b009652007-07-25 00:24:17 +00001341inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001342 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001343{
1344 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1345 return CheckVectorOperands(loc, lex, rex);
1346
Steve Naroff8f708362007-08-24 19:07:16 +00001347 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001348
1349 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001350 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001351 InvalidOperands(loc, lex, rex);
1352 return QualType();
1353}
1354
1355inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1356 Expr *&lex, Expr *&rex, SourceLocation loc)
1357{
1358 UsualUnaryConversions(lex);
1359 UsualUnaryConversions(rex);
1360
1361 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1362 return Context.IntTy;
1363 InvalidOperands(loc, lex, rex);
1364 return QualType();
1365}
1366
1367inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001368 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001369{
1370 QualType lhsType = lex->getType();
1371 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1372 bool hadError = false;
1373 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1374
1375 switch (mlval) { // C99 6.5.16p2
1376 case Expr::MLV_Valid:
1377 break;
1378 case Expr::MLV_ConstQualified:
1379 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1380 hadError = true;
1381 break;
1382 case Expr::MLV_ArrayType:
1383 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1384 lhsType.getAsString(), lex->getSourceRange());
1385 return QualType();
1386 case Expr::MLV_NotObjectType:
1387 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1388 lhsType.getAsString(), lex->getSourceRange());
1389 return QualType();
1390 case Expr::MLV_InvalidExpression:
1391 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1392 lex->getSourceRange());
1393 return QualType();
1394 case Expr::MLV_IncompleteType:
1395 case Expr::MLV_IncompleteVoidType:
1396 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1397 lhsType.getAsString(), lex->getSourceRange());
1398 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001399 case Expr::MLV_DuplicateVectorComponents:
1400 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1401 lex->getSourceRange());
1402 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001403 }
1404 AssignmentCheckResult result;
1405
1406 if (compoundType.isNull())
1407 result = CheckSingleAssignmentConstraints(lhsType, rex);
1408 else
1409 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001410
Chris Lattner4b009652007-07-25 00:24:17 +00001411 // decode the result (notice that extensions still return a type).
1412 switch (result) {
1413 case Compatible:
1414 break;
1415 case Incompatible:
1416 Diag(loc, diag::err_typecheck_assign_incompatible,
1417 lhsType.getAsString(), rhsType.getAsString(),
1418 lex->getSourceRange(), rex->getSourceRange());
1419 hadError = true;
1420 break;
1421 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +00001422 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1423 lhsType.getAsString(), rhsType.getAsString(),
1424 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001425 break;
1426 case IntFromPointer:
1427 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1428 lhsType.getAsString(), rhsType.getAsString(),
1429 lex->getSourceRange(), rex->getSourceRange());
1430 break;
1431 case IncompatiblePointer:
1432 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1433 lhsType.getAsString(), rhsType.getAsString(),
1434 lex->getSourceRange(), rex->getSourceRange());
1435 break;
1436 case CompatiblePointerDiscardsQualifiers:
1437 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1438 lhsType.getAsString(), rhsType.getAsString(),
1439 lex->getSourceRange(), rex->getSourceRange());
1440 break;
1441 }
1442 // C99 6.5.16p3: The type of an assignment expression is the type of the
1443 // left operand unless the left operand has qualified type, in which case
1444 // it is the unqualified version of the type of the left operand.
1445 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1446 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001447 // C++ 5.17p1: the type of the assignment expression is that of its left
1448 // oprdu.
Chris Lattner4b009652007-07-25 00:24:17 +00001449 return hadError ? QualType() : lhsType.getUnqualifiedType();
1450}
1451
1452inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1453 Expr *&lex, Expr *&rex, SourceLocation loc) {
1454 UsualUnaryConversions(rex);
1455 return rex->getType();
1456}
1457
1458/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1459/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1460QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1461 QualType resType = op->getType();
1462 assert(!resType.isNull() && "no type for increment/decrement expression");
1463
Steve Naroffd30e1932007-08-24 17:20:07 +00001464 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001465 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001466 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1467 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1468 resType.getAsString(), op->getSourceRange());
1469 return QualType();
1470 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001471 } else if (!resType->isRealType()) {
1472 if (resType->isComplexType())
1473 // C99 does not support ++/-- on complex types.
1474 Diag(OpLoc, diag::ext_integer_increment_complex,
1475 resType.getAsString(), op->getSourceRange());
1476 else {
1477 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1478 resType.getAsString(), op->getSourceRange());
1479 return QualType();
1480 }
Chris Lattner4b009652007-07-25 00:24:17 +00001481 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001482 // At this point, we know we have a real, complex or pointer type.
1483 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001484 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1485 if (mlval != Expr::MLV_Valid) {
1486 // FIXME: emit a more precise diagnostic...
1487 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1488 op->getSourceRange());
1489 return QualType();
1490 }
1491 return resType;
1492}
1493
1494/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1495/// This routine allows us to typecheck complex/recursive expressions
1496/// where the declaration is needed for type checking. Here are some
1497/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1498static Decl *getPrimaryDeclaration(Expr *e) {
1499 switch (e->getStmtClass()) {
1500 case Stmt::DeclRefExprClass:
1501 return cast<DeclRefExpr>(e)->getDecl();
1502 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001503 // Fields cannot be declared with a 'register' storage class.
1504 // &X->f is always ok, even if X is declared register.
1505 if (cast<MemberExpr>(e)->isArrow())
1506 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001507 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1508 case Stmt::ArraySubscriptExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001509 // &X[4] and &4[X] is invalid if X is invalid.
Chris Lattner4b009652007-07-25 00:24:17 +00001510 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +00001511 case Stmt::UnaryOperatorClass:
1512 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1513 case Stmt::ParenExprClass:
1514 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001515 case Stmt::ImplicitCastExprClass:
1516 // &X[4] when X is an array, has an implicit cast from array to pointer.
1517 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001518 default:
1519 return 0;
1520 }
1521}
1522
1523/// CheckAddressOfOperand - The operand of & must be either a function
1524/// designator or an lvalue designating an object. If it is an lvalue, the
1525/// object cannot be declared with storage class register or be a bit field.
1526/// Note: The usual conversions are *not* applied to the operand of the &
1527/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1528QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1529 Decl *dcl = getPrimaryDeclaration(op);
1530 Expr::isLvalueResult lval = op->isLvalue();
1531
1532 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001533 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1534 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001535 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1536 op->getSourceRange());
1537 return QualType();
1538 }
1539 } else if (dcl) {
1540 // We have an lvalue with a decl. Make sure the decl is not declared
1541 // with the register storage-class specifier.
1542 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1543 if (vd->getStorageClass() == VarDecl::Register) {
1544 Diag(OpLoc, diag::err_typecheck_address_of_register,
1545 op->getSourceRange());
1546 return QualType();
1547 }
1548 } else
1549 assert(0 && "Unknown/unexpected decl type");
1550
1551 // FIXME: add check for bitfields!
1552 }
1553 // If the operand has type "type", the result has type "pointer to type".
1554 return Context.getPointerType(op->getType());
1555}
1556
1557QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1558 UsualUnaryConversions(op);
1559 QualType qType = op->getType();
1560
Chris Lattner7931f4a2007-07-31 16:53:04 +00001561 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001562 QualType ptype = PT->getPointeeType();
1563 // C99 6.5.3.2p4. "if it points to an object,...".
1564 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1565 // GCC compat: special case 'void *' (treat as warning).
1566 if (ptype->isVoidType()) {
1567 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1568 qType.getAsString(), op->getSourceRange());
1569 } else {
1570 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1571 ptype.getAsString(), op->getSourceRange());
1572 return QualType();
1573 }
1574 }
1575 return ptype;
1576 }
1577 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1578 qType.getAsString(), op->getSourceRange());
1579 return QualType();
1580}
1581
1582static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1583 tok::TokenKind Kind) {
1584 BinaryOperator::Opcode Opc;
1585 switch (Kind) {
1586 default: assert(0 && "Unknown binop!");
1587 case tok::star: Opc = BinaryOperator::Mul; break;
1588 case tok::slash: Opc = BinaryOperator::Div; break;
1589 case tok::percent: Opc = BinaryOperator::Rem; break;
1590 case tok::plus: Opc = BinaryOperator::Add; break;
1591 case tok::minus: Opc = BinaryOperator::Sub; break;
1592 case tok::lessless: Opc = BinaryOperator::Shl; break;
1593 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1594 case tok::lessequal: Opc = BinaryOperator::LE; break;
1595 case tok::less: Opc = BinaryOperator::LT; break;
1596 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1597 case tok::greater: Opc = BinaryOperator::GT; break;
1598 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1599 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1600 case tok::amp: Opc = BinaryOperator::And; break;
1601 case tok::caret: Opc = BinaryOperator::Xor; break;
1602 case tok::pipe: Opc = BinaryOperator::Or; break;
1603 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1604 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1605 case tok::equal: Opc = BinaryOperator::Assign; break;
1606 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1607 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1608 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1609 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1610 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1611 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1612 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1613 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1614 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1615 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1616 case tok::comma: Opc = BinaryOperator::Comma; break;
1617 }
1618 return Opc;
1619}
1620
1621static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1622 tok::TokenKind Kind) {
1623 UnaryOperator::Opcode Opc;
1624 switch (Kind) {
1625 default: assert(0 && "Unknown unary op!");
1626 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1627 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1628 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1629 case tok::star: Opc = UnaryOperator::Deref; break;
1630 case tok::plus: Opc = UnaryOperator::Plus; break;
1631 case tok::minus: Opc = UnaryOperator::Minus; break;
1632 case tok::tilde: Opc = UnaryOperator::Not; break;
1633 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1634 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1635 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1636 case tok::kw___real: Opc = UnaryOperator::Real; break;
1637 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1638 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1639 }
1640 return Opc;
1641}
1642
1643// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001644Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001645 ExprTy *LHS, ExprTy *RHS) {
1646 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1647 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1648
Steve Naroff87d58b42007-09-16 03:34:24 +00001649 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1650 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001651
1652 QualType ResultTy; // Result type of the binary operator.
1653 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1654
1655 switch (Opc) {
1656 default:
1657 assert(0 && "Unknown binary expr!");
1658 case BinaryOperator::Assign:
1659 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1660 break;
1661 case BinaryOperator::Mul:
1662 case BinaryOperator::Div:
1663 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1664 break;
1665 case BinaryOperator::Rem:
1666 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1667 break;
1668 case BinaryOperator::Add:
1669 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1670 break;
1671 case BinaryOperator::Sub:
1672 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1673 break;
1674 case BinaryOperator::Shl:
1675 case BinaryOperator::Shr:
1676 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1677 break;
1678 case BinaryOperator::LE:
1679 case BinaryOperator::LT:
1680 case BinaryOperator::GE:
1681 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001682 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001683 break;
1684 case BinaryOperator::EQ:
1685 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001686 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001687 break;
1688 case BinaryOperator::And:
1689 case BinaryOperator::Xor:
1690 case BinaryOperator::Or:
1691 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1692 break;
1693 case BinaryOperator::LAnd:
1694 case BinaryOperator::LOr:
1695 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1696 break;
1697 case BinaryOperator::MulAssign:
1698 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001699 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001700 if (!CompTy.isNull())
1701 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1702 break;
1703 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001704 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001705 if (!CompTy.isNull())
1706 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1707 break;
1708 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001709 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001710 if (!CompTy.isNull())
1711 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1712 break;
1713 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001714 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001715 if (!CompTy.isNull())
1716 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1717 break;
1718 case BinaryOperator::ShlAssign:
1719 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001720 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001721 if (!CompTy.isNull())
1722 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1723 break;
1724 case BinaryOperator::AndAssign:
1725 case BinaryOperator::XorAssign:
1726 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001727 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001728 if (!CompTy.isNull())
1729 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1730 break;
1731 case BinaryOperator::Comma:
1732 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1733 break;
1734 }
1735 if (ResultTy.isNull())
1736 return true;
1737 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001738 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001739 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001740 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001741}
1742
1743// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001744Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001745 ExprTy *input) {
1746 Expr *Input = (Expr*)input;
1747 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1748 QualType resultType;
1749 switch (Opc) {
1750 default:
1751 assert(0 && "Unimplemented unary expr!");
1752 case UnaryOperator::PreInc:
1753 case UnaryOperator::PreDec:
1754 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1755 break;
1756 case UnaryOperator::AddrOf:
1757 resultType = CheckAddressOfOperand(Input, OpLoc);
1758 break;
1759 case UnaryOperator::Deref:
1760 resultType = CheckIndirectionOperand(Input, OpLoc);
1761 break;
1762 case UnaryOperator::Plus:
1763 case UnaryOperator::Minus:
1764 UsualUnaryConversions(Input);
1765 resultType = Input->getType();
1766 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1767 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1768 resultType.getAsString());
1769 break;
1770 case UnaryOperator::Not: // bitwise complement
1771 UsualUnaryConversions(Input);
1772 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001773 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1774 if (!resultType->isIntegerType()) {
1775 if (resultType->isComplexType())
1776 // C99 does not support '~' for complex conjugation.
1777 Diag(OpLoc, diag::ext_integer_complement_complex,
1778 resultType.getAsString());
1779 else
1780 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1781 resultType.getAsString());
1782 }
Chris Lattner4b009652007-07-25 00:24:17 +00001783 break;
1784 case UnaryOperator::LNot: // logical negation
1785 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1786 DefaultFunctionArrayConversion(Input);
1787 resultType = Input->getType();
1788 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1789 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1790 resultType.getAsString());
1791 // LNot always has type int. C99 6.5.3.3p5.
1792 resultType = Context.IntTy;
1793 break;
1794 case UnaryOperator::SizeOf:
1795 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1796 break;
1797 case UnaryOperator::AlignOf:
1798 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1799 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001800 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001801 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001802 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001803 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001804 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001805 resultType = Input->getType();
1806 break;
1807 }
1808 if (resultType.isNull())
1809 return true;
1810 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1811}
1812
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001813/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1814Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001815 SourceLocation LabLoc,
1816 IdentifierInfo *LabelII) {
1817 // Look up the record for this label identifier.
1818 LabelStmt *&LabelDecl = LabelMap[LabelII];
1819
1820 // If we haven't seen this label yet, create a forward reference.
1821 if (LabelDecl == 0)
1822 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1823
1824 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001825 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1826 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001827}
1828
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001829Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00001830 SourceLocation RPLoc) { // "({..})"
1831 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1832 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1833 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1834
1835 // FIXME: there are a variety of strange constraints to enforce here, for
1836 // example, it is not possible to goto into a stmt expression apparently.
1837 // More semantic analysis is needed.
1838
1839 // FIXME: the last statement in the compount stmt has its value used. We
1840 // should not warn about it being unused.
1841
1842 // If there are sub stmts in the compound stmt, take the type of the last one
1843 // as the type of the stmtexpr.
1844 QualType Ty = Context.VoidTy;
1845
1846 if (!Compound->body_empty())
1847 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1848 Ty = LastExpr->getType();
1849
1850 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1851}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001852
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001853Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001854 SourceLocation TypeLoc,
1855 TypeTy *argty,
1856 OffsetOfComponent *CompPtr,
1857 unsigned NumComponents,
1858 SourceLocation RPLoc) {
1859 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1860 assert(!ArgTy.isNull() && "Missing type argument!");
1861
1862 // We must have at least one component that refers to the type, and the first
1863 // one is known to be a field designator. Verify that the ArgTy represents
1864 // a struct/union/class.
1865 if (!ArgTy->isRecordType())
1866 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1867
1868 // Otherwise, create a compound literal expression as the base, and
1869 // iteratively process the offsetof designators.
1870 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1871
Chris Lattnerb37522e2007-08-31 21:49:13 +00001872 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1873 // GCC extension, diagnose them.
1874 if (NumComponents != 1)
1875 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1876 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1877
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001878 for (unsigned i = 0; i != NumComponents; ++i) {
1879 const OffsetOfComponent &OC = CompPtr[i];
1880 if (OC.isBrackets) {
1881 // Offset of an array sub-field. TODO: Should we allow vector elements?
1882 const ArrayType *AT = Res->getType()->getAsArrayType();
1883 if (!AT) {
1884 delete Res;
1885 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1886 Res->getType().getAsString());
1887 }
1888
Chris Lattner2af6a802007-08-30 17:59:59 +00001889 // FIXME: C++: Verify that operator[] isn't overloaded.
1890
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001891 // C99 6.5.2.1p1
1892 Expr *Idx = static_cast<Expr*>(OC.U.E);
1893 if (!Idx->getType()->isIntegerType())
1894 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1895 Idx->getSourceRange());
1896
1897 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1898 continue;
1899 }
1900
1901 const RecordType *RC = Res->getType()->getAsRecordType();
1902 if (!RC) {
1903 delete Res;
1904 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1905 Res->getType().getAsString());
1906 }
1907
1908 // Get the decl corresponding to this.
1909 RecordDecl *RD = RC->getDecl();
1910 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1911 if (!MemberDecl)
1912 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1913 OC.U.IdentInfo->getName(),
1914 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00001915
1916 // FIXME: C++: Verify that MemberDecl isn't a static field.
1917 // FIXME: Verify that MemberDecl isn't a bitfield.
1918
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001919 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1920 }
1921
1922 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1923 BuiltinLoc);
1924}
1925
1926
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001927Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001928 TypeTy *arg1, TypeTy *arg2,
1929 SourceLocation RPLoc) {
1930 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1931 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1932
1933 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1934
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001935 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001936}
1937
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001938Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00001939 ExprTy *expr1, ExprTy *expr2,
1940 SourceLocation RPLoc) {
1941 Expr *CondExpr = static_cast<Expr*>(cond);
1942 Expr *LHSExpr = static_cast<Expr*>(expr1);
1943 Expr *RHSExpr = static_cast<Expr*>(expr2);
1944
1945 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1946
1947 // The conditional expression is required to be a constant expression.
1948 llvm::APSInt condEval(32);
1949 SourceLocation ExpLoc;
1950 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1951 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1952 CondExpr->getSourceRange());
1953
1954 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1955 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1956 RHSExpr->getType();
1957 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1958}
1959
Anders Carlsson36760332007-10-15 20:28:48 +00001960Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
1961 ExprTy *expr, TypeTy *type,
1962 SourceLocation RPLoc)
1963{
1964 Expr *E = static_cast<Expr*>(expr);
1965 QualType T = QualType::getFromOpaquePtr(type);
1966
1967 InitBuiltinVaListType();
1968
1969 Sema::AssignmentCheckResult result;
1970
1971 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
1972 E->getType());
1973 if (result != Compatible)
1974 return Diag(E->getLocStart(),
1975 diag::err_first_argument_to_va_arg_not_of_type_va_list,
1976 E->getType().getAsString(),
1977 E->getSourceRange());
1978
1979 // FIXME: Warn if a non-POD type is passed in.
1980
1981 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
1982}
1983
Anders Carlssona66cad42007-08-21 17:43:55 +00001984// TODO: Move this to SemaObjC.cpp
Steve Naroff0add5d22007-11-03 11:27:19 +00001985Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation AtLoc,
1986 ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00001987 StringLiteral* S = static_cast<StringLiteral *>(string);
1988
1989 if (CheckBuiltinCFStringArgument(S))
1990 return true;
1991
Steve Narofff2e30312007-10-15 23:35:17 +00001992 if (Context.getObjcConstantStringInterface().isNull()) {
1993 // Initialize the constant string interface lazily. This assumes
1994 // the NSConstantString interface is seen in this translation unit.
1995 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
1996 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
1997 SourceLocation(), TUScope);
Steve Naroff134c3502007-10-16 00:00:18 +00001998 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff96f136d2007-10-18 23:53:51 +00001999 if (!strIFace)
2000 return Diag(S->getLocStart(), diag::err_undef_interface,
2001 NSIdent->getName());
Steve Naroff134c3502007-10-16 00:00:18 +00002002 Context.setObjcConstantStringInterface(strIFace);
Steve Narofff2e30312007-10-15 23:35:17 +00002003 }
2004 QualType t = Context.getObjcConstantStringInterface();
Anders Carlssona66cad42007-08-21 17:43:55 +00002005 t = Context.getPointerType(t);
Steve Naroff0add5d22007-11-03 11:27:19 +00002006 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlssona66cad42007-08-21 17:43:55 +00002007}
Anders Carlsson8be1d402007-08-22 15:14:15 +00002008
2009Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattnercfd61c82007-10-16 22:51:17 +00002010 SourceLocation EncodeLoc,
Anders Carlsson8be1d402007-08-22 15:14:15 +00002011 SourceLocation LParenLoc,
2012 TypeTy *Ty,
2013 SourceLocation RParenLoc) {
2014 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
2015
2016 QualType t = Context.getPointerType(Context.CharTy);
2017 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
2018}
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002019
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002020Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
2021 SourceLocation AtLoc,
Fariborz Jahanian957448a2007-10-16 23:21:02 +00002022 SourceLocation SelLoc,
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002023 SourceLocation LParenLoc,
2024 SourceLocation RParenLoc) {
Steve Naroffae84af82007-10-31 18:42:27 +00002025 QualType t = Context.getObjcSelType();
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002026 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
2027}
2028
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002029Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
2030 SourceLocation AtLoc,
2031 SourceLocation ProtoLoc,
2032 SourceLocation LParenLoc,
2033 SourceLocation RParenLoc) {
2034 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
2035 if (!PDecl) {
2036 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
2037 return true;
2038 }
2039
2040 QualType t = GetObjcProtoType(AtLoc);
Fariborz Jahanian20b40e42007-10-18 22:59:23 +00002041 if (t.isNull())
2042 return true;
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002043 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
2044}
Steve Naroff52664182007-10-16 23:12:48 +00002045
2046bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2047 ObjcMethodDecl *Method) {
2048 bool anyIncompatibleArgs = false;
2049
2050 for (unsigned i = 0; i < NumArgs; i++) {
2051 Expr *argExpr = Args[i];
2052 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2053
2054 QualType lhsType = Method->getParamDecl(i)->getType();
2055 QualType rhsType = argExpr->getType();
2056
2057 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2058 if (const ArrayType *ary = lhsType->getAsArrayType())
2059 lhsType = Context.getPointerType(ary->getElementType());
2060 else if (lhsType->isFunctionType())
2061 lhsType = Context.getPointerType(lhsType);
2062
2063 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2064 argExpr);
2065 if (Args[i] != argExpr) // The expression was converted.
2066 Args[i] = argExpr; // Make sure we store the converted expression.
2067 SourceLocation l = argExpr->getLocStart();
2068
2069 // decode the result (notice that AST's are still created for extensions).
2070 switch (result) {
2071 case Compatible:
2072 break;
2073 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +00002074 Diag(l, diag::ext_typecheck_sending_pointer_int,
2075 lhsType.getAsString(), rhsType.getAsString(),
2076 argExpr->getSourceRange());
Steve Naroff52664182007-10-16 23:12:48 +00002077 break;
2078 case IntFromPointer:
2079 Diag(l, diag::ext_typecheck_sending_pointer_int,
2080 lhsType.getAsString(), rhsType.getAsString(),
2081 argExpr->getSourceRange());
2082 break;
2083 case IncompatiblePointer:
2084 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2085 rhsType.getAsString(), lhsType.getAsString(),
2086 argExpr->getSourceRange());
2087 break;
2088 case CompatiblePointerDiscardsQualifiers:
2089 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2090 rhsType.getAsString(), lhsType.getAsString(),
2091 argExpr->getSourceRange());
2092 break;
2093 case Incompatible:
2094 Diag(l, diag::err_typecheck_sending_incompatible,
2095 rhsType.getAsString(), lhsType.getAsString(),
2096 argExpr->getSourceRange());
2097 anyIncompatibleArgs = true;
2098 }
2099 }
2100 return anyIncompatibleArgs;
2101}
2102
Steve Naroff4ed9d662007-09-27 14:38:14 +00002103// ActOnClassMessage - used for both unary and keyword messages.
2104// ArgExprs is optional - if it is present, the number of expressions
2105// is obtained from Sel.getNumArgs().
2106Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002107 Scope *S,
Steve Narofffa465d12007-10-02 20:01:56 +00002108 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002109 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002110{
Steve Narofffa465d12007-10-02 20:01:56 +00002111 assert(receiverName && "missing receiver class name");
Steve Naroffc39ca262007-09-18 23:55:05 +00002112
Steve Naroff52664182007-10-16 23:12:48 +00002113 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002114 ObjcInterfaceDecl* ClassDecl = 0;
2115 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2116 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahanian342f3602007-11-12 20:20:37 +00002117 if (ClassDecl && CurMethodDecl->isInstance()) {
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002118 IdentifierInfo &II = Context.Idents.get("self");
2119 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II,
2120 false);
2121 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2122 superTy = Context.getPointerType(superTy);
2123 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2124 SourceLocation(), ReceiverExpr.Val);
2125
2126 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002127 Args, NumArgs);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002128 }
2129 // class method
2130 if (ClassDecl)
2131 receiverName = ClassDecl->getIdentifier();
2132 }
2133 else
2134 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Narofffa465d12007-10-02 20:01:56 +00002135 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002136 QualType returnType;
Steve Naroff75c4baf2007-11-05 15:27:52 +00002137
2138 // Before we give up, check if the selector is an instance method.
2139 if (!Method)
2140 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002141 if (!Method) {
2142 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2143 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002144 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002145 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002146 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002147 if (Sel.getNumArgs()) {
2148 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2149 return true;
2150 }
Steve Naroff7e461452007-10-16 20:39:36 +00002151 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002152 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
Steve Naroff9f176d12007-11-15 13:05:42 +00002153 lbrac, rbrac, ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002154}
2155
Steve Naroff4ed9d662007-09-27 14:38:14 +00002156// ActOnInstanceMessage - used for both unary and keyword messages.
2157// ArgExprs is optional - if it is present, the number of expressions
2158// is obtained from Sel.getNumArgs().
2159Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroff6cb1d362007-09-28 22:22:11 +00002160 ExprTy *receiver, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002161 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff4ed9d662007-09-27 14:38:14 +00002162{
Steve Naroffc39ca262007-09-18 23:55:05 +00002163 assert(receiver && "missing receiver expression");
2164
Steve Naroff52664182007-10-16 23:12:48 +00002165 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroffc39ca262007-09-18 23:55:05 +00002166 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Narofffa465d12007-10-02 20:01:56 +00002167 QualType receiverType = RExpr->getType();
Steve Naroffee1de132007-10-10 21:53:07 +00002168 QualType returnType;
Steve Naroff1e1c3912007-11-03 16:37:59 +00002169 ObjcMethodDecl *Method;
Steve Naroffee1de132007-10-10 21:53:07 +00002170
Steve Naroff0091d142007-11-11 17:52:25 +00002171 if (receiverType == Context.getObjcIdType() ||
2172 receiverType == Context.getObjcClassType()) {
Steve Naroff1e1c3912007-11-03 16:37:59 +00002173 Method = InstanceMethodPool[Sel].Method;
Steve Naroffd0cfcd02007-11-13 04:10:18 +00002174 // If we didn't find an public method, look for a private one.
2175 if (!Method && CurMethodDecl) {
2176 NamedDecl *impCxt = CurMethodDecl->getMethodContext();
2177 if (ObjcImplementationDecl *IMD =
2178 dyn_cast<ObjcImplementationDecl>(impCxt)) {
2179 if (receiverType == Context.getObjcIdType())
2180 Method = IMD->lookupInstanceMethod(Sel);
2181 else
2182 Method = IMD->lookupClassMethod(Sel);
2183 } else if (ObjcCategoryImplDecl *CID =
2184 dyn_cast<ObjcCategoryImplDecl>(impCxt)) {
2185 if (receiverType == Context.getObjcIdType())
2186 Method = CID->lookupInstanceMethod(Sel);
2187 else
2188 Method = CID->lookupClassMethod(Sel);
2189 }
2190 }
Steve Naroff7e461452007-10-16 20:39:36 +00002191 if (!Method) {
2192 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2193 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002194 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002195 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002196 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002197 if (Sel.getNumArgs())
2198 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2199 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002200 }
Steve Naroffee1de132007-10-10 21:53:07 +00002201 } else {
Chris Lattner71c01112007-10-10 23:42:28 +00002202 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2203 // revisited. how do we get the ClassDecl from the receiver expression?
Steve Naroffee1de132007-10-10 21:53:07 +00002204 while (receiverType->isPointerType()) {
Chris Lattner71c01112007-10-10 23:42:28 +00002205 PointerType *pointerType =
2206 static_cast<PointerType*>(receiverType.getTypePtr());
Steve Naroffee1de132007-10-10 21:53:07 +00002207 receiverType = pointerType->getPointeeType();
2208 }
Chris Lattner71c01112007-10-10 23:42:28 +00002209 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2210 "bad receiver type");
Steve Naroffee1de132007-10-10 21:53:07 +00002211 ObjcInterfaceDecl* ClassDecl = static_cast<ObjcInterfaceType*>(
2212 receiverType.getTypePtr())->getDecl();
Steve Naroff7e461452007-10-16 20:39:36 +00002213 // FIXME: consider using InstanceMethodPool, since it will be faster
2214 // than the following method (which can do *many* linear searches). The
2215 // idea is to add class info to InstanceMethodPool...
Steve Naroff1e1c3912007-11-03 16:37:59 +00002216 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002217 if (!Method) {
Steve Naroffb1c7ad92007-11-11 00:10:47 +00002218 // If we have an implementation in scope, check "private" methods.
2219 if (ObjcImplementationDecl *ImpDecl =
2220 ObjcImplementations[ClassDecl->getIdentifier()])
2221 Method = ImpDecl->lookupInstanceMethod(Sel);
2222 }
2223 if (!Method) {
Steve Naroff7e461452007-10-16 20:39:36 +00002224 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2225 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002226 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002227 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002228 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002229 if (Sel.getNumArgs())
2230 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2231 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002232 }
Steve Narofffa465d12007-10-02 20:01:56 +00002233 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002234 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002235 ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002236}