blob: f53980ca906d14913cdf3cfbdc298db6c2528e4d [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()) {
Anders Carlssone87cd982007-11-30 04:21:22 +00001103 if (!getLangOptions().LaxVectorConversions) {
1104 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1105 return Incompatible;
1106 } else {
1107 if (lhsType->isVectorType() && rhsType->isVectorType()) {
1108 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1109 (lhsType->isRealFloatingType() &&
1110 rhsType->isRealFloatingType())) {
1111 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1112 Context.getTypeSize(rhsType, SourceLocation()))
1113 return Compatible;
1114 }
1115 }
Chris Lattner4b009652007-07-25 00:24:17 +00001116 return Incompatible;
Anders Carlssone87cd982007-11-30 04:21:22 +00001117 }
1118 }
Chris Lattner4b009652007-07-25 00:24:17 +00001119 return Compatible;
1120 } else if (lhsType->isPointerType()) {
1121 if (rhsType->isIntegerType())
1122 return PointerFromInt;
1123
1124 if (rhsType->isPointerType())
1125 return CheckPointerTypesForAssignment(lhsType, rhsType);
1126 } else if (rhsType->isPointerType()) {
1127 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1128 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1129 return IntFromPointer;
1130
1131 if (lhsType->isPointerType())
1132 return CheckPointerTypesForAssignment(lhsType, rhsType);
1133 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001134 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001135 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001136 }
1137 return Incompatible;
1138}
1139
1140Sema::AssignmentCheckResult
1141Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001142 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1143 // a null pointer constant.
1144 if (lhsType->isPointerType() && rExpr->isNullPointerConstant(Context)) {
1145 promoteExprToType(rExpr, lhsType);
1146 return Compatible;
1147 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001148 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001149 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001150 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001151 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001152 //
1153 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1154 // are better understood.
1155 if (!lhsType->isReferenceType())
1156 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001157
1158 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +00001159
Steve Naroff0f32f432007-08-24 22:33:52 +00001160 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1161
1162 // C99 6.5.16.1p2: The value of the right operand is converted to the
1163 // type of the assignment expression.
1164 if (rExpr->getType() != lhsType)
1165 promoteExprToType(rExpr, lhsType);
1166 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001167}
1168
1169Sema::AssignmentCheckResult
1170Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1171 return CheckAssignmentConstraints(lhsType, rhsType);
1172}
1173
1174inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1175 Diag(loc, diag::err_typecheck_invalid_operands,
1176 lex->getType().getAsString(), rex->getType().getAsString(),
1177 lex->getSourceRange(), rex->getSourceRange());
1178}
1179
1180inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1181 Expr *&rex) {
1182 QualType lhsType = lex->getType(), rhsType = rex->getType();
1183
1184 // make sure the vector types are identical.
1185 if (lhsType == rhsType)
1186 return lhsType;
1187 // You cannot convert between vector values of different size.
1188 Diag(loc, diag::err_typecheck_vector_not_convertable,
1189 lex->getType().getAsString(), rex->getType().getAsString(),
1190 lex->getSourceRange(), rex->getSourceRange());
1191 return QualType();
1192}
1193
1194inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001195 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001196{
1197 QualType lhsType = lex->getType(), rhsType = rex->getType();
1198
1199 if (lhsType->isVectorType() || rhsType->isVectorType())
1200 return CheckVectorOperands(loc, lex, rex);
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()->isArithmeticType() && rex->getType()->isArithmeticType())
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::CheckRemainderOperands(
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 QualType lhsType = lex->getType(), rhsType = rex->getType();
1214
Steve Naroff8f708362007-08-24 19:07:16 +00001215 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001216
Chris Lattner4b009652007-07-25 00:24:17 +00001217 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001218 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001219 InvalidOperands(loc, lex, rex);
1220 return QualType();
1221}
1222
1223inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001224 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001225{
1226 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1227 return CheckVectorOperands(loc, lex, rex);
1228
Steve Naroff8f708362007-08-24 19:07:16 +00001229 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001230
1231 // handle the common case first (both operands are arithmetic).
1232 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001233 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001234
1235 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1236 return lex->getType();
1237 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1238 return rex->getType();
1239 InvalidOperands(loc, lex, rex);
1240 return QualType();
1241}
1242
1243inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001244 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001245{
1246 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1247 return CheckVectorOperands(loc, lex, rex);
1248
Steve Naroff8f708362007-08-24 19:07:16 +00001249 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001250
1251 // handle the common case first (both operands are arithmetic).
1252 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001253 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001254
1255 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001256 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001257 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1258 return Context.getPointerDiffType();
1259 InvalidOperands(loc, lex, rex);
1260 return QualType();
1261}
1262
1263inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001264 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001265{
1266 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1267 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001268 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001269
1270 // handle the common case first (both operands are arithmetic).
1271 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001272 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001273 InvalidOperands(loc, lex, rex);
1274 return QualType();
1275}
1276
Chris Lattner254f3bc2007-08-26 01:18:55 +00001277inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1278 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001279{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001280 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001281 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1282 UsualArithmeticConversions(lex, rex);
1283 else {
1284 UsualUnaryConversions(lex);
1285 UsualUnaryConversions(rex);
1286 }
Chris Lattner4b009652007-07-25 00:24:17 +00001287 QualType lType = lex->getType();
1288 QualType rType = rex->getType();
1289
Ted Kremenek486509e2007-10-29 17:13:39 +00001290 // For non-floating point types, check for self-comparisons of the form
1291 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1292 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001293 if (!lType->isFloatingType()) {
1294 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1295 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1296 if (DRL->getDecl() == DRR->getDecl())
1297 Diag(loc, diag::warn_selfcomparison);
1298 }
1299
Chris Lattner254f3bc2007-08-26 01:18:55 +00001300 if (isRelational) {
1301 if (lType->isRealType() && rType->isRealType())
1302 return Context.IntTy;
1303 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001304 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001305 if (lType->isFloatingType()) {
1306 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001307 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001308 }
1309
Chris Lattner254f3bc2007-08-26 01:18:55 +00001310 if (lType->isArithmeticType() && rType->isArithmeticType())
1311 return Context.IntTy;
1312 }
Chris Lattner4b009652007-07-25 00:24:17 +00001313
Chris Lattner22be8422007-08-26 01:10:14 +00001314 bool LHSIsNull = lex->isNullPointerConstant(Context);
1315 bool RHSIsNull = rex->isNullPointerConstant(Context);
1316
Chris Lattner254f3bc2007-08-26 01:18:55 +00001317 // All of the following pointer related warnings are GCC extensions, except
1318 // when handling null pointer constants. One day, we can consider making them
1319 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001320 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff3b435622007-11-13 14:57:38 +00001321
1322 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1323 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1324 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroff85f0dc52007-10-15 20:41:53 +00001325 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1326 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001327 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1328 lType.getAsString(), rType.getAsString(),
1329 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001330 }
Chris Lattner22be8422007-08-26 01:10:14 +00001331 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001332 return Context.IntTy;
1333 }
1334 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001335 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001336 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1337 lType.getAsString(), rType.getAsString(),
1338 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001339 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001340 return Context.IntTy;
1341 }
1342 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001343 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001344 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1345 lType.getAsString(), rType.getAsString(),
1346 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001347 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001348 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001349 }
1350 InvalidOperands(loc, lex, rex);
1351 return QualType();
1352}
1353
Chris Lattner4b009652007-07-25 00:24:17 +00001354inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001355 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001356{
1357 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1358 return CheckVectorOperands(loc, lex, rex);
1359
Steve Naroff8f708362007-08-24 19:07:16 +00001360 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001361
1362 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001363 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001364 InvalidOperands(loc, lex, rex);
1365 return QualType();
1366}
1367
1368inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1369 Expr *&lex, Expr *&rex, SourceLocation loc)
1370{
1371 UsualUnaryConversions(lex);
1372 UsualUnaryConversions(rex);
1373
1374 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1375 return Context.IntTy;
1376 InvalidOperands(loc, lex, rex);
1377 return QualType();
1378}
1379
1380inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001381 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001382{
1383 QualType lhsType = lex->getType();
1384 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1385 bool hadError = false;
1386 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1387
1388 switch (mlval) { // C99 6.5.16p2
1389 case Expr::MLV_Valid:
1390 break;
1391 case Expr::MLV_ConstQualified:
1392 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1393 hadError = true;
1394 break;
1395 case Expr::MLV_ArrayType:
1396 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1397 lhsType.getAsString(), lex->getSourceRange());
1398 return QualType();
1399 case Expr::MLV_NotObjectType:
1400 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1401 lhsType.getAsString(), lex->getSourceRange());
1402 return QualType();
1403 case Expr::MLV_InvalidExpression:
1404 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1405 lex->getSourceRange());
1406 return QualType();
1407 case Expr::MLV_IncompleteType:
1408 case Expr::MLV_IncompleteVoidType:
1409 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1410 lhsType.getAsString(), lex->getSourceRange());
1411 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001412 case Expr::MLV_DuplicateVectorComponents:
1413 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1414 lex->getSourceRange());
1415 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001416 }
1417 AssignmentCheckResult result;
1418
1419 if (compoundType.isNull())
1420 result = CheckSingleAssignmentConstraints(lhsType, rex);
1421 else
1422 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001423
Chris Lattner4b009652007-07-25 00:24:17 +00001424 // decode the result (notice that extensions still return a type).
1425 switch (result) {
1426 case Compatible:
1427 break;
1428 case Incompatible:
1429 Diag(loc, diag::err_typecheck_assign_incompatible,
1430 lhsType.getAsString(), rhsType.getAsString(),
1431 lex->getSourceRange(), rex->getSourceRange());
1432 hadError = true;
1433 break;
1434 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +00001435 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1436 lhsType.getAsString(), rhsType.getAsString(),
1437 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001438 break;
1439 case IntFromPointer:
1440 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1441 lhsType.getAsString(), rhsType.getAsString(),
1442 lex->getSourceRange(), rex->getSourceRange());
1443 break;
1444 case IncompatiblePointer:
1445 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1446 lhsType.getAsString(), rhsType.getAsString(),
1447 lex->getSourceRange(), rex->getSourceRange());
1448 break;
1449 case CompatiblePointerDiscardsQualifiers:
1450 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1451 lhsType.getAsString(), rhsType.getAsString(),
1452 lex->getSourceRange(), rex->getSourceRange());
1453 break;
1454 }
1455 // C99 6.5.16p3: The type of an assignment expression is the type of the
1456 // left operand unless the left operand has qualified type, in which case
1457 // it is the unqualified version of the type of the left operand.
1458 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1459 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001460 // C++ 5.17p1: the type of the assignment expression is that of its left
1461 // oprdu.
Chris Lattner4b009652007-07-25 00:24:17 +00001462 return hadError ? QualType() : lhsType.getUnqualifiedType();
1463}
1464
1465inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1466 Expr *&lex, Expr *&rex, SourceLocation loc) {
1467 UsualUnaryConversions(rex);
1468 return rex->getType();
1469}
1470
1471/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1472/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1473QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1474 QualType resType = op->getType();
1475 assert(!resType.isNull() && "no type for increment/decrement expression");
1476
Steve Naroffd30e1932007-08-24 17:20:07 +00001477 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001478 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001479 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1480 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1481 resType.getAsString(), op->getSourceRange());
1482 return QualType();
1483 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001484 } else if (!resType->isRealType()) {
1485 if (resType->isComplexType())
1486 // C99 does not support ++/-- on complex types.
1487 Diag(OpLoc, diag::ext_integer_increment_complex,
1488 resType.getAsString(), op->getSourceRange());
1489 else {
1490 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1491 resType.getAsString(), op->getSourceRange());
1492 return QualType();
1493 }
Chris Lattner4b009652007-07-25 00:24:17 +00001494 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001495 // At this point, we know we have a real, complex or pointer type.
1496 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001497 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1498 if (mlval != Expr::MLV_Valid) {
1499 // FIXME: emit a more precise diagnostic...
1500 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1501 op->getSourceRange());
1502 return QualType();
1503 }
1504 return resType;
1505}
1506
1507/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1508/// This routine allows us to typecheck complex/recursive expressions
1509/// where the declaration is needed for type checking. Here are some
1510/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1511static Decl *getPrimaryDeclaration(Expr *e) {
1512 switch (e->getStmtClass()) {
1513 case Stmt::DeclRefExprClass:
1514 return cast<DeclRefExpr>(e)->getDecl();
1515 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001516 // Fields cannot be declared with a 'register' storage class.
1517 // &X->f is always ok, even if X is declared register.
1518 if (cast<MemberExpr>(e)->isArrow())
1519 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001520 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1521 case Stmt::ArraySubscriptExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001522 // &X[4] and &4[X] is invalid if X is invalid.
Chris Lattner4b009652007-07-25 00:24:17 +00001523 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +00001524 case Stmt::UnaryOperatorClass:
1525 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1526 case Stmt::ParenExprClass:
1527 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001528 case Stmt::ImplicitCastExprClass:
1529 // &X[4] when X is an array, has an implicit cast from array to pointer.
1530 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001531 default:
1532 return 0;
1533 }
1534}
1535
1536/// CheckAddressOfOperand - The operand of & must be either a function
1537/// designator or an lvalue designating an object. If it is an lvalue, the
1538/// object cannot be declared with storage class register or be a bit field.
1539/// Note: The usual conversions are *not* applied to the operand of the &
1540/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1541QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1542 Decl *dcl = getPrimaryDeclaration(op);
1543 Expr::isLvalueResult lval = op->isLvalue();
1544
1545 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001546 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1547 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001548 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1549 op->getSourceRange());
1550 return QualType();
1551 }
1552 } else if (dcl) {
1553 // We have an lvalue with a decl. Make sure the decl is not declared
1554 // with the register storage-class specifier.
1555 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1556 if (vd->getStorageClass() == VarDecl::Register) {
1557 Diag(OpLoc, diag::err_typecheck_address_of_register,
1558 op->getSourceRange());
1559 return QualType();
1560 }
1561 } else
1562 assert(0 && "Unknown/unexpected decl type");
1563
1564 // FIXME: add check for bitfields!
1565 }
1566 // If the operand has type "type", the result has type "pointer to type".
1567 return Context.getPointerType(op->getType());
1568}
1569
1570QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1571 UsualUnaryConversions(op);
1572 QualType qType = op->getType();
1573
Chris Lattner7931f4a2007-07-31 16:53:04 +00001574 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001575 QualType ptype = PT->getPointeeType();
1576 // C99 6.5.3.2p4. "if it points to an object,...".
1577 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1578 // GCC compat: special case 'void *' (treat as warning).
1579 if (ptype->isVoidType()) {
1580 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1581 qType.getAsString(), op->getSourceRange());
1582 } else {
1583 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1584 ptype.getAsString(), op->getSourceRange());
1585 return QualType();
1586 }
1587 }
1588 return ptype;
1589 }
1590 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1591 qType.getAsString(), op->getSourceRange());
1592 return QualType();
1593}
1594
1595static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1596 tok::TokenKind Kind) {
1597 BinaryOperator::Opcode Opc;
1598 switch (Kind) {
1599 default: assert(0 && "Unknown binop!");
1600 case tok::star: Opc = BinaryOperator::Mul; break;
1601 case tok::slash: Opc = BinaryOperator::Div; break;
1602 case tok::percent: Opc = BinaryOperator::Rem; break;
1603 case tok::plus: Opc = BinaryOperator::Add; break;
1604 case tok::minus: Opc = BinaryOperator::Sub; break;
1605 case tok::lessless: Opc = BinaryOperator::Shl; break;
1606 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1607 case tok::lessequal: Opc = BinaryOperator::LE; break;
1608 case tok::less: Opc = BinaryOperator::LT; break;
1609 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1610 case tok::greater: Opc = BinaryOperator::GT; break;
1611 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1612 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1613 case tok::amp: Opc = BinaryOperator::And; break;
1614 case tok::caret: Opc = BinaryOperator::Xor; break;
1615 case tok::pipe: Opc = BinaryOperator::Or; break;
1616 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1617 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1618 case tok::equal: Opc = BinaryOperator::Assign; break;
1619 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1620 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1621 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1622 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1623 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1624 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1625 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1626 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1627 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1628 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1629 case tok::comma: Opc = BinaryOperator::Comma; break;
1630 }
1631 return Opc;
1632}
1633
1634static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1635 tok::TokenKind Kind) {
1636 UnaryOperator::Opcode Opc;
1637 switch (Kind) {
1638 default: assert(0 && "Unknown unary op!");
1639 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1640 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1641 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1642 case tok::star: Opc = UnaryOperator::Deref; break;
1643 case tok::plus: Opc = UnaryOperator::Plus; break;
1644 case tok::minus: Opc = UnaryOperator::Minus; break;
1645 case tok::tilde: Opc = UnaryOperator::Not; break;
1646 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1647 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1648 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1649 case tok::kw___real: Opc = UnaryOperator::Real; break;
1650 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1651 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1652 }
1653 return Opc;
1654}
1655
1656// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001657Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001658 ExprTy *LHS, ExprTy *RHS) {
1659 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1660 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1661
Steve Naroff87d58b42007-09-16 03:34:24 +00001662 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1663 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001664
1665 QualType ResultTy; // Result type of the binary operator.
1666 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1667
1668 switch (Opc) {
1669 default:
1670 assert(0 && "Unknown binary expr!");
1671 case BinaryOperator::Assign:
1672 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1673 break;
1674 case BinaryOperator::Mul:
1675 case BinaryOperator::Div:
1676 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1677 break;
1678 case BinaryOperator::Rem:
1679 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1680 break;
1681 case BinaryOperator::Add:
1682 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1683 break;
1684 case BinaryOperator::Sub:
1685 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1686 break;
1687 case BinaryOperator::Shl:
1688 case BinaryOperator::Shr:
1689 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1690 break;
1691 case BinaryOperator::LE:
1692 case BinaryOperator::LT:
1693 case BinaryOperator::GE:
1694 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001695 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001696 break;
1697 case BinaryOperator::EQ:
1698 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001699 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001700 break;
1701 case BinaryOperator::And:
1702 case BinaryOperator::Xor:
1703 case BinaryOperator::Or:
1704 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1705 break;
1706 case BinaryOperator::LAnd:
1707 case BinaryOperator::LOr:
1708 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1709 break;
1710 case BinaryOperator::MulAssign:
1711 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001712 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001713 if (!CompTy.isNull())
1714 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1715 break;
1716 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001717 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001718 if (!CompTy.isNull())
1719 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1720 break;
1721 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001722 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001723 if (!CompTy.isNull())
1724 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1725 break;
1726 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001727 CompTy = CheckSubtractionOperands(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::ShlAssign:
1732 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001733 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001734 if (!CompTy.isNull())
1735 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1736 break;
1737 case BinaryOperator::AndAssign:
1738 case BinaryOperator::XorAssign:
1739 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001740 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001741 if (!CompTy.isNull())
1742 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1743 break;
1744 case BinaryOperator::Comma:
1745 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1746 break;
1747 }
1748 if (ResultTy.isNull())
1749 return true;
1750 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001751 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001752 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001753 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001754}
1755
1756// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001757Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001758 ExprTy *input) {
1759 Expr *Input = (Expr*)input;
1760 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1761 QualType resultType;
1762 switch (Opc) {
1763 default:
1764 assert(0 && "Unimplemented unary expr!");
1765 case UnaryOperator::PreInc:
1766 case UnaryOperator::PreDec:
1767 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1768 break;
1769 case UnaryOperator::AddrOf:
1770 resultType = CheckAddressOfOperand(Input, OpLoc);
1771 break;
1772 case UnaryOperator::Deref:
1773 resultType = CheckIndirectionOperand(Input, OpLoc);
1774 break;
1775 case UnaryOperator::Plus:
1776 case UnaryOperator::Minus:
1777 UsualUnaryConversions(Input);
1778 resultType = Input->getType();
1779 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1780 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1781 resultType.getAsString());
1782 break;
1783 case UnaryOperator::Not: // bitwise complement
1784 UsualUnaryConversions(Input);
1785 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001786 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1787 if (!resultType->isIntegerType()) {
1788 if (resultType->isComplexType())
1789 // C99 does not support '~' for complex conjugation.
1790 Diag(OpLoc, diag::ext_integer_complement_complex,
1791 resultType.getAsString());
1792 else
1793 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1794 resultType.getAsString());
1795 }
Chris Lattner4b009652007-07-25 00:24:17 +00001796 break;
1797 case UnaryOperator::LNot: // logical negation
1798 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1799 DefaultFunctionArrayConversion(Input);
1800 resultType = Input->getType();
1801 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1802 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1803 resultType.getAsString());
1804 // LNot always has type int. C99 6.5.3.3p5.
1805 resultType = Context.IntTy;
1806 break;
1807 case UnaryOperator::SizeOf:
1808 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1809 break;
1810 case UnaryOperator::AlignOf:
1811 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1812 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001813 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001814 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001815 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001816 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001817 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001818 resultType = Input->getType();
1819 break;
1820 }
1821 if (resultType.isNull())
1822 return true;
1823 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1824}
1825
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001826/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1827Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001828 SourceLocation LabLoc,
1829 IdentifierInfo *LabelII) {
1830 // Look up the record for this label identifier.
1831 LabelStmt *&LabelDecl = LabelMap[LabelII];
1832
1833 // If we haven't seen this label yet, create a forward reference.
1834 if (LabelDecl == 0)
1835 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1836
1837 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001838 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1839 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001840}
1841
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001842Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00001843 SourceLocation RPLoc) { // "({..})"
1844 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1845 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1846 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1847
1848 // FIXME: there are a variety of strange constraints to enforce here, for
1849 // example, it is not possible to goto into a stmt expression apparently.
1850 // More semantic analysis is needed.
1851
1852 // FIXME: the last statement in the compount stmt has its value used. We
1853 // should not warn about it being unused.
1854
1855 // If there are sub stmts in the compound stmt, take the type of the last one
1856 // as the type of the stmtexpr.
1857 QualType Ty = Context.VoidTy;
1858
1859 if (!Compound->body_empty())
1860 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1861 Ty = LastExpr->getType();
1862
1863 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1864}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001865
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001866Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001867 SourceLocation TypeLoc,
1868 TypeTy *argty,
1869 OffsetOfComponent *CompPtr,
1870 unsigned NumComponents,
1871 SourceLocation RPLoc) {
1872 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1873 assert(!ArgTy.isNull() && "Missing type argument!");
1874
1875 // We must have at least one component that refers to the type, and the first
1876 // one is known to be a field designator. Verify that the ArgTy represents
1877 // a struct/union/class.
1878 if (!ArgTy->isRecordType())
1879 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1880
1881 // Otherwise, create a compound literal expression as the base, and
1882 // iteratively process the offsetof designators.
1883 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1884
Chris Lattnerb37522e2007-08-31 21:49:13 +00001885 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1886 // GCC extension, diagnose them.
1887 if (NumComponents != 1)
1888 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1889 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1890
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001891 for (unsigned i = 0; i != NumComponents; ++i) {
1892 const OffsetOfComponent &OC = CompPtr[i];
1893 if (OC.isBrackets) {
1894 // Offset of an array sub-field. TODO: Should we allow vector elements?
1895 const ArrayType *AT = Res->getType()->getAsArrayType();
1896 if (!AT) {
1897 delete Res;
1898 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1899 Res->getType().getAsString());
1900 }
1901
Chris Lattner2af6a802007-08-30 17:59:59 +00001902 // FIXME: C++: Verify that operator[] isn't overloaded.
1903
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001904 // C99 6.5.2.1p1
1905 Expr *Idx = static_cast<Expr*>(OC.U.E);
1906 if (!Idx->getType()->isIntegerType())
1907 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1908 Idx->getSourceRange());
1909
1910 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1911 continue;
1912 }
1913
1914 const RecordType *RC = Res->getType()->getAsRecordType();
1915 if (!RC) {
1916 delete Res;
1917 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1918 Res->getType().getAsString());
1919 }
1920
1921 // Get the decl corresponding to this.
1922 RecordDecl *RD = RC->getDecl();
1923 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1924 if (!MemberDecl)
1925 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1926 OC.U.IdentInfo->getName(),
1927 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00001928
1929 // FIXME: C++: Verify that MemberDecl isn't a static field.
1930 // FIXME: Verify that MemberDecl isn't a bitfield.
1931
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001932 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1933 }
1934
1935 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1936 BuiltinLoc);
1937}
1938
1939
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001940Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001941 TypeTy *arg1, TypeTy *arg2,
1942 SourceLocation RPLoc) {
1943 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1944 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1945
1946 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1947
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001948 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001949}
1950
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001951Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00001952 ExprTy *expr1, ExprTy *expr2,
1953 SourceLocation RPLoc) {
1954 Expr *CondExpr = static_cast<Expr*>(cond);
1955 Expr *LHSExpr = static_cast<Expr*>(expr1);
1956 Expr *RHSExpr = static_cast<Expr*>(expr2);
1957
1958 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1959
1960 // The conditional expression is required to be a constant expression.
1961 llvm::APSInt condEval(32);
1962 SourceLocation ExpLoc;
1963 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1964 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1965 CondExpr->getSourceRange());
1966
1967 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1968 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1969 RHSExpr->getType();
1970 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1971}
1972
Anders Carlsson36760332007-10-15 20:28:48 +00001973Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
1974 ExprTy *expr, TypeTy *type,
1975 SourceLocation RPLoc)
1976{
1977 Expr *E = static_cast<Expr*>(expr);
1978 QualType T = QualType::getFromOpaquePtr(type);
1979
1980 InitBuiltinVaListType();
1981
1982 Sema::AssignmentCheckResult result;
1983
1984 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
1985 E->getType());
1986 if (result != Compatible)
1987 return Diag(E->getLocStart(),
1988 diag::err_first_argument_to_va_arg_not_of_type_va_list,
1989 E->getType().getAsString(),
1990 E->getSourceRange());
1991
1992 // FIXME: Warn if a non-POD type is passed in.
1993
1994 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
1995}
1996
Anders Carlssona66cad42007-08-21 17:43:55 +00001997// TODO: Move this to SemaObjC.cpp
Steve Naroff0add5d22007-11-03 11:27:19 +00001998Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation AtLoc,
1999 ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00002000 StringLiteral* S = static_cast<StringLiteral *>(string);
2001
2002 if (CheckBuiltinCFStringArgument(S))
2003 return true;
2004
Steve Narofff2e30312007-10-15 23:35:17 +00002005 if (Context.getObjcConstantStringInterface().isNull()) {
2006 // Initialize the constant string interface lazily. This assumes
2007 // the NSConstantString interface is seen in this translation unit.
2008 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
2009 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
2010 SourceLocation(), TUScope);
Steve Naroff134c3502007-10-16 00:00:18 +00002011 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff96f136d2007-10-18 23:53:51 +00002012 if (!strIFace)
2013 return Diag(S->getLocStart(), diag::err_undef_interface,
2014 NSIdent->getName());
Steve Naroff134c3502007-10-16 00:00:18 +00002015 Context.setObjcConstantStringInterface(strIFace);
Steve Narofff2e30312007-10-15 23:35:17 +00002016 }
2017 QualType t = Context.getObjcConstantStringInterface();
Anders Carlssona66cad42007-08-21 17:43:55 +00002018 t = Context.getPointerType(t);
Steve Naroff0add5d22007-11-03 11:27:19 +00002019 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlssona66cad42007-08-21 17:43:55 +00002020}
Anders Carlsson8be1d402007-08-22 15:14:15 +00002021
2022Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattnercfd61c82007-10-16 22:51:17 +00002023 SourceLocation EncodeLoc,
Anders Carlsson8be1d402007-08-22 15:14:15 +00002024 SourceLocation LParenLoc,
2025 TypeTy *Ty,
2026 SourceLocation RParenLoc) {
2027 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
2028
2029 QualType t = Context.getPointerType(Context.CharTy);
2030 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
2031}
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002032
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002033Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
2034 SourceLocation AtLoc,
Fariborz Jahanian957448a2007-10-16 23:21:02 +00002035 SourceLocation SelLoc,
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002036 SourceLocation LParenLoc,
2037 SourceLocation RParenLoc) {
Steve Naroffae84af82007-10-31 18:42:27 +00002038 QualType t = Context.getObjcSelType();
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002039 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
2040}
2041
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002042Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
2043 SourceLocation AtLoc,
2044 SourceLocation ProtoLoc,
2045 SourceLocation LParenLoc,
2046 SourceLocation RParenLoc) {
2047 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
2048 if (!PDecl) {
2049 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
2050 return true;
2051 }
2052
2053 QualType t = GetObjcProtoType(AtLoc);
Fariborz Jahanian20b40e42007-10-18 22:59:23 +00002054 if (t.isNull())
2055 return true;
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002056 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
2057}
Steve Naroff52664182007-10-16 23:12:48 +00002058
2059bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2060 ObjcMethodDecl *Method) {
2061 bool anyIncompatibleArgs = false;
2062
2063 for (unsigned i = 0; i < NumArgs; i++) {
2064 Expr *argExpr = Args[i];
2065 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2066
2067 QualType lhsType = Method->getParamDecl(i)->getType();
2068 QualType rhsType = argExpr->getType();
2069
2070 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2071 if (const ArrayType *ary = lhsType->getAsArrayType())
2072 lhsType = Context.getPointerType(ary->getElementType());
2073 else if (lhsType->isFunctionType())
2074 lhsType = Context.getPointerType(lhsType);
2075
2076 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2077 argExpr);
2078 if (Args[i] != argExpr) // The expression was converted.
2079 Args[i] = argExpr; // Make sure we store the converted expression.
2080 SourceLocation l = argExpr->getLocStart();
2081
2082 // decode the result (notice that AST's are still created for extensions).
2083 switch (result) {
2084 case Compatible:
2085 break;
2086 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +00002087 Diag(l, diag::ext_typecheck_sending_pointer_int,
2088 lhsType.getAsString(), rhsType.getAsString(),
2089 argExpr->getSourceRange());
Steve Naroff52664182007-10-16 23:12:48 +00002090 break;
2091 case IntFromPointer:
2092 Diag(l, diag::ext_typecheck_sending_pointer_int,
2093 lhsType.getAsString(), rhsType.getAsString(),
2094 argExpr->getSourceRange());
2095 break;
2096 case IncompatiblePointer:
2097 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2098 rhsType.getAsString(), lhsType.getAsString(),
2099 argExpr->getSourceRange());
2100 break;
2101 case CompatiblePointerDiscardsQualifiers:
2102 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2103 rhsType.getAsString(), lhsType.getAsString(),
2104 argExpr->getSourceRange());
2105 break;
2106 case Incompatible:
2107 Diag(l, diag::err_typecheck_sending_incompatible,
2108 rhsType.getAsString(), lhsType.getAsString(),
2109 argExpr->getSourceRange());
2110 anyIncompatibleArgs = true;
2111 }
2112 }
2113 return anyIncompatibleArgs;
2114}
2115
Steve Naroff4ed9d662007-09-27 14:38:14 +00002116// ActOnClassMessage - used for both unary and keyword messages.
2117// ArgExprs is optional - if it is present, the number of expressions
2118// is obtained from Sel.getNumArgs().
2119Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002120 Scope *S,
Steve Narofffa465d12007-10-02 20:01:56 +00002121 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002122 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002123{
Steve Narofffa465d12007-10-02 20:01:56 +00002124 assert(receiverName && "missing receiver class name");
Steve Naroffc39ca262007-09-18 23:55:05 +00002125
Steve Naroff52664182007-10-16 23:12:48 +00002126 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002127 ObjcInterfaceDecl* ClassDecl = 0;
2128 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2129 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahanian342f3602007-11-12 20:20:37 +00002130 if (ClassDecl && CurMethodDecl->isInstance()) {
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002131 IdentifierInfo &II = Context.Idents.get("self");
2132 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II,
2133 false);
2134 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2135 superTy = Context.getPointerType(superTy);
2136 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2137 SourceLocation(), ReceiverExpr.Val);
2138
2139 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002140 Args, NumArgs);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002141 }
2142 // class method
2143 if (ClassDecl)
2144 receiverName = ClassDecl->getIdentifier();
2145 }
2146 else
2147 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Narofffa465d12007-10-02 20:01:56 +00002148 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002149 QualType returnType;
Steve Naroff75c4baf2007-11-05 15:27:52 +00002150
2151 // Before we give up, check if the selector is an instance method.
2152 if (!Method)
2153 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002154 if (!Method) {
2155 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2156 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002157 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002158 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002159 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002160 if (Sel.getNumArgs()) {
2161 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2162 return true;
2163 }
Steve Naroff7e461452007-10-16 20:39:36 +00002164 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002165 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
Steve Naroff9f176d12007-11-15 13:05:42 +00002166 lbrac, rbrac, ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002167}
2168
Steve Naroff4ed9d662007-09-27 14:38:14 +00002169// ActOnInstanceMessage - used for both unary and keyword messages.
2170// ArgExprs is optional - if it is present, the number of expressions
2171// is obtained from Sel.getNumArgs().
2172Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroff6cb1d362007-09-28 22:22:11 +00002173 ExprTy *receiver, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002174 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff4ed9d662007-09-27 14:38:14 +00002175{
Steve Naroffc39ca262007-09-18 23:55:05 +00002176 assert(receiver && "missing receiver expression");
2177
Steve Naroff52664182007-10-16 23:12:48 +00002178 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroffc39ca262007-09-18 23:55:05 +00002179 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Narofffa465d12007-10-02 20:01:56 +00002180 QualType receiverType = RExpr->getType();
Steve Naroffee1de132007-10-10 21:53:07 +00002181 QualType returnType;
Steve Naroff1e1c3912007-11-03 16:37:59 +00002182 ObjcMethodDecl *Method;
Steve Naroffee1de132007-10-10 21:53:07 +00002183
Steve Naroff0091d142007-11-11 17:52:25 +00002184 if (receiverType == Context.getObjcIdType() ||
2185 receiverType == Context.getObjcClassType()) {
Steve Naroff1e1c3912007-11-03 16:37:59 +00002186 Method = InstanceMethodPool[Sel].Method;
Steve Naroffd0cfcd02007-11-13 04:10:18 +00002187 // If we didn't find an public method, look for a private one.
2188 if (!Method && CurMethodDecl) {
2189 NamedDecl *impCxt = CurMethodDecl->getMethodContext();
2190 if (ObjcImplementationDecl *IMD =
2191 dyn_cast<ObjcImplementationDecl>(impCxt)) {
2192 if (receiverType == Context.getObjcIdType())
2193 Method = IMD->lookupInstanceMethod(Sel);
2194 else
2195 Method = IMD->lookupClassMethod(Sel);
2196 } else if (ObjcCategoryImplDecl *CID =
2197 dyn_cast<ObjcCategoryImplDecl>(impCxt)) {
2198 if (receiverType == Context.getObjcIdType())
2199 Method = CID->lookupInstanceMethod(Sel);
2200 else
2201 Method = CID->lookupClassMethod(Sel);
2202 }
2203 }
Steve Naroff7e461452007-10-16 20:39:36 +00002204 if (!Method) {
2205 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2206 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002207 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002208 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002209 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002210 if (Sel.getNumArgs())
2211 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2212 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002213 }
Steve Naroffee1de132007-10-10 21:53:07 +00002214 } else {
Chris Lattner71c01112007-10-10 23:42:28 +00002215 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2216 // revisited. how do we get the ClassDecl from the receiver expression?
Steve Naroffee1de132007-10-10 21:53:07 +00002217 while (receiverType->isPointerType()) {
Chris Lattner71c01112007-10-10 23:42:28 +00002218 PointerType *pointerType =
2219 static_cast<PointerType*>(receiverType.getTypePtr());
Steve Naroffee1de132007-10-10 21:53:07 +00002220 receiverType = pointerType->getPointeeType();
2221 }
Chris Lattner71c01112007-10-10 23:42:28 +00002222 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2223 "bad receiver type");
Steve Naroffee1de132007-10-10 21:53:07 +00002224 ObjcInterfaceDecl* ClassDecl = static_cast<ObjcInterfaceType*>(
2225 receiverType.getTypePtr())->getDecl();
Steve Naroff7e461452007-10-16 20:39:36 +00002226 // FIXME: consider using InstanceMethodPool, since it will be faster
2227 // than the following method (which can do *many* linear searches). The
2228 // idea is to add class info to InstanceMethodPool...
Steve Naroff1e1c3912007-11-03 16:37:59 +00002229 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002230 if (!Method) {
Steve Naroffb1c7ad92007-11-11 00:10:47 +00002231 // If we have an implementation in scope, check "private" methods.
2232 if (ObjcImplementationDecl *ImpDecl =
2233 ObjcImplementations[ClassDecl->getIdentifier()])
2234 Method = ImpDecl->lookupInstanceMethod(Sel);
2235 }
2236 if (!Method) {
Steve Naroff7e461452007-10-16 20:39:36 +00002237 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2238 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002239 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002240 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002241 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002242 if (Sel.getNumArgs())
2243 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2244 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002245 }
Steve Narofffa465d12007-10-02 20:01:56 +00002246 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002247 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002248 ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002249}