blob: dcbfe78a41f6a0ed12eefff8acbf7e5b6c6d97aa [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Ted Kremenek30c66752007-11-25 00:58:00 +000015#include "SemaUtil.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/Expr.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000018#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Chris Lattner83bd5eb2007-12-28 05:29:59 +000023#include "llvm/ADT/OwningPtr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000025#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026using namespace clang;
27
Steve Naroff87d58b42007-09-16 03:34:24 +000028/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000029/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
30/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
31/// multiple tokens. However, the common case is that StringToks points to one
32/// string.
33///
34Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000035Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000036 assert(NumStringToks && "Must have at least one string!");
37
38 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
39 if (Literal.hadError)
40 return ExprResult(true);
41
42 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
43 for (unsigned i = 0; i != NumStringToks; ++i)
44 StringTokLocs.push_back(StringToks[i].getLocation());
45
46 // FIXME: handle wchar_t
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000047 QualType t;
48
49 if (Literal.Pascal)
50 t = Context.getPointerType(Context.UnsignedCharTy);
51 else
52 t = Context.getPointerType(Context.CharTy);
53
54 if (Literal.Pascal && Literal.GetStringLength() > 256)
55 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
56 SourceRange(StringToks[0].getLocation(),
57 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000058
59 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
60 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000061 Literal.AnyWide, t,
62 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000063 StringToks[NumStringToks-1].getLocation());
64}
65
66
Steve Naroff0acc9c92007-09-15 18:49:24 +000067/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000068/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
69/// identifier is used in an function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000070Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000071 IdentifierInfo &II,
72 bool HasTrailingLParen) {
73 // Could be enum-constant or decl.
Steve Narofff0c31dd2007-09-16 16:16:00 +000074 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Chris Lattner4b009652007-07-25 00:24:17 +000075 if (D == 0) {
76 // Otherwise, this could be an implicitly declared function reference (legal
77 // in C90, extension in C99).
78 if (HasTrailingLParen &&
79 // Not in C++.
80 !getLangOptions().CPlusPlus)
81 D = ImplicitlyDefineFunction(Loc, II, S);
82 else {
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000083 if (CurMethodDecl) {
84 ObjcInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
85 ObjcInterfaceDecl *clsDeclared;
Steve Naroff6b759ce2007-11-15 02:58:25 +000086 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
87 IdentifierInfo &II = Context.Idents.get("self");
88 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
89 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
90 static_cast<Expr*>(SelfExpr.Val), true, true);
91 }
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000092 }
Chris Lattner4b009652007-07-25 00:24:17 +000093 // If this name wasn't predeclared and if this is not a function call,
94 // diagnose the problem.
95 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
96 }
97 }
Steve Naroff91b03f72007-08-28 03:03:08 +000098 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroffcae537d2007-08-28 18:45:29 +000099 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000100 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000101 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000102 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000103 }
Chris Lattner4b009652007-07-25 00:24:17 +0000104 if (isa<TypedefDecl>(D))
105 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000106 if (isa<ObjcInterfaceDecl>(D))
107 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000108
109 assert(0 && "Invalid decl");
110 abort();
111}
112
Steve Naroff87d58b42007-09-16 03:34:24 +0000113Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000114 tok::TokenKind Kind) {
115 PreDefinedExpr::IdentType IT;
116
117 switch (Kind) {
118 default:
119 assert(0 && "Unknown simple primary expr!");
120 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
121 IT = PreDefinedExpr::Func;
122 break;
123 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
124 IT = PreDefinedExpr::Function;
125 break;
126 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
127 IT = PreDefinedExpr::PrettyFunction;
128 break;
129 }
130
131 // Pre-defined identifiers are always of type char *.
132 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
133}
134
Steve Naroff87d58b42007-09-16 03:34:24 +0000135Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000136 llvm::SmallString<16> CharBuffer;
137 CharBuffer.resize(Tok.getLength());
138 const char *ThisTokBegin = &CharBuffer[0];
139 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
140
141 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
142 Tok.getLocation(), PP);
143 if (Literal.hadError())
144 return ExprResult(true);
145 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
146 Tok.getLocation());
147}
148
Steve Naroff87d58b42007-09-16 03:34:24 +0000149Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000150 // fast path for a single digit (which is quite common). A single digit
151 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
152 if (Tok.getLength() == 1) {
153 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
154
Chris Lattner3496d522007-09-04 02:45:27 +0000155 unsigned IntSize = static_cast<unsigned>(
156 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000157 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
158 Context.IntTy,
159 Tok.getLocation()));
160 }
161 llvm::SmallString<512> IntegerBuffer;
162 IntegerBuffer.resize(Tok.getLength());
163 const char *ThisTokBegin = &IntegerBuffer[0];
164
165 // Get the spelling of the token, which eliminates trigraphs, etc.
166 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
167 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
168 Tok.getLocation(), PP);
169 if (Literal.hadError)
170 return ExprResult(true);
171
Chris Lattner1de66eb2007-08-26 03:42:43 +0000172 Expr *Res;
173
174 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000175 QualType Ty;
176 const llvm::fltSemantics *Format;
177 uint64_t Size; unsigned Align;
178
179 if (Literal.isFloat) {
180 Ty = Context.FloatTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000181 Context.Target.getFloatInfo(Size, Align, Format,
182 Context.getFullLoc(Tok.getLocation()));
183
Chris Lattner858eece2007-09-22 18:29:59 +0000184 } else if (Literal.isLong) {
185 Ty = Context.LongDoubleTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000186 Context.Target.getLongDoubleInfo(Size, Align, Format,
187 Context.getFullLoc(Tok.getLocation()));
Chris Lattner858eece2007-09-22 18:29:59 +0000188 } else {
189 Ty = Context.DoubleTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000190 Context.Target.getDoubleInfo(Size, Align, Format,
191 Context.getFullLoc(Tok.getLocation()));
Chris Lattner858eece2007-09-22 18:29:59 +0000192 }
193
Ted Kremenekddedbe22007-11-29 00:56:49 +0000194 // isExact will be set by GetFloatValue().
195 bool isExact = false;
196
197 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
198 Ty, Tok.getLocation());
199
Chris Lattner1de66eb2007-08-26 03:42:43 +0000200 } else if (!Literal.isIntegerLiteral()) {
201 return ExprResult(true);
202 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000203 QualType t;
204
Neil Booth7421e9c2007-08-29 22:00:19 +0000205 // long long is a C99 feature.
206 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000207 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000208 Diag(Tok.getLocation(), diag::ext_longlong);
209
Chris Lattner4b009652007-07-25 00:24:17 +0000210 // Get the value in the widest-possible width.
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000211 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(
212 Context.getFullLoc(Tok.getLocation())), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000213
214 if (Literal.GetIntegerValue(ResultVal)) {
215 // If this value didn't fit into uintmax_t, warn and force to ull.
216 Diag(Tok.getLocation(), diag::warn_integer_too_large);
217 t = Context.UnsignedLongLongTy;
218 assert(Context.getTypeSize(t, Tok.getLocation()) ==
219 ResultVal.getBitWidth() && "long long is not intmax_t?");
220 } else {
221 // If this value fits into a ULL, try to figure out what else it fits into
222 // according to the rules of C99 6.4.4.1p5.
223
224 // Octal, Hexadecimal, and integers with a U suffix are allowed to
225 // be an unsigned int.
226 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
227
228 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000229 if (!Literal.isLong && !Literal.isLongLong) {
230 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000231 unsigned IntSize = static_cast<unsigned>(
232 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000233 // Does it fit in a unsigned int?
234 if (ResultVal.isIntN(IntSize)) {
235 // Does it fit in a signed int?
236 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
237 t = Context.IntTy;
238 else if (AllowUnsigned)
239 t = Context.UnsignedIntTy;
240 }
241
242 if (!t.isNull())
243 ResultVal.trunc(IntSize);
244 }
245
246 // Are long/unsigned long possibilities?
247 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000248 unsigned LongSize = static_cast<unsigned>(
249 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000250
251 // Does it fit in a unsigned long?
252 if (ResultVal.isIntN(LongSize)) {
253 // Does it fit in a signed long?
254 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
255 t = Context.LongTy;
256 else if (AllowUnsigned)
257 t = Context.UnsignedLongTy;
258 }
259 if (!t.isNull())
260 ResultVal.trunc(LongSize);
261 }
262
263 // Finally, check long long if needed.
264 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000265 unsigned LongLongSize = static_cast<unsigned>(
266 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000267
268 // Does it fit in a unsigned long long?
269 if (ResultVal.isIntN(LongLongSize)) {
270 // Does it fit in a signed long long?
271 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
272 t = Context.LongLongTy;
273 else if (AllowUnsigned)
274 t = Context.UnsignedLongLongTy;
275 }
276 }
277
278 // If we still couldn't decide a type, we probably have something that
279 // does not fit in a signed long long, but has no U suffix.
280 if (t.isNull()) {
281 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
282 t = Context.UnsignedLongLongTy;
283 }
284 }
285
Chris Lattner1de66eb2007-08-26 03:42:43 +0000286 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000287 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000288
289 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
290 if (Literal.isImaginary)
291 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
292
293 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000294}
295
Steve Naroff87d58b42007-09-16 03:34:24 +0000296Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000297 ExprTy *Val) {
298 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000299 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000300 return new ParenExpr(L, R, e);
301}
302
303/// The UsualUnaryConversions() function is *not* called by this routine.
304/// See C99 6.3.2.1p[2-4] for more details.
305QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
306 SourceLocation OpLoc, bool isSizeof) {
307 // C99 6.5.3.4p1:
308 if (isa<FunctionType>(exprType) && isSizeof)
309 // alignof(function) is allowed.
310 Diag(OpLoc, diag::ext_sizeof_function_type);
311 else if (exprType->isVoidType())
312 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
313 else if (exprType->isIncompleteType()) {
314 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
315 diag::err_alignof_incomplete_type,
316 exprType.getAsString());
317 return QualType(); // error
318 }
319 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
320 return Context.getSizeType();
321}
322
323Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000324ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000325 SourceLocation LPLoc, TypeTy *Ty,
326 SourceLocation RPLoc) {
327 // If error parsing type, ignore.
328 if (Ty == 0) return true;
329
330 // Verify that this is a valid expression.
331 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
332
333 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
334
335 if (resultType.isNull())
336 return true;
337 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
338}
339
Chris Lattner5110ad52007-08-24 21:41:10 +0000340QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000341 DefaultFunctionArrayConversion(V);
342
Chris Lattnera16e42d2007-08-26 05:39:26 +0000343 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000344 if (const ComplexType *CT = V->getType()->getAsComplexType())
345 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000346
347 // Otherwise they pass through real integer and floating point types here.
348 if (V->getType()->isArithmeticType())
349 return V->getType();
350
351 // Reject anything else.
352 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
353 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000354}
355
356
Chris Lattner4b009652007-07-25 00:24:17 +0000357
Steve Naroff87d58b42007-09-16 03:34:24 +0000358Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000359 tok::TokenKind Kind,
360 ExprTy *Input) {
361 UnaryOperator::Opcode Opc;
362 switch (Kind) {
363 default: assert(0 && "Unknown unary op!");
364 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
365 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
366 }
367 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
368 if (result.isNull())
369 return true;
370 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
371}
372
373Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000374ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000375 ExprTy *Idx, SourceLocation RLoc) {
376 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
377
378 // Perform default conversions.
379 DefaultFunctionArrayConversion(LHSExp);
380 DefaultFunctionArrayConversion(RHSExp);
381
382 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
383
384 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000385 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000386 // in the subscript position. As a result, we need to derive the array base
387 // and index from the expression types.
388 Expr *BaseExpr, *IndexExpr;
389 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000390 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000391 BaseExpr = LHSExp;
392 IndexExpr = RHSExp;
393 // FIXME: need to deal with const...
394 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000395 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000396 // Handle the uncommon case of "123[Ptr]".
397 BaseExpr = RHSExp;
398 IndexExpr = LHSExp;
399 // FIXME: need to deal with const...
400 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000401 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
402 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000403 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000404
405 // Component access limited to variables (reject vec4.rg[1]).
406 if (!isa<DeclRefExpr>(BaseExpr))
407 return Diag(LLoc, diag::err_ocuvector_component_access,
408 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000409 // FIXME: need to deal with const...
410 ResultType = VTy->getElementType();
411 } else {
412 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
413 RHSExp->getSourceRange());
414 }
415 // C99 6.5.2.1p1
416 if (!IndexExpr->getType()->isIntegerType())
417 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
418 IndexExpr->getSourceRange());
419
420 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
421 // the following check catches trying to index a pointer to a function (e.g.
422 // void (*)(int)). Functions are not objects in C99.
423 if (!ResultType->isObjectType())
424 return Diag(BaseExpr->getLocStart(),
425 diag::err_typecheck_subscript_not_object,
426 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
427
428 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
429}
430
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000431QualType Sema::
432CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
433 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000434 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000435
436 // The vector accessor can't exceed the number of elements.
437 const char *compStr = CompName.getName();
438 if (strlen(compStr) > vecType->getNumElements()) {
439 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
440 baseType.getAsString(), SourceRange(CompLoc));
441 return QualType();
442 }
443 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000444 if (vecType->getPointAccessorIdx(*compStr) != -1) {
445 do
446 compStr++;
447 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
448 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
449 do
450 compStr++;
451 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
452 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
453 do
454 compStr++;
455 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
456 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000457
458 if (*compStr) {
459 // We didn't get to the end of the string. This means the component names
460 // didn't come from the same set *or* we encountered an illegal name.
461 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
462 std::string(compStr,compStr+1), SourceRange(CompLoc));
463 return QualType();
464 }
465 // Each component accessor can't exceed the vector type.
466 compStr = CompName.getName();
467 while (*compStr) {
468 if (vecType->isAccessorWithinNumElements(*compStr))
469 compStr++;
470 else
471 break;
472 }
473 if (*compStr) {
474 // We didn't get to the end of the string. This means a component accessor
475 // exceeds the number of elements in the vector.
476 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
477 baseType.getAsString(), SourceRange(CompLoc));
478 return QualType();
479 }
480 // The component accessor looks fine - now we need to compute the actual type.
481 // The vector type is implied by the component accessor. For example,
482 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
483 unsigned CompSize = strlen(CompName.getName());
484 if (CompSize == 1)
485 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000486
487 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
488 // Now look up the TypeDefDecl from the vector type. Without this,
489 // diagostics look bad. We want OCU vector types to appear built-in.
490 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
491 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
492 return Context.getTypedefType(OCUVectorDecls[i]);
493 }
494 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000495}
496
Chris Lattner4b009652007-07-25 00:24:17 +0000497Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000498ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000499 tok::TokenKind OpKind, SourceLocation MemberLoc,
500 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000501 Expr *BaseExpr = static_cast<Expr *>(Base);
502 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000503
504 // Perform default conversions.
505 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000506
Steve Naroff2cb66382007-07-26 03:11:44 +0000507 QualType BaseType = BaseExpr->getType();
508 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000509
Chris Lattner4b009652007-07-25 00:24:17 +0000510 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000511 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000512 BaseType = PT->getPointeeType();
513 else
514 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
515 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000516 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000517 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000518 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000519 RecordDecl *RDecl = RTy->getDecl();
520 if (RTy->isIncompleteType())
521 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
522 BaseExpr->getSourceRange());
523 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000524 FieldDecl *MemberDecl = RDecl->getMember(&Member);
525 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000526 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
527 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000528 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
529 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000530 // Component access limited to variables (reject vec4.rg.g).
531 if (!isa<DeclRefExpr>(BaseExpr))
532 return Diag(OpLoc, diag::err_ocuvector_component_access,
533 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000534 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
535 if (ret.isNull())
536 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000537 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000538 } else if (BaseType->isObjcInterfaceType()) {
539 ObjcInterfaceDecl *IFace;
540 if (isa<ObjcInterfaceType>(BaseType.getCanonicalType()))
541 IFace = dyn_cast<ObjcInterfaceType>(BaseType)->getDecl();
542 else
Fariborz Jahanian0c2f2142007-12-13 20:47:42 +0000543 IFace = dyn_cast<ObjcQualifiedInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000544 ObjcInterfaceDecl *clsDeclared;
545 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
546 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
547 OpKind==tok::arrow);
548 }
549 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
550 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000551}
552
Steve Naroff87d58b42007-09-16 03:34:24 +0000553/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000554/// This provides the location of the left/right parens and a list of comma
555/// locations.
556Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000557ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000558 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000559 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
560 Expr *Fn = static_cast<Expr *>(fn);
561 Expr **Args = reinterpret_cast<Expr**>(args);
562 assert(Fn && "no function call expression");
563
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000564 // Make the call expr early, before semantic checks. This guarantees cleanup
565 // of arguments and function on error.
566 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
567 Context.BoolTy, RParenLoc));
568
569 // Promote the function operand.
570 TheCall->setCallee(UsualUnaryConversions(Fn));
571
Chris Lattner4b009652007-07-25 00:24:17 +0000572 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
573 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000574 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000575 if (PT == 0)
576 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
577 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000578 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
579 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000580 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
581 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000582
583 // We know the result type of the call, set it.
584 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000585
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000586 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000587 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
588 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000589 unsigned NumArgsInProto = Proto->getNumArgs();
590 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000591
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000592 // If too few arguments are available, don't make the call.
593 if (NumArgs < NumArgsInProto)
594 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
595 Fn->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000596
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000597 // If too many are passed and not variadic, error on the extras and drop
598 // them.
599 if (NumArgs > NumArgsInProto) {
600 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000601 Diag(Args[NumArgsInProto]->getLocStart(),
602 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
603 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000604 Args[NumArgs-1]->getLocEnd()));
605 // This deletes the extra arguments.
606 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000607 }
608 NumArgsToCheck = NumArgsInProto;
609 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000610
Chris Lattner4b009652007-07-25 00:24:17 +0000611 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000612 for (unsigned i = 0; i != NumArgsToCheck; i++) {
613 Expr *Arg = Args[i];
Chris Lattner005ed752008-01-04 18:04:52 +0000614 QualType ProtoArgType = Proto->getArgType(i);
615 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000616
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000617 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +0000618 AssignConvertType ConvTy =
619 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000620 TheCall->setArg(i, Arg);
621
Chris Lattner005ed752008-01-04 18:04:52 +0000622 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
623 ArgType, Arg, "passing"))
624 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000625 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000626
627 // If this is a variadic call, handle args passed through "...".
628 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +0000629 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000630 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
631 Expr *Arg = Args[i];
632 DefaultArgumentPromotion(Arg);
633 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000634 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000635 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000636 } else {
637 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
638
Steve Naroffdb65e052007-08-28 23:30:39 +0000639 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000640 for (unsigned i = 0; i != NumArgs; i++) {
641 Expr *Arg = Args[i];
642 DefaultArgumentPromotion(Arg);
643 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000644 }
Chris Lattner4b009652007-07-25 00:24:17 +0000645 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000646
Chris Lattner2e64c072007-08-10 20:18:51 +0000647 // Do special checking on direct calls to functions.
648 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
649 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
650 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000651 if (CheckFunctionCall(FDecl, TheCall.get()))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000652 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000653
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000654 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000655}
656
657Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000658ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000659 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000660 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000661 QualType literalType = QualType::getFromOpaquePtr(Ty);
662 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000663 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000664 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000665
Steve Naroffcb69fb72007-12-10 22:44:33 +0000666 // FIXME: add more semantic analysis (C99 6.5.2.5).
667 if (CheckInitializer(literalExpr, literalType, false))
668 return 0;
Anders Carlsson9374b852007-12-05 07:24:19 +0000669
Chris Lattner386ab8a2008-01-02 21:46:24 +0000670 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000671}
672
673Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000674ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000675 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000676 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000677
Steve Naroff0acc9c92007-09-15 18:49:24 +0000678 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000679 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000680
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000681 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
682 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
683 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000684}
685
Chris Lattnerd1f26b32007-12-20 00:44:32 +0000686bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000687 assert(VectorTy->isVectorType() && "Not a vector type!");
688
689 if (Ty->isVectorType() || Ty->isIntegerType()) {
690 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
691 Context.getTypeSize(Ty, SourceLocation()))
692 return Diag(R.getBegin(),
693 Ty->isVectorType() ?
694 diag::err_invalid_conversion_between_vectors :
695 diag::err_invalid_conversion_between_vector_and_integer,
696 VectorTy.getAsString().c_str(),
697 Ty.getAsString().c_str(), R);
698 } else
699 return Diag(R.getBegin(),
700 diag::err_invalid_conversion_between_vector_and_scalar,
701 VectorTy.getAsString().c_str(),
702 Ty.getAsString().c_str(), R);
703
704 return false;
705}
706
Chris Lattner4b009652007-07-25 00:24:17 +0000707Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000708ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000709 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000710 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000711
712 Expr *castExpr = static_cast<Expr*>(Op);
713 QualType castType = QualType::getFromOpaquePtr(Ty);
714
Steve Naroff68adb482007-08-31 00:32:44 +0000715 UsualUnaryConversions(castExpr);
716
Chris Lattner4b009652007-07-25 00:24:17 +0000717 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
718 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000719 if (!castType->isVoidType()) { // Cast to void allows any expr type.
720 if (!castType->isScalarType())
721 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
722 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000723 if (!castExpr->getType()->isScalarType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000724 return Diag(castExpr->getLocStart(),
725 diag::err_typecheck_expect_scalar_operand,
726 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000727
728 if (castExpr->getType()->isVectorType()) {
729 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
730 castExpr->getType(), castType))
731 return true;
732 } else if (castType->isVectorType()) {
733 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
734 castType, castExpr->getType()))
735 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000736 }
Chris Lattner4b009652007-07-25 00:24:17 +0000737 }
738 return new CastExpr(castType, castExpr, LParenLoc);
739}
740
Steve Naroff144667e2007-10-18 05:13:08 +0000741// promoteExprToType - a helper function to ensure we create exactly one
742// ImplicitCastExpr.
743static void promoteExprToType(Expr *&expr, QualType type) {
744 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
745 impCast->setType(type);
746 else
747 expr = new ImplicitCastExpr(type, expr);
748 return;
749}
750
Chris Lattner98a425c2007-11-26 01:40:58 +0000751/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
752/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000753inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
754 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
755 UsualUnaryConversions(cond);
756 UsualUnaryConversions(lex);
757 UsualUnaryConversions(rex);
758 QualType condT = cond->getType();
759 QualType lexT = lex->getType();
760 QualType rexT = rex->getType();
761
762 // first, check the condition.
763 if (!condT->isScalarType()) { // C99 6.5.15p2
764 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
765 condT.getAsString());
766 return QualType();
767 }
Chris Lattner992ae932008-01-06 22:42:25 +0000768
769 // Now check the two expressions.
770
771 // If both operands have arithmetic type, do the usual arithmetic conversions
772 // to find a common type: C99 6.5.15p3,5.
773 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000774 UsualArithmeticConversions(lex, rex);
775 return lex->getType();
776 }
Chris Lattner992ae932008-01-06 22:42:25 +0000777
778 // If both operands are the same structure or union type, the result is that
779 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000780 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +0000781 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +0000782 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +0000783 // "If both the operands have structure or union type, the result has
784 // that type." This implies that CV qualifiers are dropped.
785 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000786 }
Chris Lattner992ae932008-01-06 22:42:25 +0000787
788 // C99 6.5.15p5: "If both operands have void type, the result has void type."
789 if (lexT->isVoidType() && rexT->isVoidType())
790 return lexT.getUnqualifiedType();
791
792 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
793 // the type of the other operand."
Steve Naroff144667e2007-10-18 05:13:08 +0000794 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
795 promoteExprToType(rex, lexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000796 return lexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000797 }
798 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
799 promoteExprToType(lex, rexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000800 return rexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000801 }
Chris Lattner71225142007-07-31 21:27:01 +0000802 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
803 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
804 // get the "pointed to" types
805 QualType lhptee = LHSPT->getPointeeType();
806 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000807
Chris Lattner71225142007-07-31 21:27:01 +0000808 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
809 if (lhptee->isVoidType() &&
810 (rhptee->isObjectType() || rhptee->isIncompleteType()))
811 return lexT;
812 if (rhptee->isVoidType() &&
813 (lhptee->isObjectType() || lhptee->isIncompleteType()))
814 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000815
Steve Naroff85f0dc52007-10-15 20:41:53 +0000816 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
817 rhptee.getUnqualifiedType())) {
Chris Lattner71225142007-07-31 21:27:01 +0000818 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
819 lexT.getAsString(), rexT.getAsString(),
820 lex->getSourceRange(), rex->getSourceRange());
821 return lexT; // FIXME: this is an _ext - is this return o.k?
822 }
823 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000824 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
825 // differently qualified versions of compatible types, the result type is
826 // a pointer to an appropriately qualified version of the *composite*
827 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000828 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000829 }
Chris Lattner4b009652007-07-25 00:24:17 +0000830 }
Chris Lattner71225142007-07-31 21:27:01 +0000831
Chris Lattner992ae932008-01-06 22:42:25 +0000832 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +0000833 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
834 lexT.getAsString(), rexT.getAsString(),
835 lex->getSourceRange(), rex->getSourceRange());
836 return QualType();
837}
838
Steve Naroff87d58b42007-09-16 03:34:24 +0000839/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000840/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000841Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000842 SourceLocation ColonLoc,
843 ExprTy *Cond, ExprTy *LHS,
844 ExprTy *RHS) {
845 Expr *CondExpr = (Expr *) Cond;
846 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000847
848 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
849 // was the condition.
850 bool isLHSNull = LHSExpr == 0;
851 if (isLHSNull)
852 LHSExpr = CondExpr;
853
Chris Lattner4b009652007-07-25 00:24:17 +0000854 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
855 RHSExpr, QuestionLoc);
856 if (result.isNull())
857 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000858 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
859 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000860}
861
Steve Naroffdb65e052007-08-28 23:30:39 +0000862/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
863/// do not have a prototype. Integer promotions are performed on each
864/// argument, and arguments that have type float are promoted to double.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000865void Sema::DefaultArgumentPromotion(Expr *&Expr) {
866 QualType Ty = Expr->getType();
867 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffdb65e052007-08-28 23:30:39 +0000868
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000869 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
870 promoteExprToType(Expr, Context.IntTy);
871 if (Ty == Context.FloatTy)
872 promoteExprToType(Expr, Context.DoubleTy);
Steve Naroffdb65e052007-08-28 23:30:39 +0000873}
874
Chris Lattner4b009652007-07-25 00:24:17 +0000875/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
876void Sema::DefaultFunctionArrayConversion(Expr *&e) {
877 QualType t = e->getType();
878 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
879
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000880 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000881 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
882 t = e->getType();
883 }
884 if (t->isFunctionType())
885 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000886 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000887 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
888}
889
890/// UsualUnaryConversion - Performs various conversions that are common to most
891/// operators (C99 6.3). The conversions of array and function types are
892/// sometimes surpressed. For example, the array->pointer conversion doesn't
893/// apply if the array is an argument to the sizeof or address (&) operators.
894/// In these instances, this routine should *not* be called.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000895Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
896 QualType Ty = Expr->getType();
897 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000898
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000899 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
900 promoteExprToType(Expr, Ref->getReferenceeType()); // C++ [expr]
901 Ty = Expr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000902 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000903 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
904 promoteExprToType(Expr, Context.IntTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000905 else
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000906 DefaultFunctionArrayConversion(Expr);
907
908 return Expr;
Chris Lattner4b009652007-07-25 00:24:17 +0000909}
910
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000911/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000912/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
913/// routine returns the first non-arithmetic type found. The client is
914/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000915QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
916 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000917 if (!isCompAssign) {
918 UsualUnaryConversions(lhsExpr);
919 UsualUnaryConversions(rhsExpr);
920 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000921 // For conversion purposes, we ignore any qualifiers.
922 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000923 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
924 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000925
926 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000927 if (lhs == rhs)
928 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000929
930 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
931 // The caller can deal with this (e.g. pointer + int).
932 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000933 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000934
935 // At this point, we have two different arithmetic types.
936
937 // Handle complex types first (C99 6.3.1.8p1).
938 if (lhs->isComplexType() || rhs->isComplexType()) {
939 // if we have an integer operand, the result is the complex type.
940 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000941 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
942 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000943 }
944 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000945 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
946 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000947 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000948 // This handles complex/complex, complex/float, or float/complex.
949 // When both operands are complex, the shorter operand is converted to the
950 // type of the longer, and that is the type of the result. This corresponds
951 // to what is done when combining two real floating-point operands.
952 // The fun begins when size promotion occur across type domains.
953 // From H&S 6.3.4: When one operand is complex and the other is a real
954 // floating-point type, the less precise type is converted, within it's
955 // real or complex domain, to the precision of the other type. For example,
956 // when combining a "long double" with a "double _Complex", the
957 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000958 int result = Context.compareFloatingType(lhs, rhs);
959
960 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000961 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
962 if (!isCompAssign)
963 promoteExprToType(rhsExpr, rhs);
964 } else if (result < 0) { // The right side is bigger, convert lhs.
965 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
966 if (!isCompAssign)
967 promoteExprToType(lhsExpr, lhs);
968 }
969 // At this point, lhs and rhs have the same rank/size. Now, make sure the
970 // domains match. This is a requirement for our implementation, C99
971 // does not require this promotion.
972 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
973 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000974 if (!isCompAssign)
975 promoteExprToType(lhsExpr, rhs);
976 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000977 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000978 if (!isCompAssign)
979 promoteExprToType(rhsExpr, lhs);
980 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000981 }
Chris Lattner4b009652007-07-25 00:24:17 +0000982 }
Steve Naroff3b6157f2007-08-27 21:43:43 +0000983 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +0000984 }
985 // Now handle "real" floating types (i.e. float, double, long double).
986 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
987 // if we have an integer operand, the result is the real floating type.
988 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000989 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
990 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000991 }
992 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000993 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
994 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000995 }
996 // We have two real floating types, float/complex combos were handled above.
997 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +0000998 int result = Context.compareFloatingType(lhs, rhs);
999
1000 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001001 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1002 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001003 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001004 if (result < 0) { // convert the lhs
1005 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1006 return rhs;
1007 }
1008 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001009 }
1010 // Finally, we have two differing integer types.
1011 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001012 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1013 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001014 }
Steve Naroff8f708362007-08-24 19:07:16 +00001015 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1016 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001017}
1018
1019// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1020// being closely modeled after the C99 spec:-). The odd characteristic of this
1021// routine is it effectively iqnores the qualifiers on the top level pointee.
1022// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1023// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001024Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001025Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1026 QualType lhptee, rhptee;
1027
1028 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001029 lhptee = lhsType->getAsPointerType()->getPointeeType();
1030 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001031
1032 // make sure we operate on the canonical type
1033 lhptee = lhptee.getCanonicalType();
1034 rhptee = rhptee.getCanonicalType();
1035
Chris Lattner005ed752008-01-04 18:04:52 +00001036 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001037
1038 // C99 6.5.16.1p1: This following citation is common to constraints
1039 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1040 // qualifiers of the type *pointed to* by the right;
1041 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1042 rhptee.getQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001043 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001044
1045 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1046 // incomplete type and the other is a pointer to a qualified or unqualified
1047 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001048 if (lhptee->isVoidType()) {
1049 if (rhptee->isObjectType() || rhptee->isIncompleteType())
Chris Lattner005ed752008-01-04 18:04:52 +00001050 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001051
1052 // As an extension, we allow cast to/from void* to function pointer.
1053 if (rhptee->isFunctionType())
1054 return FunctionVoidPointer;
1055 }
1056
1057 if (rhptee->isVoidType()) {
1058 if (lhptee->isObjectType() || lhptee->isIncompleteType())
Chris Lattner005ed752008-01-04 18:04:52 +00001059 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001060
1061 // As an extension, we allow cast to/from void* to function pointer.
1062 if (lhptee->isFunctionType())
1063 return FunctionVoidPointer;
1064 }
1065
Chris Lattner4b009652007-07-25 00:24:17 +00001066 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1067 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001068 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1069 rhptee.getUnqualifiedType()))
1070 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001071 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001072}
1073
1074/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1075/// has code to accommodate several GCC extensions when type checking
1076/// pointers. Here are some objectionable examples that GCC considers warnings:
1077///
1078/// int a, *pint;
1079/// short *pshort;
1080/// struct foo *pfoo;
1081///
1082/// pint = pshort; // warning: assignment from incompatible pointer type
1083/// a = pint; // warning: assignment makes integer from pointer without a cast
1084/// pint = a; // warning: assignment makes pointer from integer without a cast
1085/// pint = pfoo; // warning: assignment from incompatible pointer type
1086///
1087/// As a result, the code for dealing with pointers is more complex than the
1088/// C99 spec dictates.
1089/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1090///
Chris Lattner005ed752008-01-04 18:04:52 +00001091Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001092Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001093 // Get canonical types. We're not formatting these types, just comparing
1094 // them.
1095 lhsType = lhsType.getCanonicalType();
1096 rhsType = rhsType.getCanonicalType();
1097
1098 if (lhsType.getUnqualifiedType() == rhsType.getUnqualifiedType())
Chris Lattnera703c2e2007-10-29 05:15:40 +00001099 return Compatible; // common case, fast path...
Chris Lattner4b009652007-07-25 00:24:17 +00001100
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001101 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001102 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001103 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001104 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001105 }
Chris Lattner1853da22008-01-04 23:18:45 +00001106
1107 if (lhsType->isObjcQualifiedIdType()
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001108 || rhsType->isObjcQualifiedIdType()) {
1109 if (Context.ObjcQualifiedIdTypesAreCompatible(lhsType, rhsType))
1110 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001111 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001112 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001113
1114 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1115 // For OCUVector, allow vector splats; float -> <n x float>
1116 if (const OCUVectorType *LV = lhsType->getAsOCUVectorType()) {
1117 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1118 return Compatible;
1119 }
1120
1121 // If LHS and RHS are both vectors of integer or both vectors of floating
1122 // point types, and the total vector length is the same, allow the
1123 // conversion. This is a bitcast; no bits are changed but the result type
1124 // is different.
1125 if (getLangOptions().LaxVectorConversions &&
1126 lhsType->isVectorType() && rhsType->isVectorType()) {
1127 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1128 (lhsType->isRealFloatingType() && rhsType->isRealFloatingType())) {
1129 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1130 Context.getTypeSize(rhsType, SourceLocation()))
Nate Begemanec2d1062007-12-30 02:59:45 +00001131 return Compatible;
1132 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001133 }
1134 return Incompatible;
1135 }
1136
1137 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001138 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001139
1140 if (lhsType->isPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001141 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001142 return IntToPointer;
Chris Lattner4b009652007-07-25 00:24:17 +00001143
1144 if (rhsType->isPointerType())
1145 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001146 return Incompatible;
1147 }
1148
1149 if (rhsType->isPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001150 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1151 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001152 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001153
1154 if (lhsType->isPointerType())
1155 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001156 return Incompatible;
1157
1158 }
1159
1160 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001161 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001162 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001163 }
1164 return Incompatible;
1165}
1166
Chris Lattner005ed752008-01-04 18:04:52 +00001167Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001168Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001169 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1170 // a null pointer constant.
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001171 if ((lhsType->isPointerType() || lhsType->isObjcQualifiedIdType())
1172 && rExpr->isNullPointerConstant(Context)) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001173 promoteExprToType(rExpr, lhsType);
1174 return Compatible;
1175 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001176 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001177 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001178 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001179 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001180 //
1181 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1182 // are better understood.
1183 if (!lhsType->isReferenceType())
1184 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001185
Chris Lattner005ed752008-01-04 18:04:52 +00001186 Sema::AssignConvertType result =
1187 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001188
1189 // C99 6.5.16.1p2: The value of the right operand is converted to the
1190 // type of the assignment expression.
1191 if (rExpr->getType() != lhsType)
1192 promoteExprToType(rExpr, lhsType);
1193 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001194}
1195
Chris Lattner005ed752008-01-04 18:04:52 +00001196Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001197Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1198 return CheckAssignmentConstraints(lhsType, rhsType);
1199}
1200
Chris Lattner2c8bff72007-12-12 05:47:28 +00001201QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001202 Diag(loc, diag::err_typecheck_invalid_operands,
1203 lex->getType().getAsString(), rex->getType().getAsString(),
1204 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001205 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001206}
1207
1208inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1209 Expr *&rex) {
1210 QualType lhsType = lex->getType(), rhsType = rex->getType();
1211
1212 // make sure the vector types are identical.
1213 if (lhsType == rhsType)
1214 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001215
1216 // if the lhs is an ocu vector and the rhs is a scalar of the same type,
1217 // promote the rhs to the vector type.
1218 if (const OCUVectorType *V = lhsType->getAsOCUVectorType()) {
1219 if (V->getElementType().getCanonicalType().getTypePtr()
1220 == rhsType.getCanonicalType().getTypePtr()) {
1221 promoteExprToType(rex, lhsType);
1222 return lhsType;
1223 }
1224 }
1225
1226 // if the rhs is an ocu vector and the lhs is a scalar of the same type,
1227 // promote the lhs to the vector type.
1228 if (const OCUVectorType *V = rhsType->getAsOCUVectorType()) {
1229 if (V->getElementType().getCanonicalType().getTypePtr()
1230 == lhsType.getCanonicalType().getTypePtr()) {
1231 promoteExprToType(lex, rhsType);
1232 return rhsType;
1233 }
1234 }
1235
Chris Lattner4b009652007-07-25 00:24:17 +00001236 // You cannot convert between vector values of different size.
1237 Diag(loc, diag::err_typecheck_vector_not_convertable,
1238 lex->getType().getAsString(), rex->getType().getAsString(),
1239 lex->getSourceRange(), rex->getSourceRange());
1240 return QualType();
1241}
1242
1243inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001244 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001245{
1246 QualType lhsType = lex->getType(), rhsType = rex->getType();
1247
1248 if (lhsType->isVectorType() || rhsType->isVectorType())
1249 return CheckVectorOperands(loc, lex, rex);
1250
Steve Naroff8f708362007-08-24 19:07:16 +00001251 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001252
Chris Lattner4b009652007-07-25 00:24:17 +00001253 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001254 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001255 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001256}
1257
1258inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001259 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001260{
1261 QualType lhsType = lex->getType(), rhsType = rex->getType();
1262
Steve Naroff8f708362007-08-24 19:07:16 +00001263 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001264
Chris Lattner4b009652007-07-25 00:24:17 +00001265 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001266 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001267 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001268}
1269
1270inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001271 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001272{
1273 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1274 return CheckVectorOperands(loc, lex, rex);
1275
Steve Naroff8f708362007-08-24 19:07:16 +00001276 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001277
1278 // handle the common case first (both operands are arithmetic).
1279 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001280 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001281
1282 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1283 return lex->getType();
1284 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1285 return rex->getType();
Chris Lattner2c8bff72007-12-12 05:47:28 +00001286 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001287}
1288
1289inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001290 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001291{
1292 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1293 return CheckVectorOperands(loc, lex, rex);
1294
Steve Naroff8f708362007-08-24 19:07:16 +00001295 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001296
Chris Lattnerf6da2912007-12-09 21:53:25 +00001297 // Enforce type constraints: C99 6.5.6p3.
1298
1299 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001300 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001301 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001302
1303 // Either ptr - int or ptr - ptr.
1304 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1305 // The LHS must be an object type, not incomplete, function, etc.
1306 if (!LHSPTy->getPointeeType()->isObjectType()) {
1307 // Handle the GNU void* extension.
1308 if (LHSPTy->getPointeeType()->isVoidType()) {
1309 Diag(loc, diag::ext_gnu_void_ptr,
1310 lex->getSourceRange(), rex->getSourceRange());
1311 } else {
1312 Diag(loc, diag::err_typecheck_sub_ptr_object,
1313 lex->getType().getAsString(), lex->getSourceRange());
1314 return QualType();
1315 }
1316 }
1317
1318 // The result type of a pointer-int computation is the pointer type.
1319 if (rex->getType()->isIntegerType())
1320 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001321
Chris Lattnerf6da2912007-12-09 21:53:25 +00001322 // Handle pointer-pointer subtractions.
1323 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1324 // RHS must be an object type, unless void (GNU).
1325 if (!RHSPTy->getPointeeType()->isObjectType()) {
1326 // Handle the GNU void* extension.
1327 if (RHSPTy->getPointeeType()->isVoidType()) {
1328 if (!LHSPTy->getPointeeType()->isVoidType())
1329 Diag(loc, diag::ext_gnu_void_ptr,
1330 lex->getSourceRange(), rex->getSourceRange());
1331 } else {
1332 Diag(loc, diag::err_typecheck_sub_ptr_object,
1333 rex->getType().getAsString(), rex->getSourceRange());
1334 return QualType();
1335 }
1336 }
1337
1338 // Pointee types must be compatible.
1339 if (!Context.typesAreCompatible(LHSPTy->getPointeeType(),
1340 RHSPTy->getPointeeType())) {
1341 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1342 lex->getType().getAsString(), rex->getType().getAsString(),
1343 lex->getSourceRange(), rex->getSourceRange());
1344 return QualType();
1345 }
1346
1347 return Context.getPointerDiffType();
1348 }
1349 }
1350
Chris Lattner2c8bff72007-12-12 05:47:28 +00001351 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001352}
1353
1354inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Chris Lattner2c8bff72007-12-12 05:47:28 +00001355 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1356 // C99 6.5.7p2: Each of the operands shall have integer type.
1357 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1358 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001359
Chris Lattner2c8bff72007-12-12 05:47:28 +00001360 // Shifts don't perform usual arithmetic conversions, they just do integer
1361 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001362 if (!isCompAssign)
1363 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001364 UsualUnaryConversions(rex);
1365
1366 // "The type of the result is that of the promoted left operand."
1367 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001368}
1369
Chris Lattner254f3bc2007-08-26 01:18:55 +00001370inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1371 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001372{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001373 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001374 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1375 UsualArithmeticConversions(lex, rex);
1376 else {
1377 UsualUnaryConversions(lex);
1378 UsualUnaryConversions(rex);
1379 }
Chris Lattner4b009652007-07-25 00:24:17 +00001380 QualType lType = lex->getType();
1381 QualType rType = rex->getType();
1382
Ted Kremenek486509e2007-10-29 17:13:39 +00001383 // For non-floating point types, check for self-comparisons of the form
1384 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1385 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001386 if (!lType->isFloatingType()) {
1387 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1388 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1389 if (DRL->getDecl() == DRR->getDecl())
1390 Diag(loc, diag::warn_selfcomparison);
1391 }
1392
Chris Lattner254f3bc2007-08-26 01:18:55 +00001393 if (isRelational) {
1394 if (lType->isRealType() && rType->isRealType())
1395 return Context.IntTy;
1396 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001397 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001398 if (lType->isFloatingType()) {
1399 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001400 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001401 }
1402
Chris Lattner254f3bc2007-08-26 01:18:55 +00001403 if (lType->isArithmeticType() && rType->isArithmeticType())
1404 return Context.IntTy;
1405 }
Chris Lattner4b009652007-07-25 00:24:17 +00001406
Chris Lattner22be8422007-08-26 01:10:14 +00001407 bool LHSIsNull = lex->isNullPointerConstant(Context);
1408 bool RHSIsNull = rex->isNullPointerConstant(Context);
1409
Chris Lattner254f3bc2007-08-26 01:18:55 +00001410 // All of the following pointer related warnings are GCC extensions, except
1411 // when handling null pointer constants. One day, we can consider making them
1412 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001413 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff3b435622007-11-13 14:57:38 +00001414
1415 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1416 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1417 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroff85f0dc52007-10-15 20:41:53 +00001418 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1419 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001420 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1421 lType.getAsString(), rType.getAsString(),
1422 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001423 }
Chris Lattner22be8422007-08-26 01:10:14 +00001424 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001425 return Context.IntTy;
1426 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001427 if ((lType->isObjcQualifiedIdType() || rType->isObjcQualifiedIdType())
Fariborz Jahaniancd71bf42007-12-21 00:33:59 +00001428 && Context.ObjcQualifiedIdTypesAreCompatible(lType, rType, true)) {
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001429 promoteExprToType(rex, lType);
1430 return Context.IntTy;
1431 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001432 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001433 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001434 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1435 lType.getAsString(), rType.getAsString(),
1436 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001437 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001438 return Context.IntTy;
1439 }
1440 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001441 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001442 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1443 lType.getAsString(), rType.getAsString(),
1444 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001445 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001446 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001447 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001448 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001449}
1450
Chris Lattner4b009652007-07-25 00:24:17 +00001451inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001452 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001453{
1454 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1455 return CheckVectorOperands(loc, lex, rex);
1456
Steve Naroff8f708362007-08-24 19:07:16 +00001457 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001458
1459 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001460 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001461 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001462}
1463
1464inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1465 Expr *&lex, Expr *&rex, SourceLocation loc)
1466{
1467 UsualUnaryConversions(lex);
1468 UsualUnaryConversions(rex);
1469
1470 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1471 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001472 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001473}
1474
1475inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001476 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001477{
1478 QualType lhsType = lex->getType();
1479 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner4b009652007-07-25 00:24:17 +00001480 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1481
1482 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001483 case Expr::MLV_Valid:
1484 break;
1485 case Expr::MLV_ConstQualified:
1486 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1487 return QualType();
1488 case Expr::MLV_ArrayType:
1489 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1490 lhsType.getAsString(), lex->getSourceRange());
1491 return QualType();
1492 case Expr::MLV_NotObjectType:
1493 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1494 lhsType.getAsString(), lex->getSourceRange());
1495 return QualType();
1496 case Expr::MLV_InvalidExpression:
1497 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1498 lex->getSourceRange());
1499 return QualType();
1500 case Expr::MLV_IncompleteType:
1501 case Expr::MLV_IncompleteVoidType:
1502 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1503 lhsType.getAsString(), lex->getSourceRange());
1504 return QualType();
1505 case Expr::MLV_DuplicateVectorComponents:
1506 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1507 lex->getSourceRange());
1508 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001509 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001510
Chris Lattner005ed752008-01-04 18:04:52 +00001511 AssignConvertType ConvTy;
1512 if (compoundType.isNull())
1513 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1514 else
1515 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1516
1517 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1518 rex, "assigning"))
1519 return QualType();
1520
Chris Lattner4b009652007-07-25 00:24:17 +00001521 // C99 6.5.16p3: The type of an assignment expression is the type of the
1522 // left operand unless the left operand has qualified type, in which case
1523 // it is the unqualified version of the type of the left operand.
1524 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1525 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001526 // C++ 5.17p1: the type of the assignment expression is that of its left
1527 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001528 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001529}
1530
1531inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1532 Expr *&lex, Expr *&rex, SourceLocation loc) {
1533 UsualUnaryConversions(rex);
1534 return rex->getType();
1535}
1536
1537/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1538/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1539QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1540 QualType resType = op->getType();
1541 assert(!resType.isNull() && "no type for increment/decrement expression");
1542
Steve Naroffd30e1932007-08-24 17:20:07 +00001543 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001544 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001545 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1546 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1547 resType.getAsString(), op->getSourceRange());
1548 return QualType();
1549 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001550 } else if (!resType->isRealType()) {
1551 if (resType->isComplexType())
1552 // C99 does not support ++/-- on complex types.
1553 Diag(OpLoc, diag::ext_integer_increment_complex,
1554 resType.getAsString(), op->getSourceRange());
1555 else {
1556 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1557 resType.getAsString(), op->getSourceRange());
1558 return QualType();
1559 }
Chris Lattner4b009652007-07-25 00:24:17 +00001560 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001561 // At this point, we know we have a real, complex or pointer type.
1562 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001563 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1564 if (mlval != Expr::MLV_Valid) {
1565 // FIXME: emit a more precise diagnostic...
1566 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1567 op->getSourceRange());
1568 return QualType();
1569 }
1570 return resType;
1571}
1572
1573/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1574/// This routine allows us to typecheck complex/recursive expressions
1575/// where the declaration is needed for type checking. Here are some
1576/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1577static Decl *getPrimaryDeclaration(Expr *e) {
1578 switch (e->getStmtClass()) {
1579 case Stmt::DeclRefExprClass:
1580 return cast<DeclRefExpr>(e)->getDecl();
1581 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001582 // Fields cannot be declared with a 'register' storage class.
1583 // &X->f is always ok, even if X is declared register.
1584 if (cast<MemberExpr>(e)->isArrow())
1585 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001586 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1587 case Stmt::ArraySubscriptExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001588 // &X[4] and &4[X] is invalid if X is invalid.
Chris Lattner4b009652007-07-25 00:24:17 +00001589 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +00001590 case Stmt::UnaryOperatorClass:
1591 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1592 case Stmt::ParenExprClass:
1593 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001594 case Stmt::ImplicitCastExprClass:
1595 // &X[4] when X is an array, has an implicit cast from array to pointer.
1596 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001597 default:
1598 return 0;
1599 }
1600}
1601
1602/// CheckAddressOfOperand - The operand of & must be either a function
1603/// designator or an lvalue designating an object. If it is an lvalue, the
1604/// object cannot be declared with storage class register or be a bit field.
1605/// Note: The usual conversions are *not* applied to the operand of the &
1606/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1607QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1608 Decl *dcl = getPrimaryDeclaration(op);
1609 Expr::isLvalueResult lval = op->isLvalue();
1610
1611 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001612 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1613 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001614 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1615 op->getSourceRange());
1616 return QualType();
1617 }
1618 } else if (dcl) {
1619 // We have an lvalue with a decl. Make sure the decl is not declared
1620 // with the register storage-class specifier.
1621 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1622 if (vd->getStorageClass() == VarDecl::Register) {
1623 Diag(OpLoc, diag::err_typecheck_address_of_register,
1624 op->getSourceRange());
1625 return QualType();
1626 }
1627 } else
1628 assert(0 && "Unknown/unexpected decl type");
1629
1630 // FIXME: add check for bitfields!
1631 }
1632 // If the operand has type "type", the result has type "pointer to type".
1633 return Context.getPointerType(op->getType());
1634}
1635
1636QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1637 UsualUnaryConversions(op);
1638 QualType qType = op->getType();
1639
Chris Lattner7931f4a2007-07-31 16:53:04 +00001640 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001641 QualType ptype = PT->getPointeeType();
1642 // C99 6.5.3.2p4. "if it points to an object,...".
1643 if (ptype->isIncompleteType()) { // An incomplete type is not an object
Chris Lattnerfabcc642008-01-06 22:21:46 +00001644 // GCC compat: special case 'void *' (treat as extension, not error).
Chris Lattner4b009652007-07-25 00:24:17 +00001645 if (ptype->isVoidType()) {
Chris Lattnerfabcc642008-01-06 22:21:46 +00001646 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001647 } else {
1648 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1649 ptype.getAsString(), op->getSourceRange());
1650 return QualType();
1651 }
1652 }
1653 return ptype;
1654 }
1655 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1656 qType.getAsString(), op->getSourceRange());
1657 return QualType();
1658}
1659
1660static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1661 tok::TokenKind Kind) {
1662 BinaryOperator::Opcode Opc;
1663 switch (Kind) {
1664 default: assert(0 && "Unknown binop!");
1665 case tok::star: Opc = BinaryOperator::Mul; break;
1666 case tok::slash: Opc = BinaryOperator::Div; break;
1667 case tok::percent: Opc = BinaryOperator::Rem; break;
1668 case tok::plus: Opc = BinaryOperator::Add; break;
1669 case tok::minus: Opc = BinaryOperator::Sub; break;
1670 case tok::lessless: Opc = BinaryOperator::Shl; break;
1671 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1672 case tok::lessequal: Opc = BinaryOperator::LE; break;
1673 case tok::less: Opc = BinaryOperator::LT; break;
1674 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1675 case tok::greater: Opc = BinaryOperator::GT; break;
1676 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1677 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1678 case tok::amp: Opc = BinaryOperator::And; break;
1679 case tok::caret: Opc = BinaryOperator::Xor; break;
1680 case tok::pipe: Opc = BinaryOperator::Or; break;
1681 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1682 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1683 case tok::equal: Opc = BinaryOperator::Assign; break;
1684 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1685 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1686 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1687 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1688 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1689 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1690 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1691 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1692 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1693 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1694 case tok::comma: Opc = BinaryOperator::Comma; break;
1695 }
1696 return Opc;
1697}
1698
1699static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1700 tok::TokenKind Kind) {
1701 UnaryOperator::Opcode Opc;
1702 switch (Kind) {
1703 default: assert(0 && "Unknown unary op!");
1704 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1705 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1706 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1707 case tok::star: Opc = UnaryOperator::Deref; break;
1708 case tok::plus: Opc = UnaryOperator::Plus; break;
1709 case tok::minus: Opc = UnaryOperator::Minus; break;
1710 case tok::tilde: Opc = UnaryOperator::Not; break;
1711 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1712 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1713 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1714 case tok::kw___real: Opc = UnaryOperator::Real; break;
1715 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1716 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1717 }
1718 return Opc;
1719}
1720
1721// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001722Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001723 ExprTy *LHS, ExprTy *RHS) {
1724 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1725 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1726
Steve Naroff87d58b42007-09-16 03:34:24 +00001727 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1728 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001729
1730 QualType ResultTy; // Result type of the binary operator.
1731 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1732
1733 switch (Opc) {
1734 default:
1735 assert(0 && "Unknown binary expr!");
1736 case BinaryOperator::Assign:
1737 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1738 break;
1739 case BinaryOperator::Mul:
1740 case BinaryOperator::Div:
1741 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1742 break;
1743 case BinaryOperator::Rem:
1744 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1745 break;
1746 case BinaryOperator::Add:
1747 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1748 break;
1749 case BinaryOperator::Sub:
1750 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1751 break;
1752 case BinaryOperator::Shl:
1753 case BinaryOperator::Shr:
1754 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1755 break;
1756 case BinaryOperator::LE:
1757 case BinaryOperator::LT:
1758 case BinaryOperator::GE:
1759 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001760 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001761 break;
1762 case BinaryOperator::EQ:
1763 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001764 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001765 break;
1766 case BinaryOperator::And:
1767 case BinaryOperator::Xor:
1768 case BinaryOperator::Or:
1769 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1770 break;
1771 case BinaryOperator::LAnd:
1772 case BinaryOperator::LOr:
1773 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1774 break;
1775 case BinaryOperator::MulAssign:
1776 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001777 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001778 if (!CompTy.isNull())
1779 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1780 break;
1781 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001782 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001783 if (!CompTy.isNull())
1784 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1785 break;
1786 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001787 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001788 if (!CompTy.isNull())
1789 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1790 break;
1791 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001792 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001793 if (!CompTy.isNull())
1794 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1795 break;
1796 case BinaryOperator::ShlAssign:
1797 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001798 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001799 if (!CompTy.isNull())
1800 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1801 break;
1802 case BinaryOperator::AndAssign:
1803 case BinaryOperator::XorAssign:
1804 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001805 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001806 if (!CompTy.isNull())
1807 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1808 break;
1809 case BinaryOperator::Comma:
1810 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1811 break;
1812 }
1813 if (ResultTy.isNull())
1814 return true;
1815 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001816 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001817 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001818 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001819}
1820
1821// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001822Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001823 ExprTy *input) {
1824 Expr *Input = (Expr*)input;
1825 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1826 QualType resultType;
1827 switch (Opc) {
1828 default:
1829 assert(0 && "Unimplemented unary expr!");
1830 case UnaryOperator::PreInc:
1831 case UnaryOperator::PreDec:
1832 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1833 break;
1834 case UnaryOperator::AddrOf:
1835 resultType = CheckAddressOfOperand(Input, OpLoc);
1836 break;
1837 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00001838 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00001839 resultType = CheckIndirectionOperand(Input, OpLoc);
1840 break;
1841 case UnaryOperator::Plus:
1842 case UnaryOperator::Minus:
1843 UsualUnaryConversions(Input);
1844 resultType = Input->getType();
1845 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1846 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1847 resultType.getAsString());
1848 break;
1849 case UnaryOperator::Not: // bitwise complement
1850 UsualUnaryConversions(Input);
1851 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001852 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1853 if (!resultType->isIntegerType()) {
1854 if (resultType->isComplexType())
1855 // C99 does not support '~' for complex conjugation.
1856 Diag(OpLoc, diag::ext_integer_complement_complex,
1857 resultType.getAsString());
1858 else
1859 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1860 resultType.getAsString());
1861 }
Chris Lattner4b009652007-07-25 00:24:17 +00001862 break;
1863 case UnaryOperator::LNot: // logical negation
1864 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1865 DefaultFunctionArrayConversion(Input);
1866 resultType = Input->getType();
1867 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1868 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1869 resultType.getAsString());
1870 // LNot always has type int. C99 6.5.3.3p5.
1871 resultType = Context.IntTy;
1872 break;
1873 case UnaryOperator::SizeOf:
1874 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1875 break;
1876 case UnaryOperator::AlignOf:
1877 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1878 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001879 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001880 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001881 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001882 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001883 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001884 resultType = Input->getType();
1885 break;
1886 }
1887 if (resultType.isNull())
1888 return true;
1889 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1890}
1891
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001892/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1893Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001894 SourceLocation LabLoc,
1895 IdentifierInfo *LabelII) {
1896 // Look up the record for this label identifier.
1897 LabelStmt *&LabelDecl = LabelMap[LabelII];
1898
1899 // If we haven't seen this label yet, create a forward reference.
1900 if (LabelDecl == 0)
1901 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1902
1903 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001904 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1905 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001906}
1907
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001908Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00001909 SourceLocation RPLoc) { // "({..})"
1910 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1911 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1912 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1913
1914 // FIXME: there are a variety of strange constraints to enforce here, for
1915 // example, it is not possible to goto into a stmt expression apparently.
1916 // More semantic analysis is needed.
1917
1918 // FIXME: the last statement in the compount stmt has its value used. We
1919 // should not warn about it being unused.
1920
1921 // If there are sub stmts in the compound stmt, take the type of the last one
1922 // as the type of the stmtexpr.
1923 QualType Ty = Context.VoidTy;
1924
1925 if (!Compound->body_empty())
1926 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1927 Ty = LastExpr->getType();
1928
1929 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1930}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001931
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001932Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001933 SourceLocation TypeLoc,
1934 TypeTy *argty,
1935 OffsetOfComponent *CompPtr,
1936 unsigned NumComponents,
1937 SourceLocation RPLoc) {
1938 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1939 assert(!ArgTy.isNull() && "Missing type argument!");
1940
1941 // We must have at least one component that refers to the type, and the first
1942 // one is known to be a field designator. Verify that the ArgTy represents
1943 // a struct/union/class.
1944 if (!ArgTy->isRecordType())
1945 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1946
1947 // Otherwise, create a compound literal expression as the base, and
1948 // iteratively process the offsetof designators.
Chris Lattner386ab8a2008-01-02 21:46:24 +00001949 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001950
Chris Lattnerb37522e2007-08-31 21:49:13 +00001951 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1952 // GCC extension, diagnose them.
1953 if (NumComponents != 1)
1954 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1955 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1956
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001957 for (unsigned i = 0; i != NumComponents; ++i) {
1958 const OffsetOfComponent &OC = CompPtr[i];
1959 if (OC.isBrackets) {
1960 // Offset of an array sub-field. TODO: Should we allow vector elements?
1961 const ArrayType *AT = Res->getType()->getAsArrayType();
1962 if (!AT) {
1963 delete Res;
1964 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1965 Res->getType().getAsString());
1966 }
1967
Chris Lattner2af6a802007-08-30 17:59:59 +00001968 // FIXME: C++: Verify that operator[] isn't overloaded.
1969
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001970 // C99 6.5.2.1p1
1971 Expr *Idx = static_cast<Expr*>(OC.U.E);
1972 if (!Idx->getType()->isIntegerType())
1973 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1974 Idx->getSourceRange());
1975
1976 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1977 continue;
1978 }
1979
1980 const RecordType *RC = Res->getType()->getAsRecordType();
1981 if (!RC) {
1982 delete Res;
1983 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1984 Res->getType().getAsString());
1985 }
1986
1987 // Get the decl corresponding to this.
1988 RecordDecl *RD = RC->getDecl();
1989 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1990 if (!MemberDecl)
1991 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1992 OC.U.IdentInfo->getName(),
1993 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00001994
1995 // FIXME: C++: Verify that MemberDecl isn't a static field.
1996 // FIXME: Verify that MemberDecl isn't a bitfield.
1997
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001998 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1999 }
2000
2001 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2002 BuiltinLoc);
2003}
2004
2005
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002006Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002007 TypeTy *arg1, TypeTy *arg2,
2008 SourceLocation RPLoc) {
2009 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2010 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2011
2012 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2013
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002014 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002015}
2016
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002017Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002018 ExprTy *expr1, ExprTy *expr2,
2019 SourceLocation RPLoc) {
2020 Expr *CondExpr = static_cast<Expr*>(cond);
2021 Expr *LHSExpr = static_cast<Expr*>(expr1);
2022 Expr *RHSExpr = static_cast<Expr*>(expr2);
2023
2024 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2025
2026 // The conditional expression is required to be a constant expression.
2027 llvm::APSInt condEval(32);
2028 SourceLocation ExpLoc;
2029 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2030 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2031 CondExpr->getSourceRange());
2032
2033 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2034 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2035 RHSExpr->getType();
2036 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2037}
2038
Anders Carlsson36760332007-10-15 20:28:48 +00002039Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2040 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002041 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002042 Expr *E = static_cast<Expr*>(expr);
2043 QualType T = QualType::getFromOpaquePtr(type);
2044
2045 InitBuiltinVaListType();
2046
Chris Lattner005ed752008-01-04 18:04:52 +00002047 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2048 != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002049 return Diag(E->getLocStart(),
2050 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2051 E->getType().getAsString(),
2052 E->getSourceRange());
2053
2054 // FIXME: Warn if a non-POD type is passed in.
2055
2056 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2057}
2058
Chris Lattner005ed752008-01-04 18:04:52 +00002059bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2060 SourceLocation Loc,
2061 QualType DstType, QualType SrcType,
2062 Expr *SrcExpr, const char *Flavor) {
2063 // Decode the result (notice that AST's are still created for extensions).
2064 bool isInvalid = false;
2065 unsigned DiagKind;
2066 switch (ConvTy) {
2067 default: assert(0 && "Unknown conversion type");
2068 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002069 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002070 DiagKind = diag::ext_typecheck_convert_pointer_int;
2071 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002072 case IntToPointer:
2073 DiagKind = diag::ext_typecheck_convert_int_pointer;
2074 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002075 case IncompatiblePointer:
2076 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2077 break;
2078 case FunctionVoidPointer:
2079 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2080 break;
2081 case CompatiblePointerDiscardsQualifiers:
2082 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2083 break;
2084 case Incompatible:
2085 DiagKind = diag::err_typecheck_convert_incompatible;
2086 isInvalid = true;
2087 break;
2088 }
2089
2090 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2091 SrcExpr->getSourceRange());
2092 return isInvalid;
2093}
2094