blob: 8f816e67ef42e9a5bfede4a0db529e228e76f601 [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"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
Steve Naroff6a8a9a42007-10-02 20:01:56 +000017#include "clang/AST/DeclObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/Expr.h"
Steve Naroff563477d2007-09-18 23:55:05 +000019#include "clang/Parse/DeclSpec.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/Diagnostic.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
26#include "llvm/ADT/SmallString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000027#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028using namespace clang;
29
Steve Narofff69936d2007-09-16 03:34:24 +000030/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +000031/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
32/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
33/// multiple tokens. However, the common case is that StringToks points to one
34/// string.
35///
36Action::ExprResult
Steve Narofff69936d2007-09-16 03:34:24 +000037Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +000038 assert(NumStringToks && "Must have at least one string!");
39
40 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
41 if (Literal.hadError)
42 return ExprResult(true);
43
44 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
45 for (unsigned i = 0; i != NumStringToks; ++i)
46 StringTokLocs.push_back(StringToks[i].getLocation());
47
48 // FIXME: handle wchar_t
Anders Carlssonee98ac52007-10-15 02:50:23 +000049 QualType t;
50
51 if (Literal.Pascal)
52 t = Context.getPointerType(Context.UnsignedCharTy);
53 else
54 t = Context.getPointerType(Context.CharTy);
55
56 if (Literal.Pascal && Literal.GetStringLength() > 256)
57 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
58 SourceRange(StringToks[0].getLocation(),
59 StringToks[NumStringToks-1].getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +000060
61 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
62 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlssonee98ac52007-10-15 02:50:23 +000063 Literal.AnyWide, t,
64 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +000065 StringToks[NumStringToks-1].getLocation());
66}
67
68
Steve Naroff08d92e42007-09-15 18:49:24 +000069/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +000070/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
71/// identifier is used in an function call context.
Steve Naroff08d92e42007-09-15 18:49:24 +000072Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +000073 IdentifierInfo &II,
74 bool HasTrailingLParen) {
75 // Could be enum-constant or decl.
Steve Naroff8c9f13e2007-09-16 16:16:00 +000076 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Reid Spencer5f016e22007-07-11 17:01:13 +000077 if (D == 0) {
78 // Otherwise, this could be an implicitly declared function reference (legal
79 // in C90, extension in C99).
80 if (HasTrailingLParen &&
81 // Not in C++.
82 !getLangOptions().CPlusPlus)
83 D = ImplicitlyDefineFunction(Loc, II, S);
84 else {
Steve Naroff7779db42007-11-12 14:29:37 +000085 if (CurMethodDecl) {
86 ObjcInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
87 ObjcInterfaceDecl *clsDeclared;
88 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared))
89 return new ObjCIvarRefExpr(IV, IV->getType(), Loc);
90 }
Reid Spencer5f016e22007-07-11 17:01:13 +000091 // If this name wasn't predeclared and if this is not a function call,
92 // diagnose the problem.
93 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
94 }
95 }
Steve Naroffe1223f72007-08-28 03:03:08 +000096 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroff53a32342007-08-28 18:45:29 +000097 // Only create DeclRefExpr's for valid Decl's.
Steve Naroff5912a352007-08-28 20:14:24 +000098 if (VD->isInvalidDecl())
Steve Naroffe1223f72007-08-28 03:03:08 +000099 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000100 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroffe1223f72007-08-28 03:03:08 +0000101 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 if (isa<TypedefDecl>(D))
103 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
104
105 assert(0 && "Invalid decl");
Chris Lattnereddbe032007-07-21 04:57:45 +0000106 abort();
Reid Spencer5f016e22007-07-11 17:01:13 +0000107}
108
Steve Narofff69936d2007-09-16 03:34:24 +0000109Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000110 tok::TokenKind Kind) {
111 PreDefinedExpr::IdentType IT;
112
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 switch (Kind) {
114 default:
115 assert(0 && "Unknown simple primary expr!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000116 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
Anders Carlsson22742662007-07-21 05:21:51 +0000117 IT = PreDefinedExpr::Func;
118 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000120 IT = PreDefinedExpr::Function;
121 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000123 IT = PreDefinedExpr::PrettyFunction;
124 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 }
Anders Carlsson22742662007-07-21 05:21:51 +0000126
127 // Pre-defined identifiers are always of type char *.
128 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000129}
130
Steve Narofff69936d2007-09-16 03:34:24 +0000131Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 llvm::SmallString<16> CharBuffer;
133 CharBuffer.resize(Tok.getLength());
134 const char *ThisTokBegin = &CharBuffer[0];
135 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
136
137 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
138 Tok.getLocation(), PP);
139 if (Literal.hadError())
140 return ExprResult(true);
141 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
142 Tok.getLocation());
143}
144
Steve Narofff69936d2007-09-16 03:34:24 +0000145Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000146 // fast path for a single digit (which is quite common). A single digit
147 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
148 if (Tok.getLength() == 1) {
149 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
150
Chris Lattner701e5eb2007-09-04 02:45:27 +0000151 unsigned IntSize = static_cast<unsigned>(
152 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
154 Context.IntTy,
155 Tok.getLocation()));
156 }
157 llvm::SmallString<512> IntegerBuffer;
158 IntegerBuffer.resize(Tok.getLength());
159 const char *ThisTokBegin = &IntegerBuffer[0];
160
161 // Get the spelling of the token, which eliminates trigraphs, etc.
162 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
163 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
164 Tok.getLocation(), PP);
165 if (Literal.hadError)
166 return ExprResult(true);
167
Chris Lattner5d661452007-08-26 03:42:43 +0000168 Expr *Res;
169
170 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000171 QualType Ty;
172 const llvm::fltSemantics *Format;
173 uint64_t Size; unsigned Align;
174
175 if (Literal.isFloat) {
176 Ty = Context.FloatTy;
177 Context.Target.getFloatInfo(Size, Align, Format, Tok.getLocation());
178 } else if (Literal.isLong) {
179 Ty = Context.LongDoubleTy;
180 Context.Target.getLongDoubleInfo(Size, Align, Format, Tok.getLocation());
181 } else {
182 Ty = Context.DoubleTy;
183 Context.Target.getDoubleInfo(Size, Align, Format, Tok.getLocation());
184 }
185
186 Res = new FloatingLiteral(Literal.GetFloatValue(*Format), Ty,
187 Tok.getLocation());
Chris Lattner5d661452007-08-26 03:42:43 +0000188 } else if (!Literal.isIntegerLiteral()) {
189 return ExprResult(true);
190 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 QualType t;
192
Neil Boothb9449512007-08-29 22:00:19 +0000193 // long long is a C99 feature.
194 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000195 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000196 Diag(Tok.getLocation(), diag::ext_longlong);
197
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 // Get the value in the widest-possible width.
199 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
200
201 if (Literal.GetIntegerValue(ResultVal)) {
202 // If this value didn't fit into uintmax_t, warn and force to ull.
203 Diag(Tok.getLocation(), diag::warn_integer_too_large);
204 t = Context.UnsignedLongLongTy;
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000205 assert(Context.getTypeSize(t, Tok.getLocation()) ==
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 ResultVal.getBitWidth() && "long long is not intmax_t?");
207 } else {
208 // If this value fits into a ULL, try to figure out what else it fits into
209 // according to the rules of C99 6.4.4.1p5.
210
211 // Octal, Hexadecimal, and integers with a U suffix are allowed to
212 // be an unsigned int.
213 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
214
215 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner97c51562007-08-23 21:58:08 +0000216 if (!Literal.isLong && !Literal.isLongLong) {
217 // Are int/unsigned possibilities?
Chris Lattner701e5eb2007-09-04 02:45:27 +0000218 unsigned IntSize = static_cast<unsigned>(
219 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000220 // Does it fit in a unsigned int?
221 if (ResultVal.isIntN(IntSize)) {
222 // Does it fit in a signed int?
223 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
224 t = Context.IntTy;
225 else if (AllowUnsigned)
226 t = Context.UnsignedIntTy;
227 }
228
229 if (!t.isNull())
230 ResultVal.trunc(IntSize);
231 }
232
233 // Are long/unsigned long possibilities?
234 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner701e5eb2007-09-04 02:45:27 +0000235 unsigned LongSize = static_cast<unsigned>(
236 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000237
238 // Does it fit in a unsigned long?
239 if (ResultVal.isIntN(LongSize)) {
240 // Does it fit in a signed long?
241 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
242 t = Context.LongTy;
243 else if (AllowUnsigned)
244 t = Context.UnsignedLongTy;
245 }
246 if (!t.isNull())
247 ResultVal.trunc(LongSize);
248 }
249
250 // Finally, check long long if needed.
251 if (t.isNull()) {
Chris Lattner701e5eb2007-09-04 02:45:27 +0000252 unsigned LongLongSize = static_cast<unsigned>(
253 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000254
255 // Does it fit in a unsigned long long?
256 if (ResultVal.isIntN(LongLongSize)) {
257 // Does it fit in a signed long long?
258 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
259 t = Context.LongLongTy;
260 else if (AllowUnsigned)
261 t = Context.UnsignedLongLongTy;
262 }
263 }
264
265 // If we still couldn't decide a type, we probably have something that
266 // does not fit in a signed long long, but has no U suffix.
267 if (t.isNull()) {
268 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
269 t = Context.UnsignedLongLongTy;
270 }
271 }
272
Chris Lattner5d661452007-08-26 03:42:43 +0000273 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 }
Chris Lattner5d661452007-08-26 03:42:43 +0000275
276 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
277 if (Literal.isImaginary)
278 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
279
280 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000281}
282
Steve Narofff69936d2007-09-16 03:34:24 +0000283Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000284 ExprTy *Val) {
285 Expr *e = (Expr *)Val;
Steve Narofff69936d2007-09-16 03:34:24 +0000286 assert((e != 0) && "ActOnParenExpr() missing expr");
Reid Spencer5f016e22007-07-11 17:01:13 +0000287 return new ParenExpr(L, R, e);
288}
289
290/// The UsualUnaryConversions() function is *not* called by this routine.
291/// See C99 6.3.2.1p[2-4] for more details.
292QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
293 SourceLocation OpLoc, bool isSizeof) {
294 // C99 6.5.3.4p1:
295 if (isa<FunctionType>(exprType) && isSizeof)
296 // alignof(function) is allowed.
297 Diag(OpLoc, diag::ext_sizeof_function_type);
298 else if (exprType->isVoidType())
299 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
300 else if (exprType->isIncompleteType()) {
301 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
302 diag::err_alignof_incomplete_type,
303 exprType.getAsString());
304 return QualType(); // error
305 }
306 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
307 return Context.getSizeType();
308}
309
310Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000311ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 SourceLocation LPLoc, TypeTy *Ty,
313 SourceLocation RPLoc) {
314 // If error parsing type, ignore.
315 if (Ty == 0) return true;
316
317 // Verify that this is a valid expression.
318 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
319
320 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
321
322 if (resultType.isNull())
323 return true;
324 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
325}
326
Chris Lattner5d794252007-08-24 21:41:10 +0000327QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000328 DefaultFunctionArrayConversion(V);
329
Chris Lattnercc26ed72007-08-26 05:39:26 +0000330 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000331 if (const ComplexType *CT = V->getType()->getAsComplexType())
332 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000333
334 // Otherwise they pass through real integer and floating point types here.
335 if (V->getType()->isArithmeticType())
336 return V->getType();
337
338 // Reject anything else.
339 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
340 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000341}
342
343
Reid Spencer5f016e22007-07-11 17:01:13 +0000344
Steve Narofff69936d2007-09-16 03:34:24 +0000345Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 tok::TokenKind Kind,
347 ExprTy *Input) {
348 UnaryOperator::Opcode Opc;
349 switch (Kind) {
350 default: assert(0 && "Unknown unary op!");
351 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
352 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
353 }
354 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
355 if (result.isNull())
356 return true;
357 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
358}
359
360Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000361ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000363 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000364
365 // Perform default conversions.
366 DefaultFunctionArrayConversion(LHSExp);
367 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000368
Chris Lattner12d9ff62007-07-16 00:14:47 +0000369 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000370
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000372 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 // in the subscript position. As a result, we need to derive the array base
374 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000375 Expr *BaseExpr, *IndexExpr;
376 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000377 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000378 BaseExpr = LHSExp;
379 IndexExpr = RHSExp;
380 // FIXME: need to deal with const...
381 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000382 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000383 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000384 BaseExpr = RHSExp;
385 IndexExpr = LHSExp;
386 // FIXME: need to deal with const...
387 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000388 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
389 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000390 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000391
392 // Component access limited to variables (reject vec4.rg[1]).
393 if (!isa<DeclRefExpr>(BaseExpr))
394 return Diag(LLoc, diag::err_ocuvector_component_access,
395 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000396 // FIXME: need to deal with const...
397 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000399 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
400 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 }
402 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000403 if (!IndexExpr->getType()->isIntegerType())
404 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
405 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000406
Chris Lattner12d9ff62007-07-16 00:14:47 +0000407 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
408 // the following check catches trying to index a pointer to a function (e.g.
409 // void (*)(int)). Functions are not objects in C99.
410 if (!ResultType->isObjectType())
411 return Diag(BaseExpr->getLocStart(),
412 diag::err_typecheck_subscript_not_object,
413 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
414
415 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000416}
417
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000418QualType Sema::
419CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
420 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnerc8629632007-07-31 19:29:30 +0000421 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000422
423 // The vector accessor can't exceed the number of elements.
424 const char *compStr = CompName.getName();
425 if (strlen(compStr) > vecType->getNumElements()) {
426 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
427 baseType.getAsString(), SourceRange(CompLoc));
428 return QualType();
429 }
430 // The component names must come from the same set.
Chris Lattner88dca042007-08-02 22:33:49 +0000431 if (vecType->getPointAccessorIdx(*compStr) != -1) {
432 do
433 compStr++;
434 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
435 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
436 do
437 compStr++;
438 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
439 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
440 do
441 compStr++;
442 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
443 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000444
445 if (*compStr) {
446 // We didn't get to the end of the string. This means the component names
447 // didn't come from the same set *or* we encountered an illegal name.
448 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
449 std::string(compStr,compStr+1), SourceRange(CompLoc));
450 return QualType();
451 }
452 // Each component accessor can't exceed the vector type.
453 compStr = CompName.getName();
454 while (*compStr) {
455 if (vecType->isAccessorWithinNumElements(*compStr))
456 compStr++;
457 else
458 break;
459 }
460 if (*compStr) {
461 // We didn't get to the end of the string. This means a component accessor
462 // exceeds the number of elements in the vector.
463 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
464 baseType.getAsString(), SourceRange(CompLoc));
465 return QualType();
466 }
467 // The component accessor looks fine - now we need to compute the actual type.
468 // The vector type is implied by the component accessor. For example,
469 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
470 unsigned CompSize = strlen(CompName.getName());
471 if (CompSize == 1)
472 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000473
474 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
475 // Now look up the TypeDefDecl from the vector type. Without this,
476 // diagostics look bad. We want OCU vector types to appear built-in.
477 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
478 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
479 return Context.getTypedefType(OCUVectorDecls[i]);
480 }
481 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000482}
483
Reid Spencer5f016e22007-07-11 17:01:13 +0000484Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000485ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000486 tok::TokenKind OpKind, SourceLocation MemberLoc,
487 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000488 Expr *BaseExpr = static_cast<Expr *>(Base);
489 assert(BaseExpr && "no record expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000490
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000491 QualType BaseType = BaseExpr->getType();
492 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000493
Reid Spencer5f016e22007-07-11 17:01:13 +0000494 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000495 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000496 BaseType = PT->getPointeeType();
497 else
498 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
499 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000501 // The base type is either a record or an OCUVectorType.
Chris Lattnerc8629632007-07-31 19:29:30 +0000502 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000503 RecordDecl *RDecl = RTy->getDecl();
504 if (RTy->isIncompleteType())
505 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
506 BaseExpr->getSourceRange());
507 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000508 FieldDecl *MemberDecl = RDecl->getMember(&Member);
509 if (!MemberDecl)
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000510 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
511 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000512 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
513 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff608e0ee2007-08-03 22:40:33 +0000514 // Component access limited to variables (reject vec4.rg.g).
515 if (!isa<DeclRefExpr>(BaseExpr))
516 return Diag(OpLoc, diag::err_ocuvector_component_access,
517 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000518 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
519 if (ret.isNull())
520 return true;
Chris Lattner6481a572007-08-03 17:31:20 +0000521 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000522 } else if (BaseType->isObjcInterfaceType()) {
523 ObjcInterfaceDecl *IFace;
524 if (isa<ObjcInterfaceType>(BaseType.getCanonicalType()))
525 IFace = dyn_cast<ObjcInterfaceType>(BaseType)->getDecl();
526 else
527 IFace = dyn_cast<ObjcQualifiedInterfaceType>(BaseType)
528 ->getInterfaceType()->getDecl();
529 ObjcInterfaceDecl *clsDeclared;
530 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
531 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
532 OpKind==tok::arrow);
533 }
534 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
535 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000536}
537
Steve Narofff69936d2007-09-16 03:34:24 +0000538/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +0000539/// This provides the location of the left/right parens and a list of comma
540/// locations.
541Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000542ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner74c469f2007-07-21 03:03:59 +0000543 ExprTy **args, unsigned NumArgsInCall,
Reid Spencer5f016e22007-07-11 17:01:13 +0000544 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000545 Expr *Fn = static_cast<Expr *>(fn);
546 Expr **Args = reinterpret_cast<Expr**>(args);
547 assert(Fn && "no function call expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000548
Chris Lattner74c469f2007-07-21 03:03:59 +0000549 UsualUnaryConversions(Fn);
550 QualType funcType = Fn->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000551
552 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
553 // type pointer to function".
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000554 const PointerType *PT = funcType->getAsPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000555 if (PT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000556 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
557 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000558
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000559 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000560 if (funcT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000561 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
562 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000563
564 // If a prototype isn't declared, the parser implicitly defines a func decl
565 QualType resultType = funcT->getResultType();
566
567 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
568 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
569 // assignment, to the types of the corresponding parameter, ...
570
571 unsigned NumArgsInProto = proto->getNumArgs();
572 unsigned NumArgsToCheck = NumArgsInCall;
573
574 if (NumArgsInCall < NumArgsInProto)
575 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
Chris Lattner74c469f2007-07-21 03:03:59 +0000576 Fn->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 else if (NumArgsInCall > NumArgsInProto) {
578 if (!proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +0000579 Diag(Args[NumArgsInProto]->getLocStart(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000580 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +0000581 SourceRange(Args[NumArgsInProto]->getLocStart(),
582 Args[NumArgsInCall-1]->getLocEnd()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000583 }
584 NumArgsToCheck = NumArgsInProto;
585 }
586 // Continue to check argument types (even if we have too few/many args).
587 for (unsigned i = 0; i < NumArgsToCheck; i++) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000588 Expr *argExpr = Args[i];
Steve Narofff69936d2007-09-16 03:34:24 +0000589 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000590
591 QualType lhsType = proto->getArgType(i);
592 QualType rhsType = argExpr->getType();
Steve Naroff700204c2007-07-24 21:46:40 +0000593
Steve Naroff82c7e6d2007-07-25 20:45:33 +0000594 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnerc8629632007-07-31 19:29:30 +0000595 if (const ArrayType *ary = lhsType->getAsArrayType())
Steve Naroff700204c2007-07-24 21:46:40 +0000596 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff82c7e6d2007-07-25 20:45:33 +0000597 else if (lhsType->isFunctionType())
Steve Naroff700204c2007-07-24 21:46:40 +0000598 lhsType = Context.getPointerType(lhsType);
599
Steve Naroff90045e82007-07-13 23:32:42 +0000600 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
601 argExpr);
Steve Narofff1120de2007-08-24 22:33:52 +0000602 if (Args[i] != argExpr) // The expression was converted.
603 Args[i] = argExpr; // Make sure we store the converted expression.
Reid Spencer5f016e22007-07-11 17:01:13 +0000604 SourceLocation l = argExpr->getLocStart();
605
606 // decode the result (notice that AST's are still created for extensions).
607 switch (result) {
608 case Compatible:
609 break;
610 case PointerFromInt:
611 // check for null pointer constant (C99 6.3.2.3p3)
Chris Lattner590b6642007-07-15 23:26:56 +0000612 if (!argExpr->isNullPointerConstant(Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000613 Diag(l, diag::ext_typecheck_passing_pointer_int,
614 lhsType.getAsString(), rhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000615 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000616 }
617 break;
618 case IntFromPointer:
619 Diag(l, diag::ext_typecheck_passing_pointer_int,
620 lhsType.getAsString(), rhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000621 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000622 break;
623 case IncompatiblePointer:
624 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
625 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000626 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000627 break;
628 case CompatiblePointerDiscardsQualifiers:
629 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
630 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000631 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000632 break;
633 case Incompatible:
634 return Diag(l, diag::err_typecheck_passing_incompatible,
635 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000636 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000637 }
638 }
Steve Naroffb291ab62007-08-28 23:30:39 +0000639 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
640 // Promote the arguments (C99 6.5.2.2p7).
641 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
642 Expr *argExpr = Args[i];
Steve Narofff69936d2007-09-16 03:34:24 +0000643 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffb291ab62007-08-28 23:30:39 +0000644
645 DefaultArgumentPromotion(argExpr);
646 if (Args[i] != argExpr) // The expression was converted.
647 Args[i] = argExpr; // Make sure we store the converted expression.
648 }
649 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
650 // Even if the types checked, bail if the number of arguments don't match.
Reid Spencer5f016e22007-07-11 17:01:13 +0000651 return true;
Steve Naroffb291ab62007-08-28 23:30:39 +0000652 }
653 } else if (isa<FunctionTypeNoProto>(funcT)) {
654 // Promote the arguments (C99 6.5.2.2p6).
655 for (unsigned i = 0; i < NumArgsInCall; i++) {
656 Expr *argExpr = Args[i];
Steve Narofff69936d2007-09-16 03:34:24 +0000657 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffb291ab62007-08-28 23:30:39 +0000658
659 DefaultArgumentPromotion(argExpr);
660 if (Args[i] != argExpr) // The expression was converted.
661 Args[i] = argExpr; // Make sure we store the converted expression.
662 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000663 }
Chris Lattner59907c42007-08-10 20:18:51 +0000664 // Do special checking on direct calls to functions.
665 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
666 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
667 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000668 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
669 NumArgsInCall))
Anders Carlsson71993dd2007-08-17 05:31:46 +0000670 return true;
Chris Lattner59907c42007-08-10 20:18:51 +0000671
Chris Lattner74c469f2007-07-21 03:03:59 +0000672 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000673}
674
675Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000676ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +0000677 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +0000678 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +0000679 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +0000680 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +0000681 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +0000682 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000683
684 // FIXME: add semantic analysis (C99 6.5.2.5).
Steve Naroffaff1edd2007-07-19 21:32:11 +0000685 return new CompoundLiteralExpr(literalType, literalExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000686}
687
688Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000689ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000690 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +0000691 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000692
Steve Naroff08d92e42007-09-15 18:49:24 +0000693 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +0000694 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000695
Steve Naroff38374b02007-09-02 20:30:18 +0000696 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
697 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
698 return e;
Steve Naroff4aa88f82007-07-19 01:06:55 +0000699}
700
701Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000702ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +0000703 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +0000704 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +0000705
706 Expr *castExpr = static_cast<Expr*>(Op);
707 QualType castType = QualType::getFromOpaquePtr(Ty);
708
Steve Naroff711602b2007-08-31 00:32:44 +0000709 UsualUnaryConversions(castExpr);
710
Chris Lattner75af4802007-07-18 16:00:06 +0000711 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
712 // type needs to be scalar.
Chris Lattner3da2db42007-10-29 04:26:44 +0000713 if (!castType->isVoidType()) { // Cast to void allows any expr type.
714 if (!castType->isScalarType())
715 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
716 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
717 if (!castExpr->getType()->isScalarType()) {
718 return Diag(castExpr->getLocStart(),
719 diag::err_typecheck_expect_scalar_operand,
720 castExpr->getType().getAsString(),castExpr->getSourceRange());
721 }
Steve Naroff16beff82007-07-16 23:25:18 +0000722 }
723 return new CastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000724}
725
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000726// promoteExprToType - a helper function to ensure we create exactly one
727// ImplicitCastExpr.
728static void promoteExprToType(Expr *&expr, QualType type) {
729 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
730 impCast->setType(type);
731 else
732 expr = new ImplicitCastExpr(type, expr);
733 return;
734}
735
Reid Spencer5f016e22007-07-11 17:01:13 +0000736inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +0000737 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000738 UsualUnaryConversions(cond);
739 UsualUnaryConversions(lex);
740 UsualUnaryConversions(rex);
741 QualType condT = cond->getType();
742 QualType lexT = lex->getType();
743 QualType rexT = rex->getType();
744
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +0000746 if (!condT->isScalarType()) { // C99 6.5.15p2
747 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
748 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +0000749 return QualType();
750 }
751 // now check the two expressions.
Steve Naroffa4332e22007-07-17 00:58:39 +0000752 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
753 UsualArithmeticConversions(lex, rex);
754 return lex->getType();
755 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000756 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
757 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
758
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000759 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000760 return lexT;
761
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000763 lexT.getAsString(), rexT.getAsString(),
764 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 return QualType();
766 }
767 }
Chris Lattner590b6642007-07-15 23:26:56 +0000768 // C99 6.5.15p3
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000769 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
770 promoteExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff49b45262007-07-13 16:58:59 +0000771 return lexT;
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000772 }
773 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
774 promoteExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff49b45262007-07-13 16:58:59 +0000775 return rexT;
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000776 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000777 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
778 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
779 // get the "pointed to" types
780 QualType lhptee = LHSPT->getPointeeType();
781 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000782
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000783 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
784 if (lhptee->isVoidType() &&
785 (rhptee->isObjectType() || rhptee->isIncompleteType()))
786 return lexT;
787 if (rhptee->isVoidType() &&
788 (lhptee->isObjectType() || lhptee->isIncompleteType()))
789 return rexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000790
Steve Naroffec0550f2007-10-15 20:41:53 +0000791 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
792 rhptee.getUnqualifiedType())) {
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000793 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
794 lexT.getAsString(), rexT.getAsString(),
795 lex->getSourceRange(), rex->getSourceRange());
796 return lexT; // FIXME: this is an _ext - is this return o.k?
797 }
798 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000799 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
800 // differently qualified versions of compatible types, the result type is
801 // a pointer to an appropriately qualified version of the *composite*
802 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000803 return lexT; // FIXME: Need to return the composite type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000804 }
805 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000806
Steve Naroff49b45262007-07-13 16:58:59 +0000807 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
808 return lexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000809
810 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000811 lexT.getAsString(), rexT.getAsString(),
812 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000813 return QualType();
814}
815
Steve Narofff69936d2007-09-16 03:34:24 +0000816/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +0000817/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +0000818Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000819 SourceLocation ColonLoc,
820 ExprTy *Cond, ExprTy *LHS,
821 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +0000822 Expr *CondExpr = (Expr *) Cond;
823 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
824 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
825 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000826 if (result.isNull())
827 return true;
Chris Lattner26824902007-07-16 21:39:03 +0000828 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000829}
830
Steve Naroffb291ab62007-08-28 23:30:39 +0000831/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
832/// do not have a prototype. Integer promotions are performed on each
833/// argument, and arguments that have type float are promoted to double.
834void Sema::DefaultArgumentPromotion(Expr *&expr) {
835 QualType t = expr->getType();
836 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
837
838 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
839 promoteExprToType(expr, Context.IntTy);
840 if (t == Context.FloatTy)
841 promoteExprToType(expr, Context.DoubleTy);
842}
843
Steve Narofffa2eaab2007-07-15 02:02:06 +0000844/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000845void Sema::DefaultFunctionArrayConversion(Expr *&e) {
Steve Narofffa2eaab2007-07-15 02:02:06 +0000846 QualType t = e->getType();
Steve Naroff90045e82007-07-13 23:32:42 +0000847 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
Bill Wendling08ad47c2007-07-17 03:52:31 +0000848
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000849 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000850 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
851 t = e->getType();
852 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000853 if (t->isFunctionType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000854 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnerc8629632007-07-31 19:29:30 +0000855 else if (const ArrayType *ary = t->getAsArrayType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000856 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000857}
858
859/// UsualUnaryConversion - Performs various conversions that are common to most
860/// operators (C99 6.3). The conversions of array and function types are
861/// sometimes surpressed. For example, the array->pointer conversion doesn't
862/// apply if the array is an argument to the sizeof or address (&) operators.
863/// In these instances, this routine should *not* be called.
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000864void Sema::UsualUnaryConversions(Expr *&expr) {
Steve Naroff49b45262007-07-13 16:58:59 +0000865 QualType t = expr->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000866 assert(!t.isNull() && "UsualUnaryConversions - missing type");
867
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000868 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000869 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
870 t = expr->getType();
871 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000872 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000873 promoteExprToType(expr, Context.IntTy);
874 else
875 DefaultFunctionArrayConversion(expr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000876}
877
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000878/// UsualArithmeticConversions - Performs various conversions that are common to
Reid Spencer5f016e22007-07-11 17:01:13 +0000879/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
880/// routine returns the first non-arithmetic type found. The client is
881/// responsible for emitting appropriate error diagnostics.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000882QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
883 bool isCompAssign) {
Steve Naroff8702a0f2007-08-25 19:54:59 +0000884 if (!isCompAssign) {
885 UsualUnaryConversions(lhsExpr);
886 UsualUnaryConversions(rhsExpr);
887 }
Steve Naroff3187e202007-10-18 18:55:53 +0000888 // For conversion purposes, we ignore any qualifiers.
889 // For example, "const float" and "float" are equivalent.
Steve Narofff68a63f2007-11-10 19:45:54 +0000890 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
891 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000892
893 // If both types are identical, no conversion is needed.
Steve Naroff3187e202007-10-18 18:55:53 +0000894 if (lhs == rhs)
895 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000896
897 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
898 // The caller can deal with this (e.g. pointer + int).
Steve Naroffa4332e22007-07-17 00:58:39 +0000899 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000900 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000901
902 // At this point, we have two different arithmetic types.
903
904 // Handle complex types first (C99 6.3.1.8p1).
905 if (lhs->isComplexType() || rhs->isComplexType()) {
906 // if we have an integer operand, the result is the complex type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000907 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000908 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
909 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000910 }
911 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000912 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
913 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000914 }
Steve Narofff1448a02007-08-27 01:27:54 +0000915 // This handles complex/complex, complex/float, or float/complex.
916 // When both operands are complex, the shorter operand is converted to the
917 // type of the longer, and that is the type of the result. This corresponds
918 // to what is done when combining two real floating-point operands.
919 // The fun begins when size promotion occur across type domains.
920 // From H&S 6.3.4: When one operand is complex and the other is a real
921 // floating-point type, the less precise type is converted, within it's
922 // real or complex domain, to the precision of the other type. For example,
923 // when combining a "long double" with a "double _Complex", the
924 // "double _Complex" is promoted to "long double _Complex".
Steve Narofffb0d4962007-08-27 15:30:22 +0000925 int result = Context.compareFloatingType(lhs, rhs);
926
927 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff55fe4552007-08-27 21:32:55 +0000928 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
929 if (!isCompAssign)
930 promoteExprToType(rhsExpr, rhs);
931 } else if (result < 0) { // The right side is bigger, convert lhs.
932 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
933 if (!isCompAssign)
934 promoteExprToType(lhsExpr, lhs);
935 }
936 // At this point, lhs and rhs have the same rank/size. Now, make sure the
937 // domains match. This is a requirement for our implementation, C99
938 // does not require this promotion.
939 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
940 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff29960362007-08-27 21:43:43 +0000941 if (!isCompAssign)
942 promoteExprToType(lhsExpr, rhs);
943 return rhs;
Steve Naroff55fe4552007-08-27 21:32:55 +0000944 } else { // handle "_Complex double, double".
Steve Naroff29960362007-08-27 21:43:43 +0000945 if (!isCompAssign)
946 promoteExprToType(rhsExpr, lhs);
947 return lhs;
Steve Naroff55fe4552007-08-27 21:32:55 +0000948 }
Steve Naroffa4332e22007-07-17 00:58:39 +0000949 }
Steve Naroff29960362007-08-27 21:43:43 +0000950 return lhs; // The domain/size match exactly.
Reid Spencer5f016e22007-07-11 17:01:13 +0000951 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000952 // Now handle "real" floating types (i.e. float, double, long double).
953 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
954 // if we have an integer operand, the result is the real floating type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000955 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000956 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
957 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000958 }
959 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000960 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
961 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000962 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000963 // We have two real floating types, float/complex combos were handled above.
964 // Convert the smaller operand to the bigger result.
Steve Narofffb0d4962007-08-27 15:30:22 +0000965 int result = Context.compareFloatingType(lhs, rhs);
966
967 if (result > 0) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000968 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
969 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000970 }
Steve Narofffb0d4962007-08-27 15:30:22 +0000971 if (result < 0) { // convert the lhs
972 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
973 return rhs;
974 }
975 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000977 // Finally, we have two differing integer types.
Steve Naroffa4332e22007-07-17 00:58:39 +0000978 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000979 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
980 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000981 }
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000982 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
983 return rhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000984}
985
986// CheckPointerTypesForAssignment - This is a very tricky routine (despite
987// being closely modeled after the C99 spec:-). The odd characteristic of this
988// routine is it effectively iqnores the qualifiers on the top level pointee.
989// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
990// FIXME: add a couple examples in this comment.
991Sema::AssignmentCheckResult
992Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
993 QualType lhptee, rhptee;
994
995 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000996 lhptee = lhsType->getAsPointerType()->getPointeeType();
997 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000998
999 // make sure we operate on the canonical type
1000 lhptee = lhptee.getCanonicalType();
1001 rhptee = rhptee.getCanonicalType();
1002
1003 AssignmentCheckResult r = Compatible;
1004
1005 // C99 6.5.16.1p1: This following citation is common to constraints
1006 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1007 // qualifiers of the type *pointed to* by the right;
1008 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1009 rhptee.getQualifiers())
1010 r = CompatiblePointerDiscardsQualifiers;
1011
1012 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1013 // incomplete type and the other is a pointer to a qualified or unqualified
1014 // version of void...
1015 if (lhptee.getUnqualifiedType()->isVoidType() &&
1016 (rhptee->isObjectType() || rhptee->isIncompleteType()))
1017 ;
1018 else if (rhptee.getUnqualifiedType()->isVoidType() &&
1019 (lhptee->isObjectType() || lhptee->isIncompleteType()))
1020 ;
1021 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1022 // unqualified versions of compatible types, ...
Steve Naroffec0550f2007-10-15 20:41:53 +00001023 else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1024 rhptee.getUnqualifiedType()))
Reid Spencer5f016e22007-07-11 17:01:13 +00001025 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1026 return r;
1027}
1028
1029/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1030/// has code to accommodate several GCC extensions when type checking
1031/// pointers. Here are some objectionable examples that GCC considers warnings:
1032///
1033/// int a, *pint;
1034/// short *pshort;
1035/// struct foo *pfoo;
1036///
1037/// pint = pshort; // warning: assignment from incompatible pointer type
1038/// a = pint; // warning: assignment makes integer from pointer without a cast
1039/// pint = a; // warning: assignment makes pointer from integer without a cast
1040/// pint = pfoo; // warning: assignment from incompatible pointer type
1041///
1042/// As a result, the code for dealing with pointers is more complex than the
1043/// C99 spec dictates.
1044/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1045///
1046Sema::AssignmentCheckResult
1047Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner84d35ce2007-10-29 05:15:40 +00001048 if (lhsType.getCanonicalType() == rhsType.getCanonicalType())
1049 return Compatible; // common case, fast path...
Steve Naroff700204c2007-07-24 21:46:40 +00001050
Anders Carlsson793680e2007-10-12 23:56:29 +00001051 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroffec0550f2007-10-15 20:41:53 +00001052 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001053 return Compatible;
1054 } else if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001055 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1056 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1057 return Incompatible;
1058 }
1059 return Compatible;
1060 } else if (lhsType->isPointerType()) {
1061 if (rhsType->isIntegerType())
1062 return PointerFromInt;
1063
1064 if (rhsType->isPointerType())
1065 return CheckPointerTypesForAssignment(lhsType, rhsType);
1066 } else if (rhsType->isPointerType()) {
1067 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1068 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1069 return IntFromPointer;
1070
1071 if (lhsType->isPointerType())
1072 return CheckPointerTypesForAssignment(lhsType, rhsType);
1073 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroffec0550f2007-10-15 20:41:53 +00001074 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001075 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001076 }
1077 return Incompatible;
1078}
1079
Steve Naroff90045e82007-07-13 23:32:42 +00001080Sema::AssignmentCheckResult
1081Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Chris Lattner943140e2007-10-16 02:55:40 +00001082 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001083 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001084 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001085 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001086 //
1087 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1088 // are better understood.
1089 if (!lhsType->isReferenceType())
1090 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001091
1092 Sema::AssignmentCheckResult result;
Steve Naroff90045e82007-07-13 23:32:42 +00001093
Steve Narofff1120de2007-08-24 22:33:52 +00001094 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1095
1096 // C99 6.5.16.1p2: The value of the right operand is converted to the
1097 // type of the assignment expression.
1098 if (rExpr->getType() != lhsType)
1099 promoteExprToType(rExpr, lhsType);
1100 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001101}
1102
1103Sema::AssignmentCheckResult
1104Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1105 return CheckAssignmentConstraints(lhsType, rhsType);
1106}
1107
Steve Naroff49b45262007-07-13 16:58:59 +00001108inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001109 Diag(loc, diag::err_typecheck_invalid_operands,
1110 lex->getType().getAsString(), rex->getType().getAsString(),
1111 lex->getSourceRange(), rex->getSourceRange());
1112}
1113
Steve Naroff49b45262007-07-13 16:58:59 +00001114inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1115 Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001116 QualType lhsType = lex->getType(), rhsType = rex->getType();
1117
1118 // make sure the vector types are identical.
1119 if (lhsType == rhsType)
1120 return lhsType;
1121 // You cannot convert between vector values of different size.
1122 Diag(loc, diag::err_typecheck_vector_not_convertable,
1123 lex->getType().getAsString(), rex->getType().getAsString(),
1124 lex->getSourceRange(), rex->getSourceRange());
1125 return QualType();
1126}
1127
1128inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001129 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001130{
Steve Naroff90045e82007-07-13 23:32:42 +00001131 QualType lhsType = lex->getType(), rhsType = rex->getType();
1132
1133 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001135
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001136 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001137
Steve Naroffa4332e22007-07-17 00:58:39 +00001138 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001139 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 InvalidOperands(loc, lex, rex);
1141 return QualType();
1142}
1143
1144inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001145 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001146{
Steve Naroff90045e82007-07-13 23:32:42 +00001147 QualType lhsType = lex->getType(), rhsType = rex->getType();
1148
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001149 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001150
Steve Naroffa4332e22007-07-17 00:58:39 +00001151 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001152 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 InvalidOperands(loc, lex, rex);
1154 return QualType();
1155}
1156
1157inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001158 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001159{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001160 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001161 return CheckVectorOperands(loc, lex, rex);
1162
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001163 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Steve Naroff3e5e5562007-07-16 22:23:01 +00001164
Reid Spencer5f016e22007-07-11 17:01:13 +00001165 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001166 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001167 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001168
Steve Naroffa4332e22007-07-17 00:58:39 +00001169 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1170 return lex->getType();
1171 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1172 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001173 InvalidOperands(loc, lex, rex);
1174 return QualType();
1175}
1176
1177inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001178 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001179{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001180 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001181 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001182
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001183 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001184
1185 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001186 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001187 return compType;
Steve Naroff3e5e5562007-07-16 22:23:01 +00001188
1189 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001190 return compType;
Steve Naroff3e5e5562007-07-16 22:23:01 +00001191 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
Chris Lattner8b9023b2007-07-13 03:05:23 +00001192 return Context.getPointerDiffType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001193 InvalidOperands(loc, lex, rex);
1194 return QualType();
1195}
1196
1197inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001198 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001199{
1200 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1201 // for int << longlong -> the result type should be int, not long long.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001202 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001203
Steve Naroffa4332e22007-07-17 00:58:39 +00001204 // handle the common case first (both operands are arithmetic).
1205 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001206 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001207 InvalidOperands(loc, lex, rex);
1208 return QualType();
1209}
1210
Ted Kremeneke780f0d2007-10-29 16:45:23 +00001211// Utility method to plow through parentheses to get the first nested
1212// non-ParenExpr expr.
1213static inline Expr* IgnoreParen(Expr* E) {
Ted Kremenek59092d02007-10-30 21:03:09 +00001214 while (ParenExpr* P = dyn_cast<ParenExpr>(E))
1215 E = P->getSubExpr();
Ted Kremeneke780f0d2007-10-29 16:45:23 +00001216
1217 return E;
1218}
1219
Chris Lattnera5937dd2007-08-26 01:18:55 +00001220inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1221 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Reid Spencer5f016e22007-07-11 17:01:13 +00001222{
Chris Lattnera5937dd2007-08-26 01:18:55 +00001223 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00001224 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1225 UsualArithmeticConversions(lex, rex);
1226 else {
1227 UsualUnaryConversions(lex);
1228 UsualUnaryConversions(rex);
1229 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001230 QualType lType = lex->getType();
1231 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001232
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001233
1234 // For non-floating point types, check for self-comparisons of the form
1235 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1236 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001237 if (!lType->isFloatingType()) {
1238 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1239 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1240 if (DRL->getDecl() == DRR->getDecl())
1241 Diag(loc, diag::warn_selfcomparison);
1242 }
1243
Chris Lattnera5937dd2007-08-26 01:18:55 +00001244 if (isRelational) {
1245 if (lType->isRealType() && rType->isRealType())
1246 return Context.IntTy;
1247 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001248 // Check for comparisons of floating point operands using != and ==.
1249 // Issue a warning if these are no self-comparisons, as they are not likely
1250 // to do what the programmer intended.
1251 if (lType->isFloatingType()) {
1252 assert (rType->isFloatingType());
1253
Ted Kremenek6a261552007-10-29 16:40:01 +00001254 // Special case: check for x == x (which is OK).
1255 bool EmitWarning = true;
1256
Ted Kremeneke780f0d2007-10-29 16:45:23 +00001257 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1258 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
Ted Kremenek6a261552007-10-29 16:40:01 +00001259 if (DRL->getDecl() == DRR->getDecl())
1260 EmitWarning = false;
1261
1262 if (EmitWarning)
1263 Diag(loc, diag::warn_floatingpoint_eq);
1264 }
1265
Chris Lattnera5937dd2007-08-26 01:18:55 +00001266 if (lType->isArithmeticType() && rType->isArithmeticType())
1267 return Context.IntTy;
1268 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001269
Chris Lattnerd28f8152007-08-26 01:10:14 +00001270 bool LHSIsNull = lex->isNullPointerConstant(Context);
1271 bool RHSIsNull = rex->isNullPointerConstant(Context);
1272
Chris Lattnera5937dd2007-08-26 01:18:55 +00001273 // All of the following pointer related warnings are GCC extensions, except
1274 // when handling null pointer constants. One day, we can consider making them
1275 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00001276 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerd28f8152007-08-26 01:10:14 +00001277 if (!LHSIsNull && !RHSIsNull &&
Steve Naroffec0550f2007-10-15 20:41:53 +00001278 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1279 rType.getUnqualifiedType())) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001280 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1281 lType.getAsString(), rType.getAsString(),
1282 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001283 }
Chris Lattnerd28f8152007-08-26 01:10:14 +00001284 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001285 return Context.IntTy;
1286 }
1287 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001288 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001289 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1290 lType.getAsString(), rType.getAsString(),
1291 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001292 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001293 return Context.IntTy;
1294 }
1295 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001296 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001297 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1298 lType.getAsString(), rType.getAsString(),
1299 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001300 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001301 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 }
1303 InvalidOperands(loc, lex, rex);
1304 return QualType();
1305}
1306
Reid Spencer5f016e22007-07-11 17:01:13 +00001307inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001308 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001309{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001310 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001311 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001312
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001313 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001314
Steve Naroffa4332e22007-07-17 00:58:39 +00001315 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001316 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 InvalidOperands(loc, lex, rex);
1318 return QualType();
1319}
1320
1321inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00001322 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001323{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001324 UsualUnaryConversions(lex);
1325 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001326
Steve Naroffa4332e22007-07-17 00:58:39 +00001327 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 return Context.IntTy;
1329 InvalidOperands(loc, lex, rex);
1330 return QualType();
1331}
1332
1333inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00001334 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001335{
1336 QualType lhsType = lex->getType();
1337 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1338 bool hadError = false;
1339 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1340
1341 switch (mlval) { // C99 6.5.16p2
1342 case Expr::MLV_Valid:
1343 break;
1344 case Expr::MLV_ConstQualified:
1345 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1346 hadError = true;
1347 break;
1348 case Expr::MLV_ArrayType:
1349 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1350 lhsType.getAsString(), lex->getSourceRange());
1351 return QualType();
1352 case Expr::MLV_NotObjectType:
1353 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1354 lhsType.getAsString(), lex->getSourceRange());
1355 return QualType();
1356 case Expr::MLV_InvalidExpression:
1357 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1358 lex->getSourceRange());
1359 return QualType();
1360 case Expr::MLV_IncompleteType:
1361 case Expr::MLV_IncompleteVoidType:
1362 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1363 lhsType.getAsString(), lex->getSourceRange());
1364 return QualType();
Steve Narofffec0b492007-07-30 03:29:09 +00001365 case Expr::MLV_DuplicateVectorComponents:
1366 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1367 lex->getSourceRange());
1368 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 }
Steve Naroff90045e82007-07-13 23:32:42 +00001370 AssignmentCheckResult result;
1371
1372 if (compoundType.isNull())
1373 result = CheckSingleAssignmentConstraints(lhsType, rex);
1374 else
1375 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001376
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 // decode the result (notice that extensions still return a type).
1378 switch (result) {
1379 case Compatible:
1380 break;
1381 case Incompatible:
1382 Diag(loc, diag::err_typecheck_assign_incompatible,
1383 lhsType.getAsString(), rhsType.getAsString(),
1384 lex->getSourceRange(), rex->getSourceRange());
1385 hadError = true;
1386 break;
1387 case PointerFromInt:
1388 // check for null pointer constant (C99 6.3.2.3p3)
Chris Lattner590b6642007-07-15 23:26:56 +00001389 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1391 lhsType.getAsString(), rhsType.getAsString(),
1392 lex->getSourceRange(), rex->getSourceRange());
1393 }
1394 break;
1395 case IntFromPointer:
1396 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1397 lhsType.getAsString(), rhsType.getAsString(),
1398 lex->getSourceRange(), rex->getSourceRange());
1399 break;
1400 case IncompatiblePointer:
1401 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1402 lhsType.getAsString(), rhsType.getAsString(),
1403 lex->getSourceRange(), rex->getSourceRange());
1404 break;
1405 case CompatiblePointerDiscardsQualifiers:
1406 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1407 lhsType.getAsString(), rhsType.getAsString(),
1408 lex->getSourceRange(), rex->getSourceRange());
1409 break;
1410 }
1411 // C99 6.5.16p3: The type of an assignment expression is the type of the
1412 // left operand unless the left operand has qualified type, in which case
1413 // it is the unqualified version of the type of the left operand.
1414 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1415 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001416 // C++ 5.17p1: the type of the assignment expression is that of its left
1417 // oprdu.
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 return hadError ? QualType() : lhsType.getUnqualifiedType();
1419}
1420
1421inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00001422 Expr *&lex, Expr *&rex, SourceLocation loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001423 UsualUnaryConversions(rex);
1424 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001425}
1426
Steve Naroff49b45262007-07-13 16:58:59 +00001427/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1428/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00001429QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00001430 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001431 assert(!resType.isNull() && "no type for increment/decrement expression");
1432
Steve Naroff084f9ed2007-08-24 17:20:07 +00001433 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00001434 if (const PointerType *pt = resType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001435 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1436 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1437 resType.getAsString(), op->getSourceRange());
1438 return QualType();
1439 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00001440 } else if (!resType->isRealType()) {
1441 if (resType->isComplexType())
1442 // C99 does not support ++/-- on complex types.
1443 Diag(OpLoc, diag::ext_integer_increment_complex,
1444 resType.getAsString(), op->getSourceRange());
1445 else {
1446 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1447 resType.getAsString(), op->getSourceRange());
1448 return QualType();
1449 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001450 }
Steve Naroffdd10e022007-08-23 21:37:33 +00001451 // At this point, we know we have a real, complex or pointer type.
1452 // Now make sure the operand is a modifiable lvalue.
Reid Spencer5f016e22007-07-11 17:01:13 +00001453 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1454 if (mlval != Expr::MLV_Valid) {
1455 // FIXME: emit a more precise diagnostic...
1456 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1457 op->getSourceRange());
1458 return QualType();
1459 }
1460 return resType;
1461}
1462
1463/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1464/// This routine allows us to typecheck complex/recursive expressions
1465/// where the declaration is needed for type checking. Here are some
1466/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1467static Decl *getPrimaryDeclaration(Expr *e) {
1468 switch (e->getStmtClass()) {
1469 case Stmt::DeclRefExprClass:
1470 return cast<DeclRefExpr>(e)->getDecl();
1471 case Stmt::MemberExprClass:
1472 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1473 case Stmt::ArraySubscriptExprClass:
1474 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1475 case Stmt::CallExprClass:
1476 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1477 case Stmt::UnaryOperatorClass:
1478 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1479 case Stmt::ParenExprClass:
1480 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1481 default:
1482 return 0;
1483 }
1484}
1485
1486/// CheckAddressOfOperand - The operand of & must be either a function
1487/// designator or an lvalue designating an object. If it is an lvalue, the
1488/// object cannot be declared with storage class register or be a bit field.
1489/// Note: The usual conversions are *not* applied to the operand of the &
1490/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1491QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1492 Decl *dcl = getPrimaryDeclaration(op);
1493 Expr::isLvalueResult lval = op->isLvalue();
1494
1495 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1496 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1497 ;
1498 else { // FIXME: emit more specific diag...
1499 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1500 op->getSourceRange());
1501 return QualType();
1502 }
1503 } else if (dcl) {
1504 // We have an lvalue with a decl. Make sure the decl is not declared
1505 // with the register storage-class specifier.
1506 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1507 if (vd->getStorageClass() == VarDecl::Register) {
1508 Diag(OpLoc, diag::err_typecheck_address_of_register,
1509 op->getSourceRange());
1510 return QualType();
1511 }
1512 } else
1513 assert(0 && "Unknown/unexpected decl type");
1514
1515 // FIXME: add check for bitfields!
1516 }
1517 // If the operand has type "type", the result has type "pointer to type".
1518 return Context.getPointerType(op->getType());
1519}
1520
1521QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001522 UsualUnaryConversions(op);
1523 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001524
Chris Lattnerbefee482007-07-31 16:53:04 +00001525 if (const PointerType *PT = qType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 QualType ptype = PT->getPointeeType();
1527 // C99 6.5.3.2p4. "if it points to an object,...".
1528 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1529 // GCC compat: special case 'void *' (treat as warning).
1530 if (ptype->isVoidType()) {
1531 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1532 qType.getAsString(), op->getSourceRange());
1533 } else {
1534 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1535 ptype.getAsString(), op->getSourceRange());
1536 return QualType();
1537 }
1538 }
1539 return ptype;
1540 }
1541 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1542 qType.getAsString(), op->getSourceRange());
1543 return QualType();
1544}
1545
1546static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1547 tok::TokenKind Kind) {
1548 BinaryOperator::Opcode Opc;
1549 switch (Kind) {
1550 default: assert(0 && "Unknown binop!");
1551 case tok::star: Opc = BinaryOperator::Mul; break;
1552 case tok::slash: Opc = BinaryOperator::Div; break;
1553 case tok::percent: Opc = BinaryOperator::Rem; break;
1554 case tok::plus: Opc = BinaryOperator::Add; break;
1555 case tok::minus: Opc = BinaryOperator::Sub; break;
1556 case tok::lessless: Opc = BinaryOperator::Shl; break;
1557 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1558 case tok::lessequal: Opc = BinaryOperator::LE; break;
1559 case tok::less: Opc = BinaryOperator::LT; break;
1560 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1561 case tok::greater: Opc = BinaryOperator::GT; break;
1562 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1563 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1564 case tok::amp: Opc = BinaryOperator::And; break;
1565 case tok::caret: Opc = BinaryOperator::Xor; break;
1566 case tok::pipe: Opc = BinaryOperator::Or; break;
1567 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1568 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1569 case tok::equal: Opc = BinaryOperator::Assign; break;
1570 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1571 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1572 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1573 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1574 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1575 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1576 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1577 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1578 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1579 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1580 case tok::comma: Opc = BinaryOperator::Comma; break;
1581 }
1582 return Opc;
1583}
1584
1585static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1586 tok::TokenKind Kind) {
1587 UnaryOperator::Opcode Opc;
1588 switch (Kind) {
1589 default: assert(0 && "Unknown unary op!");
1590 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1591 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1592 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1593 case tok::star: Opc = UnaryOperator::Deref; break;
1594 case tok::plus: Opc = UnaryOperator::Plus; break;
1595 case tok::minus: Opc = UnaryOperator::Minus; break;
1596 case tok::tilde: Opc = UnaryOperator::Not; break;
1597 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1598 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1599 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1600 case tok::kw___real: Opc = UnaryOperator::Real; break;
1601 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1602 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1603 }
1604 return Opc;
1605}
1606
1607// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001608Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 ExprTy *LHS, ExprTy *RHS) {
1610 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1611 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1612
Steve Narofff69936d2007-09-16 03:34:24 +00001613 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1614 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00001615
1616 QualType ResultTy; // Result type of the binary operator.
1617 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1618
1619 switch (Opc) {
1620 default:
1621 assert(0 && "Unknown binary expr!");
1622 case BinaryOperator::Assign:
1623 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1624 break;
1625 case BinaryOperator::Mul:
1626 case BinaryOperator::Div:
1627 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1628 break;
1629 case BinaryOperator::Rem:
1630 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1631 break;
1632 case BinaryOperator::Add:
1633 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1634 break;
1635 case BinaryOperator::Sub:
1636 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1637 break;
1638 case BinaryOperator::Shl:
1639 case BinaryOperator::Shr:
1640 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1641 break;
1642 case BinaryOperator::LE:
1643 case BinaryOperator::LT:
1644 case BinaryOperator::GE:
1645 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001646 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 break;
1648 case BinaryOperator::EQ:
1649 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001650 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 break;
1652 case BinaryOperator::And:
1653 case BinaryOperator::Xor:
1654 case BinaryOperator::Or:
1655 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1656 break;
1657 case BinaryOperator::LAnd:
1658 case BinaryOperator::LOr:
1659 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1660 break;
1661 case BinaryOperator::MulAssign:
1662 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001663 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 if (!CompTy.isNull())
1665 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1666 break;
1667 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001668 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 if (!CompTy.isNull())
1670 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1671 break;
1672 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001673 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001674 if (!CompTy.isNull())
1675 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1676 break;
1677 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001678 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001679 if (!CompTy.isNull())
1680 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1681 break;
1682 case BinaryOperator::ShlAssign:
1683 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001684 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 if (!CompTy.isNull())
1686 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1687 break;
1688 case BinaryOperator::AndAssign:
1689 case BinaryOperator::XorAssign:
1690 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001691 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 if (!CompTy.isNull())
1693 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1694 break;
1695 case BinaryOperator::Comma:
1696 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1697 break;
1698 }
1699 if (ResultTy.isNull())
1700 return true;
1701 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001702 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001704 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001705}
1706
1707// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001708Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00001709 ExprTy *input) {
1710 Expr *Input = (Expr*)input;
1711 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1712 QualType resultType;
1713 switch (Opc) {
1714 default:
1715 assert(0 && "Unimplemented unary expr!");
1716 case UnaryOperator::PreInc:
1717 case UnaryOperator::PreDec:
1718 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1719 break;
1720 case UnaryOperator::AddrOf:
1721 resultType = CheckAddressOfOperand(Input, OpLoc);
1722 break;
1723 case UnaryOperator::Deref:
1724 resultType = CheckIndirectionOperand(Input, OpLoc);
1725 break;
1726 case UnaryOperator::Plus:
1727 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001728 UsualUnaryConversions(Input);
1729 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001730 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1731 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1732 resultType.getAsString());
1733 break;
1734 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001735 UsualUnaryConversions(Input);
1736 resultType = Input->getType();
Steve Naroff084f9ed2007-08-24 17:20:07 +00001737 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1738 if (!resultType->isIntegerType()) {
1739 if (resultType->isComplexType())
1740 // C99 does not support '~' for complex conjugation.
1741 Diag(OpLoc, diag::ext_integer_complement_complex,
1742 resultType.getAsString());
1743 else
1744 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1745 resultType.getAsString());
1746 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 break;
1748 case UnaryOperator::LNot: // logical negation
1749 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001750 DefaultFunctionArrayConversion(Input);
1751 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1753 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1754 resultType.getAsString());
1755 // LNot always has type int. C99 6.5.3.3p5.
1756 resultType = Context.IntTy;
1757 break;
1758 case UnaryOperator::SizeOf:
1759 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1760 break;
1761 case UnaryOperator::AlignOf:
1762 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1763 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00001764 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00001765 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00001766 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00001767 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001768 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 resultType = Input->getType();
1770 break;
1771 }
1772 if (resultType.isNull())
1773 return true;
1774 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1775}
1776
Steve Naroff1b273c42007-09-16 14:56:35 +00001777/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1778Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 SourceLocation LabLoc,
1780 IdentifierInfo *LabelII) {
1781 // Look up the record for this label identifier.
1782 LabelStmt *&LabelDecl = LabelMap[LabelII];
1783
1784 // If we haven't seen this label yet, create a forward reference.
1785 if (LabelDecl == 0)
1786 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1787
1788 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00001789 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1790 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001791}
1792
Steve Naroff1b273c42007-09-16 14:56:35 +00001793Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001794 SourceLocation RPLoc) { // "({..})"
1795 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1796 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1797 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1798
1799 // FIXME: there are a variety of strange constraints to enforce here, for
1800 // example, it is not possible to goto into a stmt expression apparently.
1801 // More semantic analysis is needed.
1802
1803 // FIXME: the last statement in the compount stmt has its value used. We
1804 // should not warn about it being unused.
1805
1806 // If there are sub stmts in the compound stmt, take the type of the last one
1807 // as the type of the stmtexpr.
1808 QualType Ty = Context.VoidTy;
1809
1810 if (!Compound->body_empty())
1811 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1812 Ty = LastExpr->getType();
1813
1814 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1815}
Steve Naroffd34e9152007-08-01 22:05:33 +00001816
Steve Naroff1b273c42007-09-16 14:56:35 +00001817Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001818 SourceLocation TypeLoc,
1819 TypeTy *argty,
1820 OffsetOfComponent *CompPtr,
1821 unsigned NumComponents,
1822 SourceLocation RPLoc) {
1823 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1824 assert(!ArgTy.isNull() && "Missing type argument!");
1825
1826 // We must have at least one component that refers to the type, and the first
1827 // one is known to be a field designator. Verify that the ArgTy represents
1828 // a struct/union/class.
1829 if (!ArgTy->isRecordType())
1830 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1831
1832 // Otherwise, create a compound literal expression as the base, and
1833 // iteratively process the offsetof designators.
1834 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1835
Chris Lattner9e2b75c2007-08-31 21:49:13 +00001836 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1837 // GCC extension, diagnose them.
1838 if (NumComponents != 1)
1839 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1840 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1841
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001842 for (unsigned i = 0; i != NumComponents; ++i) {
1843 const OffsetOfComponent &OC = CompPtr[i];
1844 if (OC.isBrackets) {
1845 // Offset of an array sub-field. TODO: Should we allow vector elements?
1846 const ArrayType *AT = Res->getType()->getAsArrayType();
1847 if (!AT) {
1848 delete Res;
1849 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1850 Res->getType().getAsString());
1851 }
1852
Chris Lattner704fe352007-08-30 17:59:59 +00001853 // FIXME: C++: Verify that operator[] isn't overloaded.
1854
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001855 // C99 6.5.2.1p1
1856 Expr *Idx = static_cast<Expr*>(OC.U.E);
1857 if (!Idx->getType()->isIntegerType())
1858 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1859 Idx->getSourceRange());
1860
1861 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1862 continue;
1863 }
1864
1865 const RecordType *RC = Res->getType()->getAsRecordType();
1866 if (!RC) {
1867 delete Res;
1868 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1869 Res->getType().getAsString());
1870 }
1871
1872 // Get the decl corresponding to this.
1873 RecordDecl *RD = RC->getDecl();
1874 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1875 if (!MemberDecl)
1876 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1877 OC.U.IdentInfo->getName(),
1878 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00001879
1880 // FIXME: C++: Verify that MemberDecl isn't a static field.
1881 // FIXME: Verify that MemberDecl isn't a bitfield.
1882
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001883 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1884 }
1885
1886 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1887 BuiltinLoc);
1888}
1889
1890
Steve Naroff1b273c42007-09-16 14:56:35 +00001891Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00001892 TypeTy *arg1, TypeTy *arg2,
1893 SourceLocation RPLoc) {
1894 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1895 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1896
1897 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1898
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001899 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00001900}
1901
Steve Naroff1b273c42007-09-16 14:56:35 +00001902Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00001903 ExprTy *expr1, ExprTy *expr2,
1904 SourceLocation RPLoc) {
1905 Expr *CondExpr = static_cast<Expr*>(cond);
1906 Expr *LHSExpr = static_cast<Expr*>(expr1);
1907 Expr *RHSExpr = static_cast<Expr*>(expr2);
1908
1909 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1910
1911 // The conditional expression is required to be a constant expression.
1912 llvm::APSInt condEval(32);
1913 SourceLocation ExpLoc;
1914 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1915 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1916 CondExpr->getSourceRange());
1917
1918 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1919 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1920 RHSExpr->getType();
1921 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1922}
1923
Anders Carlsson7c50aca2007-10-15 20:28:48 +00001924Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
1925 ExprTy *expr, TypeTy *type,
1926 SourceLocation RPLoc)
1927{
1928 Expr *E = static_cast<Expr*>(expr);
1929 QualType T = QualType::getFromOpaquePtr(type);
1930
1931 InitBuiltinVaListType();
1932
1933 Sema::AssignmentCheckResult result;
1934
1935 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
1936 E->getType());
1937 if (result != Compatible)
1938 return Diag(E->getLocStart(),
1939 diag::err_first_argument_to_va_arg_not_of_type_va_list,
1940 E->getType().getAsString(),
1941 E->getSourceRange());
1942
1943 // FIXME: Warn if a non-POD type is passed in.
1944
1945 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
1946}
1947
Anders Carlsson55085182007-08-21 17:43:55 +00001948// TODO: Move this to SemaObjC.cpp
Steve Naroffbeaf2992007-11-03 11:27:19 +00001949Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation AtLoc,
1950 ExprTy *string) {
Anders Carlsson55085182007-08-21 17:43:55 +00001951 StringLiteral* S = static_cast<StringLiteral *>(string);
1952
1953 if (CheckBuiltinCFStringArgument(S))
1954 return true;
1955
Steve Naroff21988912007-10-15 23:35:17 +00001956 if (Context.getObjcConstantStringInterface().isNull()) {
1957 // Initialize the constant string interface lazily. This assumes
1958 // the NSConstantString interface is seen in this translation unit.
1959 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
1960 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
1961 SourceLocation(), TUScope);
Steve Naroffa1fe1172007-10-16 00:00:18 +00001962 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff806a4eb2007-10-18 23:53:51 +00001963 if (!strIFace)
1964 return Diag(S->getLocStart(), diag::err_undef_interface,
1965 NSIdent->getName());
Steve Naroffa1fe1172007-10-16 00:00:18 +00001966 Context.setObjcConstantStringInterface(strIFace);
Steve Naroff21988912007-10-15 23:35:17 +00001967 }
1968 QualType t = Context.getObjcConstantStringInterface();
Anders Carlsson55085182007-08-21 17:43:55 +00001969 t = Context.getPointerType(t);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001970 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlsson55085182007-08-21 17:43:55 +00001971}
Anders Carlssonf9bcf012007-08-22 15:14:15 +00001972
1973Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattner674af952007-10-16 22:51:17 +00001974 SourceLocation EncodeLoc,
Anders Carlssonf9bcf012007-08-22 15:14:15 +00001975 SourceLocation LParenLoc,
1976 TypeTy *Ty,
1977 SourceLocation RParenLoc) {
1978 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
1979
1980 QualType t = Context.getPointerType(Context.CharTy);
1981 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
1982}
Steve Naroff708391a2007-09-17 21:01:15 +00001983
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00001984Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1985 SourceLocation AtLoc,
Fariborz Jahanian2a35fa92007-10-16 23:21:02 +00001986 SourceLocation SelLoc,
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00001987 SourceLocation LParenLoc,
1988 SourceLocation RParenLoc) {
Steve Naroff8ee529b2007-10-31 18:42:27 +00001989 QualType t = Context.getObjcSelType();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00001990 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
1991}
1992
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00001993Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1994 SourceLocation AtLoc,
1995 SourceLocation ProtoLoc,
1996 SourceLocation LParenLoc,
1997 SourceLocation RParenLoc) {
1998 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
1999 if (!PDecl) {
2000 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
2001 return true;
2002 }
2003
2004 QualType t = GetObjcProtoType(AtLoc);
Fariborz Jahanian3e27aa12007-10-18 22:59:23 +00002005 if (t.isNull())
2006 return true;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002007 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
2008}
Steve Naroff81bfde92007-10-16 23:12:48 +00002009
2010bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2011 ObjcMethodDecl *Method) {
2012 bool anyIncompatibleArgs = false;
2013
2014 for (unsigned i = 0; i < NumArgs; i++) {
2015 Expr *argExpr = Args[i];
2016 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2017
2018 QualType lhsType = Method->getParamDecl(i)->getType();
2019 QualType rhsType = argExpr->getType();
2020
2021 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2022 if (const ArrayType *ary = lhsType->getAsArrayType())
2023 lhsType = Context.getPointerType(ary->getElementType());
2024 else if (lhsType->isFunctionType())
2025 lhsType = Context.getPointerType(lhsType);
2026
2027 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2028 argExpr);
2029 if (Args[i] != argExpr) // The expression was converted.
2030 Args[i] = argExpr; // Make sure we store the converted expression.
2031 SourceLocation l = argExpr->getLocStart();
2032
2033 // decode the result (notice that AST's are still created for extensions).
2034 switch (result) {
2035 case Compatible:
2036 break;
2037 case PointerFromInt:
2038 // check for null pointer constant (C99 6.3.2.3p3)
2039 if (!argExpr->isNullPointerConstant(Context)) {
2040 Diag(l, diag::ext_typecheck_sending_pointer_int,
2041 lhsType.getAsString(), rhsType.getAsString(),
2042 argExpr->getSourceRange());
2043 }
2044 break;
2045 case IntFromPointer:
2046 Diag(l, diag::ext_typecheck_sending_pointer_int,
2047 lhsType.getAsString(), rhsType.getAsString(),
2048 argExpr->getSourceRange());
2049 break;
2050 case IncompatiblePointer:
2051 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2052 rhsType.getAsString(), lhsType.getAsString(),
2053 argExpr->getSourceRange());
2054 break;
2055 case CompatiblePointerDiscardsQualifiers:
2056 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2057 rhsType.getAsString(), lhsType.getAsString(),
2058 argExpr->getSourceRange());
2059 break;
2060 case Incompatible:
2061 Diag(l, diag::err_typecheck_sending_incompatible,
2062 rhsType.getAsString(), lhsType.getAsString(),
2063 argExpr->getSourceRange());
2064 anyIncompatibleArgs = true;
2065 }
2066 }
2067 return anyIncompatibleArgs;
2068}
2069
Steve Naroff68d331a2007-09-27 14:38:14 +00002070// ActOnClassMessage - used for both unary and keyword messages.
2071// ArgExprs is optional - if it is present, the number of expressions
2072// is obtained from Sel.getNumArgs().
2073Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002074 Scope *S,
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002075 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff68d331a2007-09-27 14:38:14 +00002076 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args)
Steve Naroff708391a2007-09-17 21:01:15 +00002077{
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002078 assert(receiverName && "missing receiver class name");
Steve Naroff563477d2007-09-18 23:55:05 +00002079
Steve Naroff81bfde92007-10-16 23:12:48 +00002080 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002081 ObjcInterfaceDecl* ClassDecl = 0;
2082 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2083 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahaniancffff842007-11-12 20:20:37 +00002084 if (ClassDecl && CurMethodDecl->isInstance()) {
Fariborz Jahanian0523aaf2007-11-12 20:13:27 +00002085 IdentifierInfo &II = Context.Idents.get("self");
2086 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II,
2087 false);
2088 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2089 superTy = Context.getPointerType(superTy);
2090 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2091 SourceLocation(), ReceiverExpr.Val);
2092
2093 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
2094 Args);
2095 }
2096 // class method
2097 if (ClassDecl)
2098 receiverName = ClassDecl->getIdentifier();
2099 }
2100 else
2101 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002102 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff983df5b2007-10-16 20:39:36 +00002103 QualType returnType;
Steve Naroff945c0a82007-11-05 15:27:52 +00002104
2105 // Before we give up, check if the selector is an instance method.
2106 if (!Method)
2107 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff983df5b2007-10-16 20:39:36 +00002108 if (!Method) {
2109 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2110 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002111 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002112 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002113 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002114 if (Sel.getNumArgs()) {
2115 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2116 return true;
2117 }
Steve Naroff983df5b2007-10-16 20:39:36 +00002118 }
Steve Naroffdb611d52007-11-03 16:37:59 +00002119 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
2120 lbrac, rbrac, ArgExprs);
Steve Naroff708391a2007-09-17 21:01:15 +00002121}
2122
Steve Naroff68d331a2007-09-27 14:38:14 +00002123// ActOnInstanceMessage - used for both unary and keyword messages.
2124// ArgExprs is optional - if it is present, the number of expressions
2125// is obtained from Sel.getNumArgs().
2126Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroffbcfb06a2007-09-28 22:22:11 +00002127 ExprTy *receiver, Selector Sel,
Steve Naroff68d331a2007-09-27 14:38:14 +00002128 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args)
2129{
Steve Naroff563477d2007-09-18 23:55:05 +00002130 assert(receiver && "missing receiver expression");
2131
Steve Naroff81bfde92007-10-16 23:12:48 +00002132 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroff563477d2007-09-18 23:55:05 +00002133 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002134 QualType receiverType = RExpr->getType();
Steve Naroff3b950172007-10-10 21:53:07 +00002135 QualType returnType;
Steve Naroffdb611d52007-11-03 16:37:59 +00002136 ObjcMethodDecl *Method;
Steve Naroff3b950172007-10-10 21:53:07 +00002137
Steve Naroff7c249152007-11-11 17:52:25 +00002138 if (receiverType == Context.getObjcIdType() ||
2139 receiverType == Context.getObjcClassType()) {
Steve Naroffdb611d52007-11-03 16:37:59 +00002140 Method = InstanceMethodPool[Sel].Method;
Steve Naroff983df5b2007-10-16 20:39:36 +00002141 if (!Method) {
2142 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2143 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002144 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002145 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002146 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002147 if (Sel.getNumArgs())
2148 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2149 return true;
Steve Naroff983df5b2007-10-16 20:39:36 +00002150 }
Steve Naroff3b950172007-10-10 21:53:07 +00002151 } else {
Chris Lattner22b73ba2007-10-10 23:42:28 +00002152 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2153 // revisited. how do we get the ClassDecl from the receiver expression?
Steve Naroff3b950172007-10-10 21:53:07 +00002154 while (receiverType->isPointerType()) {
Chris Lattner22b73ba2007-10-10 23:42:28 +00002155 PointerType *pointerType =
2156 static_cast<PointerType*>(receiverType.getTypePtr());
Steve Naroff3b950172007-10-10 21:53:07 +00002157 receiverType = pointerType->getPointeeType();
2158 }
Chris Lattner22b73ba2007-10-10 23:42:28 +00002159 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2160 "bad receiver type");
Steve Naroff3b950172007-10-10 21:53:07 +00002161 ObjcInterfaceDecl* ClassDecl = static_cast<ObjcInterfaceType*>(
2162 receiverType.getTypePtr())->getDecl();
Steve Naroff983df5b2007-10-16 20:39:36 +00002163 // FIXME: consider using InstanceMethodPool, since it will be faster
2164 // than the following method (which can do *many* linear searches). The
2165 // idea is to add class info to InstanceMethodPool...
Steve Naroffdb611d52007-11-03 16:37:59 +00002166 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff983df5b2007-10-16 20:39:36 +00002167 if (!Method) {
Steve Naroffc43d8682007-11-11 00:10:47 +00002168 // If we have an implementation in scope, check "private" methods.
2169 if (ObjcImplementationDecl *ImpDecl =
2170 ObjcImplementations[ClassDecl->getIdentifier()])
2171 Method = ImpDecl->lookupInstanceMethod(Sel);
2172 }
2173 if (!Method) {
Steve Naroff983df5b2007-10-16 20:39:36 +00002174 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2175 SourceRange(lbrac, rbrac));
Steve Naroff8ee529b2007-10-31 18:42:27 +00002176 returnType = Context.getObjcIdType();
Steve Naroff983df5b2007-10-16 20:39:36 +00002177 } else {
Steve Naroff3bea81b2007-10-16 21:36:54 +00002178 returnType = Method->getResultType();
Steve Naroff81bfde92007-10-16 23:12:48 +00002179 if (Sel.getNumArgs())
2180 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2181 return true;
Steve Naroff983df5b2007-10-16 20:39:36 +00002182 }
Steve Naroff6a8a9a42007-10-02 20:01:56 +00002183 }
Steve Naroffdb611d52007-11-03 16:37:59 +00002184 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
2185 ArgExprs);
Steve Naroff708391a2007-09-17 21:01:15 +00002186}