blob: 3fa159eb4463ad25aeb8cfea08ac48cd9eeb0b30 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenek588e5eb2007-11-25 00:58:00 +000015#include "SemaUtil.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
Steve Naroff6a8a9a42007-10-02 20:01:56 +000018#include "clang/AST/DeclObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/AST/Expr.h"
Steve Naroff563477d2007-09-18 23:55:05 +000020#include "clang/Parse/DeclSpec.h"
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner59907c42007-08-10 20:18:51 +000028#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30
Steve Narofff69936d2007-09-16 03:34:24 +000031/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofff69936d2007-09-16 03:34:24 +000038Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Carlssonee98ac52007-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()));
Reid Spencer5f016e22007-07-11 17:01:13 +000061
62 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
63 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlssonee98ac52007-10-15 02:50:23 +000064 Literal.AnyWide, t,
65 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +000066 StringToks[NumStringToks-1].getLocation());
67}
68
69
Steve Naroff08d92e42007-09-15 18:49:24 +000070/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +000071/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
72/// identifier is used in an function call context.
Steve Naroff08d92e42007-09-15 18:49:24 +000073Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +000074 IdentifierInfo &II,
75 bool HasTrailingLParen) {
76 // Could be enum-constant or decl.
Steve Naroff8c9f13e2007-09-16 16:16:00 +000077 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff7779db42007-11-12 14:29:37 +000086 if (CurMethodDecl) {
87 ObjcInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
88 ObjcInterfaceDecl *clsDeclared;
Steve Naroff7e3411b2007-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 Naroff7779db42007-11-12 14:29:37 +000095 }
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroffe1223f72007-08-28 03:03:08 +0000101 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroff53a32342007-08-28 18:45:29 +0000102 // Only create DeclRefExpr's for valid Decl's.
Steve Naroff5912a352007-08-28 20:14:24 +0000103 if (VD->isInvalidDecl())
Steve Naroffe1223f72007-08-28 03:03:08 +0000104 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000105 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroffe1223f72007-08-28 03:03:08 +0000106 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 if (isa<TypedefDecl>(D))
108 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Fariborz Jahanian5ef404f2007-12-05 18:16:33 +0000109 if (isa<ObjcInterfaceDecl>(D))
110 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000111
112 assert(0 && "Invalid decl");
Chris Lattnereddbe032007-07-21 04:57:45 +0000113 abort();
Reid Spencer5f016e22007-07-11 17:01:13 +0000114}
115
Steve Narofff69936d2007-09-16 03:34:24 +0000116Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000117 tok::TokenKind Kind) {
118 PreDefinedExpr::IdentType IT;
119
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 switch (Kind) {
121 default:
122 assert(0 && "Unknown simple primary expr!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
Anders Carlsson22742662007-07-21 05:21:51 +0000124 IT = PreDefinedExpr::Func;
125 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000126 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000127 IT = PreDefinedExpr::Function;
128 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000129 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000130 IT = PreDefinedExpr::PrettyFunction;
131 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 }
Anders Carlsson22742662007-07-21 05:21:51 +0000133
134 // Pre-defined identifiers are always of type char *.
135 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000136}
137
Steve Narofff69936d2007-09-16 03:34:24 +0000138Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000139 llvm::SmallString<16> CharBuffer;
140 CharBuffer.resize(Tok.getLength());
141 const char *ThisTokBegin = &CharBuffer[0];
142 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
143
144 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
145 Tok.getLocation(), PP);
146 if (Literal.hadError())
147 return ExprResult(true);
148 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
149 Tok.getLocation());
150}
151
Steve Narofff69936d2007-09-16 03:34:24 +0000152Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 // fast path for a single digit (which is quite common). A single digit
154 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
155 if (Tok.getLength() == 1) {
156 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
157
Chris Lattner701e5eb2007-09-04 02:45:27 +0000158 unsigned IntSize = static_cast<unsigned>(
159 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000160 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
161 Context.IntTy,
162 Tok.getLocation()));
163 }
164 llvm::SmallString<512> IntegerBuffer;
165 IntegerBuffer.resize(Tok.getLength());
166 const char *ThisTokBegin = &IntegerBuffer[0];
167
168 // Get the spelling of the token, which eliminates trigraphs, etc.
169 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
170 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
171 Tok.getLocation(), PP);
172 if (Literal.hadError)
173 return ExprResult(true);
174
Chris Lattner5d661452007-08-26 03:42:43 +0000175 Expr *Res;
176
177 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000178 QualType Ty;
179 const llvm::fltSemantics *Format;
180 uint64_t Size; unsigned Align;
181
182 if (Literal.isFloat) {
183 Ty = Context.FloatTy;
184 Context.Target.getFloatInfo(Size, Align, Format, Tok.getLocation());
185 } else if (Literal.isLong) {
186 Ty = Context.LongDoubleTy;
187 Context.Target.getLongDoubleInfo(Size, Align, Format, Tok.getLocation());
188 } else {
189 Ty = Context.DoubleTy;
190 Context.Target.getDoubleInfo(Size, Align, Format, Tok.getLocation());
191 }
192
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000193 // isExact will be set by GetFloatValue().
194 bool isExact = false;
195
196 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
197 Ty, Tok.getLocation());
198
Chris Lattner5d661452007-08-26 03:42:43 +0000199 } else if (!Literal.isIntegerLiteral()) {
200 return ExprResult(true);
201 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000202 QualType t;
203
Neil Boothb9449512007-08-29 22:00:19 +0000204 // long long is a C99 feature.
205 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000206 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000207 Diag(Tok.getLocation(), diag::ext_longlong);
208
Reid Spencer5f016e22007-07-11 17:01:13 +0000209 // Get the value in the widest-possible width.
210 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
211
212 if (Literal.GetIntegerValue(ResultVal)) {
213 // If this value didn't fit into uintmax_t, warn and force to ull.
214 Diag(Tok.getLocation(), diag::warn_integer_too_large);
215 t = Context.UnsignedLongLongTy;
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000216 assert(Context.getTypeSize(t, Tok.getLocation()) ==
Reid Spencer5f016e22007-07-11 17:01:13 +0000217 ResultVal.getBitWidth() && "long long is not intmax_t?");
218 } else {
219 // If this value fits into a ULL, try to figure out what else it fits into
220 // according to the rules of C99 6.4.4.1p5.
221
222 // Octal, Hexadecimal, and integers with a U suffix are allowed to
223 // be an unsigned int.
224 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
225
226 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner97c51562007-08-23 21:58:08 +0000227 if (!Literal.isLong && !Literal.isLongLong) {
228 // Are int/unsigned possibilities?
Chris Lattner701e5eb2007-09-04 02:45:27 +0000229 unsigned IntSize = static_cast<unsigned>(
230 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000231 // Does it fit in a unsigned int?
232 if (ResultVal.isIntN(IntSize)) {
233 // Does it fit in a signed int?
234 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
235 t = Context.IntTy;
236 else if (AllowUnsigned)
237 t = Context.UnsignedIntTy;
238 }
239
240 if (!t.isNull())
241 ResultVal.trunc(IntSize);
242 }
243
244 // Are long/unsigned long possibilities?
245 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner701e5eb2007-09-04 02:45:27 +0000246 unsigned LongSize = static_cast<unsigned>(
247 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000248
249 // Does it fit in a unsigned long?
250 if (ResultVal.isIntN(LongSize)) {
251 // Does it fit in a signed long?
252 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
253 t = Context.LongTy;
254 else if (AllowUnsigned)
255 t = Context.UnsignedLongTy;
256 }
257 if (!t.isNull())
258 ResultVal.trunc(LongSize);
259 }
260
261 // Finally, check long long if needed.
262 if (t.isNull()) {
Chris Lattner701e5eb2007-09-04 02:45:27 +0000263 unsigned LongLongSize = static_cast<unsigned>(
264 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000265
266 // Does it fit in a unsigned long long?
267 if (ResultVal.isIntN(LongLongSize)) {
268 // Does it fit in a signed long long?
269 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
270 t = Context.LongLongTy;
271 else if (AllowUnsigned)
272 t = Context.UnsignedLongLongTy;
273 }
274 }
275
276 // If we still couldn't decide a type, we probably have something that
277 // does not fit in a signed long long, but has no U suffix.
278 if (t.isNull()) {
279 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
280 t = Context.UnsignedLongLongTy;
281 }
282 }
283
Chris Lattner5d661452007-08-26 03:42:43 +0000284 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000285 }
Chris Lattner5d661452007-08-26 03:42:43 +0000286
287 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
288 if (Literal.isImaginary)
289 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
290
291 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000292}
293
Steve Narofff69936d2007-09-16 03:34:24 +0000294Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000295 ExprTy *Val) {
296 Expr *e = (Expr *)Val;
Steve Narofff69936d2007-09-16 03:34:24 +0000297 assert((e != 0) && "ActOnParenExpr() missing expr");
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 return new ParenExpr(L, R, e);
299}
300
301/// The UsualUnaryConversions() function is *not* called by this routine.
302/// See C99 6.3.2.1p[2-4] for more details.
303QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
304 SourceLocation OpLoc, bool isSizeof) {
305 // C99 6.5.3.4p1:
306 if (isa<FunctionType>(exprType) && isSizeof)
307 // alignof(function) is allowed.
308 Diag(OpLoc, diag::ext_sizeof_function_type);
309 else if (exprType->isVoidType())
310 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
311 else if (exprType->isIncompleteType()) {
312 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
313 diag::err_alignof_incomplete_type,
314 exprType.getAsString());
315 return QualType(); // error
316 }
317 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
318 return Context.getSizeType();
319}
320
321Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000322ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +0000323 SourceLocation LPLoc, TypeTy *Ty,
324 SourceLocation RPLoc) {
325 // If error parsing type, ignore.
326 if (Ty == 0) return true;
327
328 // Verify that this is a valid expression.
329 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
330
331 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
332
333 if (resultType.isNull())
334 return true;
335 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
336}
337
Chris Lattner5d794252007-08-24 21:41:10 +0000338QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000339 DefaultFunctionArrayConversion(V);
340
Chris Lattnercc26ed72007-08-26 05:39:26 +0000341 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000342 if (const ComplexType *CT = V->getType()->getAsComplexType())
343 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000344
345 // Otherwise they pass through real integer and floating point types here.
346 if (V->getType()->isArithmeticType())
347 return V->getType();
348
349 // Reject anything else.
350 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
351 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000352}
353
354
Reid Spencer5f016e22007-07-11 17:01:13 +0000355
Steve Narofff69936d2007-09-16 03:34:24 +0000356Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000357 tok::TokenKind Kind,
358 ExprTy *Input) {
359 UnaryOperator::Opcode Opc;
360 switch (Kind) {
361 default: assert(0 && "Unknown unary op!");
362 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
363 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
364 }
365 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
366 if (result.isNull())
367 return true;
368 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
369}
370
371Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000372ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000374 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000375
376 // Perform default conversions.
377 DefaultFunctionArrayConversion(LHSExp);
378 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000379
Chris Lattner12d9ff62007-07-16 00:14:47 +0000380 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000381
Reid Spencer5f016e22007-07-11 17:01:13 +0000382 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000383 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000384 // in the subscript position. As a result, we need to derive the array base
385 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000386 Expr *BaseExpr, *IndexExpr;
387 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000388 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000389 BaseExpr = LHSExp;
390 IndexExpr = RHSExp;
391 // FIXME: need to deal with const...
392 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000393 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000394 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000395 BaseExpr = RHSExp;
396 IndexExpr = LHSExp;
397 // FIXME: need to deal with const...
398 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000399 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
400 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000401 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000402
403 // Component access limited to variables (reject vec4.rg[1]).
404 if (!isa<DeclRefExpr>(BaseExpr))
405 return Diag(LLoc, diag::err_ocuvector_component_access,
406 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000407 // FIXME: need to deal with const...
408 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000410 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
411 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 }
413 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000414 if (!IndexExpr->getType()->isIntegerType())
415 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
416 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000417
Chris Lattner12d9ff62007-07-16 00:14:47 +0000418 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
419 // the following check catches trying to index a pointer to a function (e.g.
420 // void (*)(int)). Functions are not objects in C99.
421 if (!ResultType->isObjectType())
422 return Diag(BaseExpr->getLocStart(),
423 diag::err_typecheck_subscript_not_object,
424 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
425
426 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000427}
428
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000429QualType Sema::
430CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
431 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnerc8629632007-07-31 19:29:30 +0000432 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000433
434 // The vector accessor can't exceed the number of elements.
435 const char *compStr = CompName.getName();
436 if (strlen(compStr) > vecType->getNumElements()) {
437 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
438 baseType.getAsString(), SourceRange(CompLoc));
439 return QualType();
440 }
441 // The component names must come from the same set.
Chris Lattner88dca042007-08-02 22:33:49 +0000442 if (vecType->getPointAccessorIdx(*compStr) != -1) {
443 do
444 compStr++;
445 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
446 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
447 do
448 compStr++;
449 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
450 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
451 do
452 compStr++;
453 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
454 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000455
456 if (*compStr) {
457 // We didn't get to the end of the string. This means the component names
458 // didn't come from the same set *or* we encountered an illegal name.
459 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
460 std::string(compStr,compStr+1), SourceRange(CompLoc));
461 return QualType();
462 }
463 // Each component accessor can't exceed the vector type.
464 compStr = CompName.getName();
465 while (*compStr) {
466 if (vecType->isAccessorWithinNumElements(*compStr))
467 compStr++;
468 else
469 break;
470 }
471 if (*compStr) {
472 // We didn't get to the end of the string. This means a component accessor
473 // exceeds the number of elements in the vector.
474 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
475 baseType.getAsString(), SourceRange(CompLoc));
476 return QualType();
477 }
478 // The component accessor looks fine - now we need to compute the actual type.
479 // The vector type is implied by the component accessor. For example,
480 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
481 unsigned CompSize = strlen(CompName.getName());
482 if (CompSize == 1)
483 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000484
485 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
486 // Now look up the TypeDefDecl from the vector type. Without this,
487 // diagostics look bad. We want OCU vector types to appear built-in.
488 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
489 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
490 return Context.getTypedefType(OCUVectorDecls[i]);
491 }
492 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000493}
494
Reid Spencer5f016e22007-07-11 17:01:13 +0000495Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000496ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000497 tok::TokenKind OpKind, SourceLocation MemberLoc,
498 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000499 Expr *BaseExpr = static_cast<Expr *>(Base);
500 assert(BaseExpr && "no record expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000501
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000502 QualType BaseType = BaseExpr->getType();
503 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000504
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000506 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000507 BaseType = PT->getPointeeType();
508 else
509 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
510 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000511 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000512 // The base type is either a record or an OCUVectorType.
Chris Lattnerc8629632007-07-31 19:29:30 +0000513 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000514 RecordDecl *RDecl = RTy->getDecl();
515 if (RTy->isIncompleteType())
516 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
517 BaseExpr->getSourceRange());
518 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000519 FieldDecl *MemberDecl = RDecl->getMember(&Member);
520 if (!MemberDecl)
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000521 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
522 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000523 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
524 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff608e0ee2007-08-03 22:40:33 +0000525 // Component access limited to variables (reject vec4.rg.g).
526 if (!isa<DeclRefExpr>(BaseExpr))
527 return Diag(OpLoc, diag::err_ocuvector_component_access,
528 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000529 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
530 if (ret.isNull())
531 return true;
Chris Lattner6481a572007-08-03 17:31:20 +0000532 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000533 } else if (BaseType->isObjcInterfaceType()) {
534 ObjcInterfaceDecl *IFace;
535 if (isa<ObjcInterfaceType>(BaseType.getCanonicalType()))
536 IFace = dyn_cast<ObjcInterfaceType>(BaseType)->getDecl();
537 else
538 IFace = dyn_cast<ObjcQualifiedInterfaceType>(BaseType)
539 ->getInterfaceType()->getDecl();
540 ObjcInterfaceDecl *clsDeclared;
541 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
542 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
543 OpKind==tok::arrow);
544 }
545 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
546 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000547}
548
Steve Narofff69936d2007-09-16 03:34:24 +0000549/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +0000550/// This provides the location of the left/right parens and a list of comma
551/// locations.
552Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000553ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner74c469f2007-07-21 03:03:59 +0000554 ExprTy **args, unsigned NumArgsInCall,
Reid Spencer5f016e22007-07-11 17:01:13 +0000555 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000556 Expr *Fn = static_cast<Expr *>(fn);
557 Expr **Args = reinterpret_cast<Expr**>(args);
558 assert(Fn && "no function call expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000559
Chris Lattner74c469f2007-07-21 03:03:59 +0000560 UsualUnaryConversions(Fn);
561 QualType funcType = Fn->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000562
563 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
564 // type pointer to function".
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000565 const PointerType *PT = funcType->getAsPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000566 if (PT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000567 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
568 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000569
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000570 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000571 if (funcT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000572 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
573 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000574
575 // If a prototype isn't declared, the parser implicitly defines a func decl
576 QualType resultType = funcT->getResultType();
577
578 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
579 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
580 // assignment, to the types of the corresponding parameter, ...
581
582 unsigned NumArgsInProto = proto->getNumArgs();
583 unsigned NumArgsToCheck = NumArgsInCall;
584
585 if (NumArgsInCall < NumArgsInProto)
586 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
Chris Lattner74c469f2007-07-21 03:03:59 +0000587 Fn->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000588 else if (NumArgsInCall > NumArgsInProto) {
589 if (!proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +0000590 Diag(Args[NumArgsInProto]->getLocStart(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000591 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +0000592 SourceRange(Args[NumArgsInProto]->getLocStart(),
593 Args[NumArgsInCall-1]->getLocEnd()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 }
595 NumArgsToCheck = NumArgsInProto;
596 }
597 // Continue to check argument types (even if we have too few/many args).
598 for (unsigned i = 0; i < NumArgsToCheck; i++) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000599 Expr *argExpr = Args[i];
Steve Narofff69936d2007-09-16 03:34:24 +0000600 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000601
602 QualType lhsType = proto->getArgType(i);
603 QualType rhsType = argExpr->getType();
Steve Naroff700204c2007-07-24 21:46:40 +0000604
Steve Naroff82c7e6d2007-07-25 20:45:33 +0000605 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnerc8629632007-07-31 19:29:30 +0000606 if (const ArrayType *ary = lhsType->getAsArrayType())
Steve Naroff700204c2007-07-24 21:46:40 +0000607 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff82c7e6d2007-07-25 20:45:33 +0000608 else if (lhsType->isFunctionType())
Steve Naroff700204c2007-07-24 21:46:40 +0000609 lhsType = Context.getPointerType(lhsType);
610
Steve Naroff90045e82007-07-13 23:32:42 +0000611 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
612 argExpr);
Steve Narofff1120de2007-08-24 22:33:52 +0000613 if (Args[i] != argExpr) // The expression was converted.
614 Args[i] = argExpr; // Make sure we store the converted expression.
Reid Spencer5f016e22007-07-11 17:01:13 +0000615 SourceLocation l = argExpr->getLocStart();
616
617 // decode the result (notice that AST's are still created for extensions).
618 switch (result) {
619 case Compatible:
620 break;
621 case PointerFromInt:
Steve Naroff529a4ad2007-11-27 17:58:44 +0000622 Diag(l, diag::ext_typecheck_passing_pointer_int,
623 lhsType.getAsString(), rhsType.getAsString(),
624 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000625 break;
626 case IntFromPointer:
627 Diag(l, diag::ext_typecheck_passing_pointer_int,
628 lhsType.getAsString(), rhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000629 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000630 break;
631 case IncompatiblePointer:
632 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
633 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000634 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000635 break;
636 case CompatiblePointerDiscardsQualifiers:
637 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
638 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000639 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 break;
641 case Incompatible:
642 return Diag(l, diag::err_typecheck_passing_incompatible,
643 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000644 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 }
646 }
Steve Naroffb291ab62007-08-28 23:30:39 +0000647 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
648 // Promote the arguments (C99 6.5.2.2p7).
649 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
650 Expr *argExpr = Args[i];
Steve Narofff69936d2007-09-16 03:34:24 +0000651 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffb291ab62007-08-28 23:30:39 +0000652
653 DefaultArgumentPromotion(argExpr);
654 if (Args[i] != argExpr) // The expression was converted.
655 Args[i] = argExpr; // Make sure we store the converted expression.
656 }
657 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
658 // Even if the types checked, bail if the number of arguments don't match.
Reid Spencer5f016e22007-07-11 17:01:13 +0000659 return true;
Steve Naroffb291ab62007-08-28 23:30:39 +0000660 }
661 } else if (isa<FunctionTypeNoProto>(funcT)) {
662 // Promote the arguments (C99 6.5.2.2p6).
663 for (unsigned i = 0; i < NumArgsInCall; i++) {
664 Expr *argExpr = Args[i];
Steve Narofff69936d2007-09-16 03:34:24 +0000665 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffb291ab62007-08-28 23:30:39 +0000666
667 DefaultArgumentPromotion(argExpr);
668 if (Args[i] != argExpr) // The expression was converted.
669 Args[i] = argExpr; // Make sure we store the converted expression.
670 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000671 }
Chris Lattner59907c42007-08-10 20:18:51 +0000672 // Do special checking on direct calls to functions.
673 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
674 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
675 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000676 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
677 NumArgsInCall))
Anders Carlsson71993dd2007-08-17 05:31:46 +0000678 return true;
Chris Lattner59907c42007-08-10 20:18:51 +0000679
Chris Lattner74c469f2007-07-21 03:03:59 +0000680 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000681}
682
683Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000684ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +0000685 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +0000686 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +0000687 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +0000688 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +0000689 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +0000690 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +0000691
Anders Carlssonb2f08e02007-12-06 20:10:20 +0000692 // FIXME: This is just a temporary workaround to get
693 // test/Parser/compound_literal.c passing. (CheckInitializer does not support
694 // initializing a char array from a single string literal).
695 if (!literalType->isArrayType() ||
696 !literalType->getAsArrayType()->getElementType()->isCharType()) {
697 // FIXME: add more semantic analysis (C99 6.5.2.5).
698 if (CheckInitializer(literalExpr, literalType, false))
699 return 0;
700 }
Anders Carlssond35c8322007-12-05 07:24:19 +0000701
Steve Naroffaff1edd2007-07-19 21:32:11 +0000702 return new CompoundLiteralExpr(literalType, literalExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000703}
704
705Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000706ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000707 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +0000708 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000709
Steve Naroff08d92e42007-09-15 18:49:24 +0000710 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +0000711 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000712
Steve Naroff38374b02007-09-02 20:30:18 +0000713 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
714 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
715 return e;
Steve Naroff4aa88f82007-07-19 01:06:55 +0000716}
717
Anders Carlssona64db8f2007-11-27 05:51:55 +0000718bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty)
719{
720 assert(VectorTy->isVectorType() && "Not a vector type!");
721
722 if (Ty->isVectorType() || Ty->isIntegerType()) {
723 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
724 Context.getTypeSize(Ty, SourceLocation()))
725 return Diag(R.getBegin(),
726 Ty->isVectorType() ?
727 diag::err_invalid_conversion_between_vectors :
728 diag::err_invalid_conversion_between_vector_and_integer,
729 VectorTy.getAsString().c_str(),
730 Ty.getAsString().c_str(), R);
731 } else
732 return Diag(R.getBegin(),
733 diag::err_invalid_conversion_between_vector_and_scalar,
734 VectorTy.getAsString().c_str(),
735 Ty.getAsString().c_str(), R);
736
737 return false;
738}
739
Steve Naroff4aa88f82007-07-19 01:06:55 +0000740Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000741ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +0000742 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +0000743 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +0000744
745 Expr *castExpr = static_cast<Expr*>(Op);
746 QualType castType = QualType::getFromOpaquePtr(Ty);
747
Steve Naroff711602b2007-08-31 00:32:44 +0000748 UsualUnaryConversions(castExpr);
749
Chris Lattner75af4802007-07-18 16:00:06 +0000750 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
751 // type needs to be scalar.
Chris Lattner3da2db42007-10-29 04:26:44 +0000752 if (!castType->isVoidType()) { // Cast to void allows any expr type.
753 if (!castType->isScalarType())
754 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
755 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Anders Carlssona64db8f2007-11-27 05:51:55 +0000756 if (!castExpr->getType()->isScalarType())
Chris Lattner3da2db42007-10-29 04:26:44 +0000757 return Diag(castExpr->getLocStart(),
758 diag::err_typecheck_expect_scalar_operand,
759 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssona64db8f2007-11-27 05:51:55 +0000760
761 if (castExpr->getType()->isVectorType()) {
762 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
763 castExpr->getType(), castType))
764 return true;
765 } else if (castType->isVectorType()) {
766 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
767 castType, castExpr->getType()))
768 return true;
Chris Lattner3da2db42007-10-29 04:26:44 +0000769 }
Steve Naroff16beff82007-07-16 23:25:18 +0000770 }
771 return new CastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000772}
773
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000774// promoteExprToType - a helper function to ensure we create exactly one
775// ImplicitCastExpr.
776static void promoteExprToType(Expr *&expr, QualType type) {
777 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
778 impCast->setType(type);
779 else
780 expr = new ImplicitCastExpr(type, expr);
781 return;
782}
783
Chris Lattnera21ddb32007-11-26 01:40:58 +0000784/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
785/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +0000786inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +0000787 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000788 UsualUnaryConversions(cond);
789 UsualUnaryConversions(lex);
790 UsualUnaryConversions(rex);
791 QualType condT = cond->getType();
792 QualType lexT = lex->getType();
793 QualType rexT = rex->getType();
794
Reid Spencer5f016e22007-07-11 17:01:13 +0000795 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +0000796 if (!condT->isScalarType()) { // C99 6.5.15p2
797 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
798 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +0000799 return QualType();
800 }
801 // now check the two expressions.
Steve Naroffa4332e22007-07-17 00:58:39 +0000802 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
803 UsualArithmeticConversions(lex, rex);
804 return lex->getType();
805 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000806 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
807 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
Chris Lattnera21ddb32007-11-26 01:40:58 +0000808 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000809 return lexT;
810
Reid Spencer5f016e22007-07-11 17:01:13 +0000811 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000812 lexT.getAsString(), rexT.getAsString(),
813 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000814 return QualType();
815 }
816 }
Chris Lattner590b6642007-07-15 23:26:56 +0000817 // C99 6.5.15p3
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000818 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
819 promoteExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff49b45262007-07-13 16:58:59 +0000820 return lexT;
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000821 }
822 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
823 promoteExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff49b45262007-07-13 16:58:59 +0000824 return rexT;
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000825 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000826 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
827 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
828 // get the "pointed to" types
829 QualType lhptee = LHSPT->getPointeeType();
830 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000831
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000832 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
833 if (lhptee->isVoidType() &&
834 (rhptee->isObjectType() || rhptee->isIncompleteType()))
835 return lexT;
836 if (rhptee->isVoidType() &&
837 (lhptee->isObjectType() || lhptee->isIncompleteType()))
838 return rexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000839
Steve Naroffec0550f2007-10-15 20:41:53 +0000840 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
841 rhptee.getUnqualifiedType())) {
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000842 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
843 lexT.getAsString(), rexT.getAsString(),
844 lex->getSourceRange(), rex->getSourceRange());
845 return lexT; // FIXME: this is an _ext - is this return o.k?
846 }
847 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000848 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
849 // differently qualified versions of compatible types, the result type is
850 // a pointer to an appropriately qualified version of the *composite*
851 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000852 return lexT; // FIXME: Need to return the composite type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000853 }
854 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000855
Steve Naroff49b45262007-07-13 16:58:59 +0000856 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
857 return lexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000858
859 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000860 lexT.getAsString(), rexT.getAsString(),
861 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000862 return QualType();
863}
864
Steve Narofff69936d2007-09-16 03:34:24 +0000865/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +0000866/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +0000867Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000868 SourceLocation ColonLoc,
869 ExprTy *Cond, ExprTy *LHS,
870 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +0000871 Expr *CondExpr = (Expr *) Cond;
872 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +0000873
874 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
875 // was the condition.
876 bool isLHSNull = LHSExpr == 0;
877 if (isLHSNull)
878 LHSExpr = CondExpr;
879
Chris Lattner26824902007-07-16 21:39:03 +0000880 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
881 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000882 if (result.isNull())
883 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +0000884 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
885 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000886}
887
Steve Naroffb291ab62007-08-28 23:30:39 +0000888/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
889/// do not have a prototype. Integer promotions are performed on each
890/// argument, and arguments that have type float are promoted to double.
891void Sema::DefaultArgumentPromotion(Expr *&expr) {
892 QualType t = expr->getType();
893 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
894
895 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
896 promoteExprToType(expr, Context.IntTy);
897 if (t == Context.FloatTy)
898 promoteExprToType(expr, Context.DoubleTy);
899}
900
Steve Narofffa2eaab2007-07-15 02:02:06 +0000901/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000902void Sema::DefaultFunctionArrayConversion(Expr *&e) {
Steve Narofffa2eaab2007-07-15 02:02:06 +0000903 QualType t = e->getType();
Steve Naroff90045e82007-07-13 23:32:42 +0000904 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
Bill Wendling08ad47c2007-07-17 03:52:31 +0000905
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000906 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000907 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
908 t = e->getType();
909 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000910 if (t->isFunctionType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000911 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnerc8629632007-07-31 19:29:30 +0000912 else if (const ArrayType *ary = t->getAsArrayType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000913 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000914}
915
916/// UsualUnaryConversion - Performs various conversions that are common to most
917/// operators (C99 6.3). The conversions of array and function types are
918/// sometimes surpressed. For example, the array->pointer conversion doesn't
919/// apply if the array is an argument to the sizeof or address (&) operators.
920/// In these instances, this routine should *not* be called.
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000921void Sema::UsualUnaryConversions(Expr *&expr) {
Steve Naroff49b45262007-07-13 16:58:59 +0000922 QualType t = expr->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000923 assert(!t.isNull() && "UsualUnaryConversions - missing type");
924
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000925 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000926 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
927 t = expr->getType();
928 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000929 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000930 promoteExprToType(expr, Context.IntTy);
931 else
932 DefaultFunctionArrayConversion(expr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000933}
934
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000935/// UsualArithmeticConversions - Performs various conversions that are common to
Reid Spencer5f016e22007-07-11 17:01:13 +0000936/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
937/// routine returns the first non-arithmetic type found. The client is
938/// responsible for emitting appropriate error diagnostics.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000939QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
940 bool isCompAssign) {
Steve Naroff8702a0f2007-08-25 19:54:59 +0000941 if (!isCompAssign) {
942 UsualUnaryConversions(lhsExpr);
943 UsualUnaryConversions(rhsExpr);
944 }
Steve Naroff3187e202007-10-18 18:55:53 +0000945 // For conversion purposes, we ignore any qualifiers.
946 // For example, "const float" and "float" are equivalent.
Steve Narofff68a63f2007-11-10 19:45:54 +0000947 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
948 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000949
950 // If both types are identical, no conversion is needed.
Steve Naroff3187e202007-10-18 18:55:53 +0000951 if (lhs == rhs)
952 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000953
954 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
955 // The caller can deal with this (e.g. pointer + int).
Steve Naroffa4332e22007-07-17 00:58:39 +0000956 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000957 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000958
959 // At this point, we have two different arithmetic types.
960
961 // Handle complex types first (C99 6.3.1.8p1).
962 if (lhs->isComplexType() || rhs->isComplexType()) {
963 // if we have an integer operand, the result is the complex type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000964 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000965 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
966 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000967 }
968 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000969 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
970 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000971 }
Steve Narofff1448a02007-08-27 01:27:54 +0000972 // This handles complex/complex, complex/float, or float/complex.
973 // When both operands are complex, the shorter operand is converted to the
974 // type of the longer, and that is the type of the result. This corresponds
975 // to what is done when combining two real floating-point operands.
976 // The fun begins when size promotion occur across type domains.
977 // From H&S 6.3.4: When one operand is complex and the other is a real
978 // floating-point type, the less precise type is converted, within it's
979 // real or complex domain, to the precision of the other type. For example,
980 // when combining a "long double" with a "double _Complex", the
981 // "double _Complex" is promoted to "long double _Complex".
Steve Narofffb0d4962007-08-27 15:30:22 +0000982 int result = Context.compareFloatingType(lhs, rhs);
983
984 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff55fe4552007-08-27 21:32:55 +0000985 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
986 if (!isCompAssign)
987 promoteExprToType(rhsExpr, rhs);
988 } else if (result < 0) { // The right side is bigger, convert lhs.
989 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
990 if (!isCompAssign)
991 promoteExprToType(lhsExpr, lhs);
992 }
993 // At this point, lhs and rhs have the same rank/size. Now, make sure the
994 // domains match. This is a requirement for our implementation, C99
995 // does not require this promotion.
996 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
997 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff29960362007-08-27 21:43:43 +0000998 if (!isCompAssign)
999 promoteExprToType(lhsExpr, rhs);
1000 return rhs;
Steve Naroff55fe4552007-08-27 21:32:55 +00001001 } else { // handle "_Complex double, double".
Steve Naroff29960362007-08-27 21:43:43 +00001002 if (!isCompAssign)
1003 promoteExprToType(rhsExpr, lhs);
1004 return lhs;
Steve Naroff55fe4552007-08-27 21:32:55 +00001005 }
Steve Naroffa4332e22007-07-17 00:58:39 +00001006 }
Steve Naroff29960362007-08-27 21:43:43 +00001007 return lhs; // The domain/size match exactly.
Reid Spencer5f016e22007-07-11 17:01:13 +00001008 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001009 // Now handle "real" floating types (i.e. float, double, long double).
1010 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1011 // if we have an integer operand, the result is the real floating type.
Steve Naroffa4332e22007-07-17 00:58:39 +00001012 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001013 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1014 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001015 }
1016 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001017 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
1018 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001019 }
Steve Narofffa2eaab2007-07-15 02:02:06 +00001020 // We have two real floating types, float/complex combos were handled above.
1021 // Convert the smaller operand to the bigger result.
Steve Narofffb0d4962007-08-27 15:30:22 +00001022 int result = Context.compareFloatingType(lhs, rhs);
1023
1024 if (result > 0) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001025 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1026 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001027 }
Steve Narofffb0d4962007-08-27 15:30:22 +00001028 if (result < 0) { // convert the lhs
1029 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1030 return rhs;
1031 }
1032 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Reid Spencer5f016e22007-07-11 17:01:13 +00001033 }
Steve Narofffa2eaab2007-07-15 02:02:06 +00001034 // Finally, we have two differing integer types.
Steve Naroffa4332e22007-07-17 00:58:39 +00001035 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001036 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1037 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001038 }
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001039 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1040 return rhs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001041}
1042
1043// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1044// being closely modeled after the C99 spec:-). The odd characteristic of this
1045// routine is it effectively iqnores the qualifiers on the top level pointee.
1046// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1047// FIXME: add a couple examples in this comment.
1048Sema::AssignmentCheckResult
1049Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1050 QualType lhptee, rhptee;
1051
1052 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001053 lhptee = lhsType->getAsPointerType()->getPointeeType();
1054 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001055
1056 // make sure we operate on the canonical type
1057 lhptee = lhptee.getCanonicalType();
1058 rhptee = rhptee.getCanonicalType();
1059
1060 AssignmentCheckResult r = Compatible;
1061
1062 // C99 6.5.16.1p1: This following citation is common to constraints
1063 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1064 // qualifiers of the type *pointed to* by the right;
1065 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1066 rhptee.getQualifiers())
1067 r = CompatiblePointerDiscardsQualifiers;
1068
1069 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1070 // incomplete type and the other is a pointer to a qualified or unqualified
1071 // version of void...
1072 if (lhptee.getUnqualifiedType()->isVoidType() &&
1073 (rhptee->isObjectType() || rhptee->isIncompleteType()))
1074 ;
1075 else if (rhptee.getUnqualifiedType()->isVoidType() &&
1076 (lhptee->isObjectType() || lhptee->isIncompleteType()))
1077 ;
1078 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1079 // unqualified versions of compatible types, ...
Steve Naroffec0550f2007-10-15 20:41:53 +00001080 else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1081 rhptee.getUnqualifiedType()))
Reid Spencer5f016e22007-07-11 17:01:13 +00001082 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1083 return r;
1084}
1085
1086/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1087/// has code to accommodate several GCC extensions when type checking
1088/// pointers. Here are some objectionable examples that GCC considers warnings:
1089///
1090/// int a, *pint;
1091/// short *pshort;
1092/// struct foo *pfoo;
1093///
1094/// pint = pshort; // warning: assignment from incompatible pointer type
1095/// a = pint; // warning: assignment makes integer from pointer without a cast
1096/// pint = a; // warning: assignment makes pointer from integer without a cast
1097/// pint = pfoo; // warning: assignment from incompatible pointer type
1098///
1099/// As a result, the code for dealing with pointers is more complex than the
1100/// C99 spec dictates.
1101/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1102///
1103Sema::AssignmentCheckResult
1104Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Steve Naroff8eabdff2007-11-13 00:31:42 +00001105 if (lhsType.getCanonicalType().getUnqualifiedType() ==
1106 rhsType.getCanonicalType().getUnqualifiedType())
Chris Lattner84d35ce2007-10-29 05:15:40 +00001107 return Compatible; // common case, fast path...
Steve Naroff700204c2007-07-24 21:46:40 +00001108
Anders Carlsson793680e2007-10-12 23:56:29 +00001109 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroffec0550f2007-10-15 20:41:53 +00001110 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001111 return Compatible;
1112 } else if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001113 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Anders Carlsson695dbb62007-11-30 04:21:22 +00001114 if (!getLangOptions().LaxVectorConversions) {
1115 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1116 return Incompatible;
1117 } else {
1118 if (lhsType->isVectorType() && rhsType->isVectorType()) {
1119 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1120 (lhsType->isRealFloatingType() &&
1121 rhsType->isRealFloatingType())) {
1122 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1123 Context.getTypeSize(rhsType, SourceLocation()))
1124 return Compatible;
1125 }
1126 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001127 return Incompatible;
Anders Carlsson695dbb62007-11-30 04:21:22 +00001128 }
1129 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001130 return Compatible;
1131 } else if (lhsType->isPointerType()) {
1132 if (rhsType->isIntegerType())
1133 return PointerFromInt;
1134
1135 if (rhsType->isPointerType())
1136 return CheckPointerTypesForAssignment(lhsType, rhsType);
1137 } else if (rhsType->isPointerType()) {
1138 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1139 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1140 return IntFromPointer;
1141
1142 if (lhsType->isPointerType())
1143 return CheckPointerTypesForAssignment(lhsType, rhsType);
1144 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroffec0550f2007-10-15 20:41:53 +00001145 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001146 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001147 }
1148 return Incompatible;
1149}
1150
Steve Naroff90045e82007-07-13 23:32:42 +00001151Sema::AssignmentCheckResult
1152Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroff529a4ad2007-11-27 17:58:44 +00001153 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1154 // a null pointer constant.
1155 if (lhsType->isPointerType() && rExpr->isNullPointerConstant(Context)) {
1156 promoteExprToType(rExpr, lhsType);
1157 return Compatible;
1158 }
Chris Lattner943140e2007-10-16 02:55:40 +00001159 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001160 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001161 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001162 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001163 //
1164 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1165 // are better understood.
1166 if (!lhsType->isReferenceType())
1167 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001168
1169 Sema::AssignmentCheckResult result;
Steve Naroff90045e82007-07-13 23:32:42 +00001170
Steve Narofff1120de2007-08-24 22:33:52 +00001171 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1172
1173 // C99 6.5.16.1p2: The value of the right operand is converted to the
1174 // type of the assignment expression.
1175 if (rExpr->getType() != lhsType)
1176 promoteExprToType(rExpr, lhsType);
1177 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001178}
1179
1180Sema::AssignmentCheckResult
1181Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1182 return CheckAssignmentConstraints(lhsType, rhsType);
1183}
1184
Steve Naroff49b45262007-07-13 16:58:59 +00001185inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001186 Diag(loc, diag::err_typecheck_invalid_operands,
1187 lex->getType().getAsString(), rex->getType().getAsString(),
1188 lex->getSourceRange(), rex->getSourceRange());
1189}
1190
Steve Naroff49b45262007-07-13 16:58:59 +00001191inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1192 Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001193 QualType lhsType = lex->getType(), rhsType = rex->getType();
1194
1195 // make sure the vector types are identical.
1196 if (lhsType == rhsType)
1197 return lhsType;
1198 // You cannot convert between vector values of different size.
1199 Diag(loc, diag::err_typecheck_vector_not_convertable,
1200 lex->getType().getAsString(), rex->getType().getAsString(),
1201 lex->getSourceRange(), rex->getSourceRange());
1202 return QualType();
1203}
1204
1205inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001206 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001207{
Steve Naroff90045e82007-07-13 23:32:42 +00001208 QualType lhsType = lex->getType(), rhsType = rex->getType();
1209
1210 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001211 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001212
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001213 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001214
Steve Naroffa4332e22007-07-17 00:58:39 +00001215 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001216 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001217 InvalidOperands(loc, lex, rex);
1218 return QualType();
1219}
1220
1221inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001222 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001223{
Steve Naroff90045e82007-07-13 23:32:42 +00001224 QualType lhsType = lex->getType(), rhsType = rex->getType();
1225
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001226 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001227
Steve Naroffa4332e22007-07-17 00:58:39 +00001228 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001229 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001230 InvalidOperands(loc, lex, rex);
1231 return QualType();
1232}
1233
1234inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001235 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001236{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001237 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001238 return CheckVectorOperands(loc, lex, rex);
1239
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001240 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Steve Naroff3e5e5562007-07-16 22:23:01 +00001241
Reid Spencer5f016e22007-07-11 17:01:13 +00001242 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001243 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001244 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001245
Steve Naroffa4332e22007-07-17 00:58:39 +00001246 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1247 return lex->getType();
1248 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1249 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001250 InvalidOperands(loc, lex, rex);
1251 return QualType();
1252}
1253
1254inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001255 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001256{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001257 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001258 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001259
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001260 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001261
Chris Lattner6e4ab612007-12-09 21:53:25 +00001262 // Enforce type constraints: C99 6.5.6p3.
1263
1264 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001265 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001266 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001267
1268 // Either ptr - int or ptr - ptr.
1269 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1270 // The LHS must be an object type, not incomplete, function, etc.
1271 if (!LHSPTy->getPointeeType()->isObjectType()) {
1272 // Handle the GNU void* extension.
1273 if (LHSPTy->getPointeeType()->isVoidType()) {
1274 Diag(loc, diag::ext_gnu_void_ptr,
1275 lex->getSourceRange(), rex->getSourceRange());
1276 } else {
1277 Diag(loc, diag::err_typecheck_sub_ptr_object,
1278 lex->getType().getAsString(), lex->getSourceRange());
1279 return QualType();
1280 }
1281 }
1282
1283 // The result type of a pointer-int computation is the pointer type.
1284 if (rex->getType()->isIntegerType())
1285 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001286
Chris Lattner6e4ab612007-12-09 21:53:25 +00001287 // Handle pointer-pointer subtractions.
1288 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1289 // RHS must be an object type, unless void (GNU).
1290 if (!RHSPTy->getPointeeType()->isObjectType()) {
1291 // Handle the GNU void* extension.
1292 if (RHSPTy->getPointeeType()->isVoidType()) {
1293 if (!LHSPTy->getPointeeType()->isVoidType())
1294 Diag(loc, diag::ext_gnu_void_ptr,
1295 lex->getSourceRange(), rex->getSourceRange());
1296 } else {
1297 Diag(loc, diag::err_typecheck_sub_ptr_object,
1298 rex->getType().getAsString(), rex->getSourceRange());
1299 return QualType();
1300 }
1301 }
1302
1303 // Pointee types must be compatible.
1304 if (!Context.typesAreCompatible(LHSPTy->getPointeeType(),
1305 RHSPTy->getPointeeType())) {
1306 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1307 lex->getType().getAsString(), rex->getType().getAsString(),
1308 lex->getSourceRange(), rex->getSourceRange());
1309 return QualType();
1310 }
1311
1312 return Context.getPointerDiffType();
1313 }
1314 }
1315
Reid Spencer5f016e22007-07-11 17:01:13 +00001316 InvalidOperands(loc, lex, rex);
1317 return QualType();
1318}
1319
1320inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001321 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001322{
1323 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1324 // for int << longlong -> the result type should be int, not long long.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001325 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001326
Steve Naroffa4332e22007-07-17 00:58:39 +00001327 // handle the common case first (both operands are arithmetic).
1328 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001329 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001330 InvalidOperands(loc, lex, rex);
1331 return QualType();
1332}
1333
Chris Lattnera5937dd2007-08-26 01:18:55 +00001334inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1335 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Reid Spencer5f016e22007-07-11 17:01:13 +00001336{
Chris Lattnera5937dd2007-08-26 01:18:55 +00001337 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00001338 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1339 UsualArithmeticConversions(lex, rex);
1340 else {
1341 UsualUnaryConversions(lex);
1342 UsualUnaryConversions(rex);
1343 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001344 QualType lType = lex->getType();
1345 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001346
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001347 // For non-floating point types, check for self-comparisons of the form
1348 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1349 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001350 if (!lType->isFloatingType()) {
1351 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1352 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1353 if (DRL->getDecl() == DRR->getDecl())
1354 Diag(loc, diag::warn_selfcomparison);
1355 }
1356
Chris Lattnera5937dd2007-08-26 01:18:55 +00001357 if (isRelational) {
1358 if (lType->isRealType() && rType->isRealType())
1359 return Context.IntTy;
1360 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001361 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001362 if (lType->isFloatingType()) {
1363 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001364 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00001365 }
1366
Chris Lattnera5937dd2007-08-26 01:18:55 +00001367 if (lType->isArithmeticType() && rType->isArithmeticType())
1368 return Context.IntTy;
1369 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001370
Chris Lattnerd28f8152007-08-26 01:10:14 +00001371 bool LHSIsNull = lex->isNullPointerConstant(Context);
1372 bool RHSIsNull = rex->isNullPointerConstant(Context);
1373
Chris Lattnera5937dd2007-08-26 01:18:55 +00001374 // All of the following pointer related warnings are GCC extensions, except
1375 // when handling null pointer constants. One day, we can consider making them
1376 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00001377 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff66296cb2007-11-13 14:57:38 +00001378
1379 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1380 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1381 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroffec0550f2007-10-15 20:41:53 +00001382 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1383 rType.getUnqualifiedType())) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001384 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1385 lType.getAsString(), rType.getAsString(),
1386 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001387 }
Chris Lattnerd28f8152007-08-26 01:10:14 +00001388 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001389 return Context.IntTy;
1390 }
1391 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001392 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001393 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1394 lType.getAsString(), rType.getAsString(),
1395 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001396 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001397 return Context.IntTy;
1398 }
1399 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001400 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001401 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1402 lType.getAsString(), rType.getAsString(),
1403 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001404 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001405 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 }
1407 InvalidOperands(loc, lex, rex);
1408 return QualType();
1409}
1410
Reid Spencer5f016e22007-07-11 17:01:13 +00001411inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001412 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001413{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001414 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001415 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001416
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001417 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001418
Steve Naroffa4332e22007-07-17 00:58:39 +00001419 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001420 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 InvalidOperands(loc, lex, rex);
1422 return QualType();
1423}
1424
1425inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00001426 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001427{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001428 UsualUnaryConversions(lex);
1429 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001430
Steve Naroffa4332e22007-07-17 00:58:39 +00001431 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001432 return Context.IntTy;
1433 InvalidOperands(loc, lex, rex);
1434 return QualType();
1435}
1436
1437inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00001438 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001439{
1440 QualType lhsType = lex->getType();
1441 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1442 bool hadError = false;
1443 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1444
1445 switch (mlval) { // C99 6.5.16p2
1446 case Expr::MLV_Valid:
1447 break;
1448 case Expr::MLV_ConstQualified:
1449 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1450 hadError = true;
1451 break;
1452 case Expr::MLV_ArrayType:
1453 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1454 lhsType.getAsString(), lex->getSourceRange());
1455 return QualType();
1456 case Expr::MLV_NotObjectType:
1457 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1458 lhsType.getAsString(), lex->getSourceRange());
1459 return QualType();
1460 case Expr::MLV_InvalidExpression:
1461 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1462 lex->getSourceRange());
1463 return QualType();
1464 case Expr::MLV_IncompleteType:
1465 case Expr::MLV_IncompleteVoidType:
1466 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1467 lhsType.getAsString(), lex->getSourceRange());
1468 return QualType();
Steve Narofffec0b492007-07-30 03:29:09 +00001469 case Expr::MLV_DuplicateVectorComponents:
1470 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1471 lex->getSourceRange());
1472 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001473 }
Steve Naroff90045e82007-07-13 23:32:42 +00001474 AssignmentCheckResult result;
1475
1476 if (compoundType.isNull())
1477 result = CheckSingleAssignmentConstraints(lhsType, rex);
1478 else
1479 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001480
Reid Spencer5f016e22007-07-11 17:01:13 +00001481 // decode the result (notice that extensions still return a type).
1482 switch (result) {
1483 case Compatible:
1484 break;
1485 case Incompatible:
1486 Diag(loc, diag::err_typecheck_assign_incompatible,
1487 lhsType.getAsString(), rhsType.getAsString(),
1488 lex->getSourceRange(), rex->getSourceRange());
1489 hadError = true;
1490 break;
1491 case PointerFromInt:
Steve Naroff529a4ad2007-11-27 17:58:44 +00001492 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1493 lhsType.getAsString(), rhsType.getAsString(),
1494 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 break;
1496 case IntFromPointer:
1497 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1498 lhsType.getAsString(), rhsType.getAsString(),
1499 lex->getSourceRange(), rex->getSourceRange());
1500 break;
1501 case IncompatiblePointer:
1502 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1503 lhsType.getAsString(), rhsType.getAsString(),
1504 lex->getSourceRange(), rex->getSourceRange());
1505 break;
1506 case CompatiblePointerDiscardsQualifiers:
1507 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1508 lhsType.getAsString(), rhsType.getAsString(),
1509 lex->getSourceRange(), rex->getSourceRange());
1510 break;
1511 }
1512 // C99 6.5.16p3: The type of an assignment expression is the type of the
1513 // left operand unless the left operand has qualified type, in which case
1514 // it is the unqualified version of the type of the left operand.
1515 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1516 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001517 // C++ 5.17p1: the type of the assignment expression is that of its left
1518 // oprdu.
Reid Spencer5f016e22007-07-11 17:01:13 +00001519 return hadError ? QualType() : lhsType.getUnqualifiedType();
1520}
1521
1522inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00001523 Expr *&lex, Expr *&rex, SourceLocation loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001524 UsualUnaryConversions(rex);
1525 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001526}
1527
Steve Naroff49b45262007-07-13 16:58:59 +00001528/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1529/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00001530QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00001531 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 assert(!resType.isNull() && "no type for increment/decrement expression");
1533
Steve Naroff084f9ed2007-08-24 17:20:07 +00001534 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00001535 if (const PointerType *pt = resType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001536 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1537 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1538 resType.getAsString(), op->getSourceRange());
1539 return QualType();
1540 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00001541 } else if (!resType->isRealType()) {
1542 if (resType->isComplexType())
1543 // C99 does not support ++/-- on complex types.
1544 Diag(OpLoc, diag::ext_integer_increment_complex,
1545 resType.getAsString(), op->getSourceRange());
1546 else {
1547 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1548 resType.getAsString(), op->getSourceRange());
1549 return QualType();
1550 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 }
Steve Naroffdd10e022007-08-23 21:37:33 +00001552 // At this point, we know we have a real, complex or pointer type.
1553 // Now make sure the operand is a modifiable lvalue.
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1555 if (mlval != Expr::MLV_Valid) {
1556 // FIXME: emit a more precise diagnostic...
1557 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1558 op->getSourceRange());
1559 return QualType();
1560 }
1561 return resType;
1562}
1563
1564/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1565/// This routine allows us to typecheck complex/recursive expressions
1566/// where the declaration is needed for type checking. Here are some
1567/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1568static Decl *getPrimaryDeclaration(Expr *e) {
1569 switch (e->getStmtClass()) {
1570 case Stmt::DeclRefExprClass:
1571 return cast<DeclRefExpr>(e)->getDecl();
1572 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00001573 // Fields cannot be declared with a 'register' storage class.
1574 // &X->f is always ok, even if X is declared register.
1575 if (cast<MemberExpr>(e)->isArrow())
1576 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1578 case Stmt::ArraySubscriptExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00001579 // &X[4] and &4[X] is invalid if X is invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 case Stmt::UnaryOperatorClass:
1582 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1583 case Stmt::ParenExprClass:
1584 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00001585 case Stmt::ImplicitCastExprClass:
1586 // &X[4] when X is an array, has an implicit cast from array to pointer.
1587 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00001588 default:
1589 return 0;
1590 }
1591}
1592
1593/// CheckAddressOfOperand - The operand of & must be either a function
1594/// designator or an lvalue designating an object. If it is an lvalue, the
1595/// object cannot be declared with storage class register or be a bit field.
1596/// Note: The usual conversions are *not* applied to the operand of the &
1597/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1598QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1599 Decl *dcl = getPrimaryDeclaration(op);
1600 Expr::isLvalueResult lval = op->isLvalue();
1601
1602 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00001603 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1604 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00001605 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1606 op->getSourceRange());
1607 return QualType();
1608 }
1609 } else if (dcl) {
1610 // We have an lvalue with a decl. Make sure the decl is not declared
1611 // with the register storage-class specifier.
1612 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1613 if (vd->getStorageClass() == VarDecl::Register) {
1614 Diag(OpLoc, diag::err_typecheck_address_of_register,
1615 op->getSourceRange());
1616 return QualType();
1617 }
1618 } else
1619 assert(0 && "Unknown/unexpected decl type");
1620
1621 // FIXME: add check for bitfields!
1622 }
1623 // If the operand has type "type", the result has type "pointer to type".
1624 return Context.getPointerType(op->getType());
1625}
1626
1627QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001628 UsualUnaryConversions(op);
1629 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001630
Chris Lattnerbefee482007-07-31 16:53:04 +00001631 if (const PointerType *PT = qType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001632 QualType ptype = PT->getPointeeType();
1633 // C99 6.5.3.2p4. "if it points to an object,...".
1634 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1635 // GCC compat: special case 'void *' (treat as warning).
1636 if (ptype->isVoidType()) {
1637 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1638 qType.getAsString(), op->getSourceRange());
1639 } else {
1640 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1641 ptype.getAsString(), op->getSourceRange());
1642 return QualType();
1643 }
1644 }
1645 return ptype;
1646 }
1647 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1648 qType.getAsString(), op->getSourceRange());
1649 return QualType();
1650}
1651
1652static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1653 tok::TokenKind Kind) {
1654 BinaryOperator::Opcode Opc;
1655 switch (Kind) {
1656 default: assert(0 && "Unknown binop!");
1657 case tok::star: Opc = BinaryOperator::Mul; break;
1658 case tok::slash: Opc = BinaryOperator::Div; break;
1659 case tok::percent: Opc = BinaryOperator::Rem; break;
1660 case tok::plus: Opc = BinaryOperator::Add; break;
1661 case tok::minus: Opc = BinaryOperator::Sub; break;
1662 case tok::lessless: Opc = BinaryOperator::Shl; break;
1663 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1664 case tok::lessequal: Opc = BinaryOperator::LE; break;
1665 case tok::less: Opc = BinaryOperator::LT; break;
1666 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1667 case tok::greater: Opc = BinaryOperator::GT; break;
1668 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1669 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1670 case tok::amp: Opc = BinaryOperator::And; break;
1671 case tok::caret: Opc = BinaryOperator::Xor; break;
1672 case tok::pipe: Opc = BinaryOperator::Or; break;
1673 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1674 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1675 case tok::equal: Opc = BinaryOperator::Assign; break;
1676 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1677 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1678 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1679 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1680 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1681 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1682 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1683 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1684 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1685 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1686 case tok::comma: Opc = BinaryOperator::Comma; break;
1687 }
1688 return Opc;
1689}
1690
1691static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1692 tok::TokenKind Kind) {
1693 UnaryOperator::Opcode Opc;
1694 switch (Kind) {
1695 default: assert(0 && "Unknown unary op!");
1696 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1697 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1698 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1699 case tok::star: Opc = UnaryOperator::Deref; break;
1700 case tok::plus: Opc = UnaryOperator::Plus; break;
1701 case tok::minus: Opc = UnaryOperator::Minus; break;
1702 case tok::tilde: Opc = UnaryOperator::Not; break;
1703 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1704 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1705 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1706 case tok::kw___real: Opc = UnaryOperator::Real; break;
1707 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1708 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1709 }
1710 return Opc;
1711}
1712
1713// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001714Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00001715 ExprTy *LHS, ExprTy *RHS) {
1716 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1717 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1718
Steve Narofff69936d2007-09-16 03:34:24 +00001719 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1720 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00001721
1722 QualType ResultTy; // Result type of the binary operator.
1723 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1724
1725 switch (Opc) {
1726 default:
1727 assert(0 && "Unknown binary expr!");
1728 case BinaryOperator::Assign:
1729 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1730 break;
1731 case BinaryOperator::Mul:
1732 case BinaryOperator::Div:
1733 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1734 break;
1735 case BinaryOperator::Rem:
1736 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1737 break;
1738 case BinaryOperator::Add:
1739 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1740 break;
1741 case BinaryOperator::Sub:
1742 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1743 break;
1744 case BinaryOperator::Shl:
1745 case BinaryOperator::Shr:
1746 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1747 break;
1748 case BinaryOperator::LE:
1749 case BinaryOperator::LT:
1750 case BinaryOperator::GE:
1751 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001752 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001753 break;
1754 case BinaryOperator::EQ:
1755 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001756 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001757 break;
1758 case BinaryOperator::And:
1759 case BinaryOperator::Xor:
1760 case BinaryOperator::Or:
1761 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1762 break;
1763 case BinaryOperator::LAnd:
1764 case BinaryOperator::LOr:
1765 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1766 break;
1767 case BinaryOperator::MulAssign:
1768 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001769 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 if (!CompTy.isNull())
1771 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1772 break;
1773 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001774 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001775 if (!CompTy.isNull())
1776 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1777 break;
1778 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001779 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001780 if (!CompTy.isNull())
1781 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1782 break;
1783 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001784 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001785 if (!CompTy.isNull())
1786 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1787 break;
1788 case BinaryOperator::ShlAssign:
1789 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001790 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001791 if (!CompTy.isNull())
1792 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1793 break;
1794 case BinaryOperator::AndAssign:
1795 case BinaryOperator::XorAssign:
1796 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001797 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001798 if (!CompTy.isNull())
1799 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1800 break;
1801 case BinaryOperator::Comma:
1802 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1803 break;
1804 }
1805 if (ResultTy.isNull())
1806 return true;
1807 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001808 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001809 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001810 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001811}
1812
1813// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001814Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00001815 ExprTy *input) {
1816 Expr *Input = (Expr*)input;
1817 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1818 QualType resultType;
1819 switch (Opc) {
1820 default:
1821 assert(0 && "Unimplemented unary expr!");
1822 case UnaryOperator::PreInc:
1823 case UnaryOperator::PreDec:
1824 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1825 break;
1826 case UnaryOperator::AddrOf:
1827 resultType = CheckAddressOfOperand(Input, OpLoc);
1828 break;
1829 case UnaryOperator::Deref:
1830 resultType = CheckIndirectionOperand(Input, OpLoc);
1831 break;
1832 case UnaryOperator::Plus:
1833 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001834 UsualUnaryConversions(Input);
1835 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001836 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1837 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1838 resultType.getAsString());
1839 break;
1840 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001841 UsualUnaryConversions(Input);
1842 resultType = Input->getType();
Steve Naroff084f9ed2007-08-24 17:20:07 +00001843 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1844 if (!resultType->isIntegerType()) {
1845 if (resultType->isComplexType())
1846 // C99 does not support '~' for complex conjugation.
1847 Diag(OpLoc, diag::ext_integer_complement_complex,
1848 resultType.getAsString());
1849 else
1850 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1851 resultType.getAsString());
1852 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001853 break;
1854 case UnaryOperator::LNot: // logical negation
1855 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001856 DefaultFunctionArrayConversion(Input);
1857 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001858 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1859 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1860 resultType.getAsString());
1861 // LNot always has type int. C99 6.5.3.3p5.
1862 resultType = Context.IntTy;
1863 break;
1864 case UnaryOperator::SizeOf:
1865 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1866 break;
1867 case UnaryOperator::AlignOf:
1868 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1869 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00001870 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00001871 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00001872 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00001873 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001874 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00001875 resultType = Input->getType();
1876 break;
1877 }
1878 if (resultType.isNull())
1879 return true;
1880 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1881}
1882
Steve Naroff1b273c42007-09-16 14:56:35 +00001883/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1884Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001885 SourceLocation LabLoc,
1886 IdentifierInfo *LabelII) {
1887 // Look up the record for this label identifier.
1888 LabelStmt *&LabelDecl = LabelMap[LabelII];
1889
1890 // If we haven't seen this label yet, create a forward reference.
1891 if (LabelDecl == 0)
1892 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1893
1894 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00001895 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1896 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001897}
1898
Steve Naroff1b273c42007-09-16 14:56:35 +00001899Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001900 SourceLocation RPLoc) { // "({..})"
1901 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1902 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1903 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1904
1905 // FIXME: there are a variety of strange constraints to enforce here, for
1906 // example, it is not possible to goto into a stmt expression apparently.
1907 // More semantic analysis is needed.
1908
1909 // FIXME: the last statement in the compount stmt has its value used. We
1910 // should not warn about it being unused.
1911
1912 // If there are sub stmts in the compound stmt, take the type of the last one
1913 // as the type of the stmtexpr.
1914 QualType Ty = Context.VoidTy;
1915
1916 if (!Compound->body_empty())
1917 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1918 Ty = LastExpr->getType();
1919
1920 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1921}
Steve Naroffd34e9152007-08-01 22:05:33 +00001922
Steve Naroff1b273c42007-09-16 14:56:35 +00001923Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001924 SourceLocation TypeLoc,
1925 TypeTy *argty,
1926 OffsetOfComponent *CompPtr,
1927 unsigned NumComponents,
1928 SourceLocation RPLoc) {
1929 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1930 assert(!ArgTy.isNull() && "Missing type argument!");
1931
1932 // We must have at least one component that refers to the type, and the first
1933 // one is known to be a field designator. Verify that the ArgTy represents
1934 // a struct/union/class.
1935 if (!ArgTy->isRecordType())
1936 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1937
1938 // Otherwise, create a compound literal expression as the base, and
1939 // iteratively process the offsetof designators.
1940 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1941
Chris Lattner9e2b75c2007-08-31 21:49:13 +00001942 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1943 // GCC extension, diagnose them.
1944 if (NumComponents != 1)
1945 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1946 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1947
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001948 for (unsigned i = 0; i != NumComponents; ++i) {
1949 const OffsetOfComponent &OC = CompPtr[i];
1950 if (OC.isBrackets) {
1951 // Offset of an array sub-field. TODO: Should we allow vector elements?
1952 const ArrayType *AT = Res->getType()->getAsArrayType();
1953 if (!AT) {
1954 delete Res;
1955 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1956 Res->getType().getAsString());
1957 }
1958
Chris Lattner704fe352007-08-30 17:59:59 +00001959 // FIXME: C++: Verify that operator[] isn't overloaded.
1960
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001961 // C99 6.5.2.1p1
1962 Expr *Idx = static_cast<Expr*>(OC.U.E);
1963 if (!Idx->getType()->isIntegerType())
1964 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1965 Idx->getSourceRange());
1966
1967 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1968 continue;
1969 }
1970
1971 const RecordType *RC = Res->getType()->getAsRecordType();
1972 if (!RC) {
1973 delete Res;
1974 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1975 Res->getType().getAsString());
1976 }
1977
1978 // Get the decl corresponding to this.
1979 RecordDecl *RD = RC->getDecl();
1980 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1981 if (!MemberDecl)
1982 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1983 OC.U.IdentInfo->getName(),
1984 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00001985
1986 // FIXME: C++: Verify that MemberDecl isn't a static field.
1987 // FIXME: Verify that MemberDecl isn't a bitfield.
1988
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001989 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1990 }
1991
1992 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1993 BuiltinLoc);
1994}
1995
1996
Steve Naroff1b273c42007-09-16 14:56:35 +00001997Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00001998 TypeTy *arg1, TypeTy *arg2,
1999 SourceLocation RPLoc) {
2000 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2001 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2002
2003 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2004
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002005 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00002006}
2007
Steve Naroff1b273c42007-09-16 14:56:35 +00002008Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00002009 ExprTy *expr1, ExprTy *expr2,
2010 SourceLocation RPLoc) {
2011 Expr *CondExpr = static_cast<Expr*>(cond);
2012 Expr *LHSExpr = static_cast<Expr*>(expr1);
2013 Expr *RHSExpr = static_cast<Expr*>(expr2);
2014
2015 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2016
2017 // The conditional expression is required to be a constant expression.
2018 llvm::APSInt condEval(32);
2019 SourceLocation ExpLoc;
2020 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2021 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2022 CondExpr->getSourceRange());
2023
2024 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2025 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2026 RHSExpr->getType();
2027 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2028}
2029
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002030Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2031 ExprTy *expr, TypeTy *type,
2032 SourceLocation RPLoc)
2033{
2034 Expr *E = static_cast<Expr*>(expr);
2035 QualType T = QualType::getFromOpaquePtr(type);
2036
2037 InitBuiltinVaListType();
2038
2039 Sema::AssignmentCheckResult result;
2040
2041 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
2042 E->getType());
2043 if (result != Compatible)
2044 return Diag(E->getLocStart(),
2045 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2046 E->getType().getAsString(),
2047 E->getSourceRange());
2048
2049 // FIXME: Warn if a non-POD type is passed in.
2050
2051 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2052}
2053
Anders Carlsson55085182007-08-21 17:43:55 +00002054// TODO: Move this to SemaObjC.cpp
Steve Naroffbeaf2992007-11-03 11:27:19 +00002055Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation AtLoc,
2056 ExprTy *string) {
Anders Carlsson55085182007-08-21 17:43:55 +00002057 StringLiteral* S = static_cast<StringLiteral *>(string);
2058
2059 if (CheckBuiltinCFStringArgument(S))
2060 return true;
2061
Steve Naroff21988912007-10-15 23:35:17 +00002062 if (Context.getObjcConstantStringInterface().isNull()) {
2063 // Initialize the constant string interface lazily. This assumes
2064 // the NSConstantString interface is seen in this translation unit.
2065 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
2066 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
2067 SourceLocation(), TUScope);
Steve Naroffa1fe1172007-10-16 00:00:18 +00002068 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff806a4eb2007-10-18 23:53:51 +00002069 if (!strIFace)
2070 return Diag(S->getLocStart(), diag::err_undef_interface,
2071 NSIdent->getName());
Steve Naroffa1fe1172007-10-16 00:00:18 +00002072 Context.setObjcConstantStringInterface(strIFace);
Steve Naroff21988912007-10-15 23:35:17 +00002073 }
2074 QualType t = Context.getObjcConstantStringInterface();
Anders Carlsson55085182007-08-21 17:43:55 +00002075 t = Context.getPointerType(t);
Steve Naroffbeaf2992007-11-03 11:27:19 +00002076 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlsson55085182007-08-21 17:43:55 +00002077}
Anders Carlssonf9bcf012007-08-22 15:14:15 +00002078
2079Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattner674af952007-10-16 22:51:17 +00002080 SourceLocation EncodeLoc,
Anders Carlssonf9bcf012007-08-22 15:14:15 +00002081 SourceLocation LParenLoc,
2082 TypeTy *Ty,
2083 SourceLocation RParenLoc) {
2084 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
2085
2086 QualType t = Context.getPointerType(Context.CharTy);
2087 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
2088}
Steve Naroff708391a2007-09-17 21:01:15 +00002089
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002090Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
2091 SourceLocation AtLoc,
Fariborz Jahanian2a35fa92007-10-16 23:21:02 +00002092 SourceLocation SelLoc,
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002093 SourceLocation LParenLoc,
2094 SourceLocation RParenLoc) {
Steve Naroff8ee529b2007-10-31 18:42:27 +00002095 QualType t = Context.getObjcSelType();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002096 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
2097}
2098
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002099Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
2100 SourceLocation AtLoc,
2101 SourceLocation ProtoLoc,
2102 SourceLocation LParenLoc,
2103 SourceLocation RParenLoc) {
2104 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
2105 if (!PDecl) {
2106 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
2107 return true;
2108 }
2109
Fariborz Jahanian66c5dfc2007-12-07 00:18:54 +00002110 QualType t = Context.getObjcProtoType();
Fariborz Jahanian3e27aa12007-10-18 22:59:23 +00002111 if (t.isNull())
2112 return true;
Fariborz Jahanian66c5dfc2007-12-07 00:18:54 +00002113 t = Context.getPointerType(t);
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002114 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
2115}
Steve Naroff81bfde92007-10-16 23:12:48 +00002116
2117bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2118 ObjcMethodDecl *Method) {
2119 bool anyIncompatibleArgs = false;
2120
2121 for (unsigned i = 0; i < NumArgs; i++) {
2122 Expr *argExpr = Args[i];
2123 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2124
2125 QualType lhsType = Method->getParamDecl(i)->getType();
2126 QualType rhsType = argExpr->getType();
2127
2128 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2129 if (const ArrayType *ary = lhsType->getAsArrayType())
2130 lhsType = Context.getPointerType(ary->getElementType());
2131 else if (lhsType->isFunctionType())
2132 lhsType = Context.getPointerType(lhsType);
2133
2134 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2135 argExpr);
2136 if (Args[i] != argExpr) // The expression was converted.
2137 Args[i] = argExpr; // Make sure we store the converted expression.
2138 SourceLocation l = argExpr->getLocStart();
2139
2140 // decode the result (notice that AST's are still created for extensions).
2141 switch (result) {
2142 case Compatible:
2143 break;
2144 case PointerFromInt:
Steve Naroff529a4ad2007-11-27 17:58:44 +00002145 Diag(l, diag::ext_typecheck_sending_pointer_int,
2146 lhsType.getAsString(), rhsType.getAsString(),
2147 argExpr->getSourceRange());
Steve Naroff81bfde92007-10-16 23:12:48 +00002148 break;
2149 case IntFromPointer:
2150 Diag(l, diag::ext_typecheck_sending_pointer_int,
2151 lhsType.getAsString(), rhsType.getAsString(),
2152 argExpr->getSourceRange());
2153 break;
2154 case IncompatiblePointer:
2155 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2156 rhsType.getAsString(), lhsType.getAsString(),
2157 argExpr->getSourceRange());
2158 break;
2159 case CompatiblePointerDiscardsQualifiers:
2160 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2161 rhsType.getAsString(), lhsType.getAsString(),
2162 argExpr->getSourceRange());
2163 break;
2164 case Incompatible:
2165 Diag(l, diag::err_typecheck_sending_incompatible,
2166 rhsType.getAsString(), lhsType.getAsString(),
2167 argExpr->getSourceRange());
2168 anyIncompatibleArgs = true;
2169 }
2170 }
2171 return anyIncompatibleArgs;
2172}
2173
Steve Naroff68d331a2007-09-27 14:38:14 +00002174// ActOnClassMessage - used for both unary and keyword messages.
2175// ArgExprs is optional - if it is present, the number of expressions
2176// is obtained from Sel.getNumArgs().
2177Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002178 Scope *S,
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002179 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff49f109c2007-11-15 13:05:42 +00002180 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff708391a2007-09-17 21:01:15 +00002181{
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002182 assert(receiverName && "missing receiver class name");
Steve Naroff563477d2007-09-18 23:55:05 +00002183
Steve Naroff81bfde92007-10-16 23:12:48 +00002184 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002185 ObjcInterfaceDecl* ClassDecl = 0;
2186 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2187 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahaniancffff842007-11-12 20:20:37 +00002188 if (ClassDecl && CurMethodDecl->isInstance()) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002189 // Synthesize a cast to the super class. This hack allows us to loosely
2190 // represent super without creating a special expression node.
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002191 IdentifierInfo &II = Context.Idents.get("self");
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002192 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II, false);
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002193 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2194 superTy = Context.getPointerType(superTy);
2195 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2196 SourceLocation(), ReceiverExpr.Val);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002197 // We are really in an instance method, redirect.
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002198 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
Steve Naroff49f109c2007-11-15 13:05:42 +00002199 Args, NumArgs);
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002200 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002201 // We are sending a message to 'super' within a class method. Do nothing,
2202 // the receiver will pass through as 'super' (how convenient:-).
2203 } else
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002204 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002205
2206 // FIXME: can ClassDecl ever be null?
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002207 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff983df5b2007-10-16 20:39:36 +00002208 QualType returnType;
Steve Naroff945c0a82007-11-05 15:27:52 +00002209
2210 // Before we give up, check if the selector is an instance method.
2211 if (!Method)
2212 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff983df5b2007-10-16 20:39:36 +00002213 if (!Method) {
2214 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2215 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002216 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002217 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002218 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002219 if (Sel.getNumArgs()) {
2220 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2221 return true;
2222 }
Steve Naroff983df5b2007-10-16 20:39:36 +00002223 }
Steve Naroffdb611d52007-11-03 16:37:59 +00002224 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
Steve Naroff49f109c2007-11-15 13:05:42 +00002225 lbrac, rbrac, ArgExprs, NumArgs);
Steve Naroff708391a2007-09-17 21:01:15 +00002226}
2227
Steve Naroff68d331a2007-09-27 14:38:14 +00002228// ActOnInstanceMessage - used for both unary and keyword messages.
2229// ArgExprs is optional - if it is present, the number of expressions
2230// is obtained from Sel.getNumArgs().
2231Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroffbcfb06a2007-09-28 22:22:11 +00002232 ExprTy *receiver, Selector Sel,
Steve Naroff49f109c2007-11-15 13:05:42 +00002233 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff68d331a2007-09-27 14:38:14 +00002234{
Steve Naroff563477d2007-09-18 23:55:05 +00002235 assert(receiver && "missing receiver expression");
2236
Steve Naroff81bfde92007-10-16 23:12:48 +00002237 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroff563477d2007-09-18 23:55:05 +00002238 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002239 QualType receiverType = RExpr->getType();
Steve Naroff3b950172007-10-10 21:53:07 +00002240 QualType returnType;
Steve Naroffdb611d52007-11-03 16:37:59 +00002241 ObjcMethodDecl *Method;
Steve Naroff3b950172007-10-10 21:53:07 +00002242
Steve Naroff7c249152007-11-11 17:52:25 +00002243 if (receiverType == Context.getObjcIdType() ||
2244 receiverType == Context.getObjcClassType()) {
Steve Naroffdb611d52007-11-03 16:37:59 +00002245 Method = InstanceMethodPool[Sel].Method;
Steve Naroff817da7c2007-11-13 04:10:18 +00002246 // If we didn't find an public method, look for a private one.
2247 if (!Method && CurMethodDecl) {
2248 NamedDecl *impCxt = CurMethodDecl->getMethodContext();
2249 if (ObjcImplementationDecl *IMD =
2250 dyn_cast<ObjcImplementationDecl>(impCxt)) {
2251 if (receiverType == Context.getObjcIdType())
2252 Method = IMD->lookupInstanceMethod(Sel);
2253 else
2254 Method = IMD->lookupClassMethod(Sel);
2255 } else if (ObjcCategoryImplDecl *CID =
2256 dyn_cast<ObjcCategoryImplDecl>(impCxt)) {
2257 if (receiverType == Context.getObjcIdType())
2258 Method = CID->lookupInstanceMethod(Sel);
2259 else
2260 Method = CID->lookupClassMethod(Sel);
2261 }
2262 }
Steve Naroff983df5b2007-10-16 20:39:36 +00002263 if (!Method) {
2264 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2265 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002266 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002267 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002268 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002269 if (Sel.getNumArgs())
2270 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2271 return true;
Steve Naroff983df5b2007-10-16 20:39:36 +00002272 }
Steve Naroff3b950172007-10-10 21:53:07 +00002273 } else {
Chris Lattner22b73ba2007-10-10 23:42:28 +00002274 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2275 // revisited. how do we get the ClassDecl from the receiver expression?
Steve Naroff3b950172007-10-10 21:53:07 +00002276 while (receiverType->isPointerType()) {
Chris Lattner22b73ba2007-10-10 23:42:28 +00002277 PointerType *pointerType =
2278 static_cast<PointerType*>(receiverType.getTypePtr());
Steve Naroff3b950172007-10-10 21:53:07 +00002279 receiverType = pointerType->getPointeeType();
2280 }
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002281 ObjcInterfaceDecl* ClassDecl;
2282 if (ObjcQualifiedInterfaceType *QIT =
2283 dyn_cast<ObjcQualifiedInterfaceType>(receiverType)) {
2284 ObjcInterfaceType * OITypePtr = QIT->getInterfaceType();
2285
2286 ClassDecl = OITypePtr->getDecl();
2287 Method = ClassDecl->lookupInstanceMethod(Sel);
2288 if (!Method) {
2289 // search protocols
2290 for (unsigned i = 0; i < QIT->getNumProtocols(); i++) {
2291 ObjcProtocolDecl *PDecl = QIT->getProtocols(i);
2292 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
2293 break;
2294 }
2295 }
2296 }
2297 else {
2298 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2299 "bad receiver type");
2300 ClassDecl = static_cast<ObjcInterfaceType*>(
2301 receiverType.getTypePtr())->getDecl();
2302 // FIXME: consider using InstanceMethodPool, since it will be faster
2303 // than the following method (which can do *many* linear searches). The
2304 // idea is to add class info to InstanceMethodPool...
2305 Method = ClassDecl->lookupInstanceMethod(Sel);
2306 }
Steve Naroff983df5b2007-10-16 20:39:36 +00002307 if (!Method) {
Steve Naroffc43d8682007-11-11 00:10:47 +00002308 // If we have an implementation in scope, check "private" methods.
2309 if (ObjcImplementationDecl *ImpDecl =
2310 ObjcImplementations[ClassDecl->getIdentifier()])
2311 Method = ImpDecl->lookupInstanceMethod(Sel);
Steve Naroff9feba022007-12-07 20:41:14 +00002312 // If we still haven't found a method, look in the global pool.
2313 // I am not fond of this behavior, however we conform to what gcc does.
2314 if (!Method)
2315 Method = InstanceMethodPool[Sel].Method;
Steve Naroffc43d8682007-11-11 00:10:47 +00002316 }
2317 if (!Method) {
Steve Naroff983df5b2007-10-16 20:39:36 +00002318 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2319 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002320 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002321 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002322 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002323 if (Sel.getNumArgs())
2324 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2325 return true;
Steve Naroff983df5b2007-10-16 20:39:36 +00002326 }
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002327 }
Steve Naroffdb611d52007-11-03 16:37:59 +00002328 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
Steve Naroff49f109c2007-11-15 13:05:42 +00002329 ArgExprs, NumArgs);
Steve Naroff708391a2007-09-17 21:01:15 +00002330}