blob: bf96712aad1fe6911859af9275d0ae4433ca6190 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Ted Kremenek588e5eb2007-11-25 00:58:00 +000015#include "SemaUtil.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/Expr.h"
Steve Naroff563477d2007-09-18 23:55:05 +000018#include "clang/Parse/DeclSpec.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Chris Lattner925e60d2007-12-28 05:29:59 +000023#include "llvm/ADT/OwningPtr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "llvm/ADT/SmallString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000025#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27
Steve Narofff69936d2007-09-16 03:34:24 +000028/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofff69936d2007-09-16 03:34:24 +000035Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Carlssonee98ac52007-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()));
Reid Spencer5f016e22007-07-11 17:01:13 +000058
59 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
60 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlssonee98ac52007-10-15 02:50:23 +000061 Literal.AnyWide, t,
62 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +000063 StringToks[NumStringToks-1].getLocation());
64}
65
66
Steve Naroff08d92e42007-09-15 18:49:24 +000067/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +000068/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
69/// identifier is used in an function call context.
Steve Naroff08d92e42007-09-15 18:49:24 +000070Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +000071 IdentifierInfo &II,
72 bool HasTrailingLParen) {
73 // Could be enum-constant or decl.
Steve Naroff8c9f13e2007-09-16 16:16:00 +000074 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff7779db42007-11-12 14:29:37 +000083 if (CurMethodDecl) {
84 ObjcInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
85 ObjcInterfaceDecl *clsDeclared;
Steve Naroff7e3411b2007-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 Naroff7779db42007-11-12 14:29:37 +000092 }
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroffe1223f72007-08-28 03:03:08 +000098 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroff53a32342007-08-28 18:45:29 +000099 // Only create DeclRefExpr's for valid Decl's.
Steve Naroff5912a352007-08-28 20:14:24 +0000100 if (VD->isInvalidDecl())
Steve Naroffe1223f72007-08-28 03:03:08 +0000101 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroffe1223f72007-08-28 03:03:08 +0000103 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000104 if (isa<TypedefDecl>(D))
105 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Fariborz Jahanian5ef404f2007-12-05 18:16:33 +0000106 if (isa<ObjcInterfaceDecl>(D))
107 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000108
109 assert(0 && "Invalid decl");
Chris Lattnereddbe032007-07-21 04:57:45 +0000110 abort();
Reid Spencer5f016e22007-07-11 17:01:13 +0000111}
112
Steve Narofff69936d2007-09-16 03:34:24 +0000113Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000114 tok::TokenKind Kind) {
115 PreDefinedExpr::IdentType IT;
116
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 switch (Kind) {
118 default:
119 assert(0 && "Unknown simple primary expr!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
Anders Carlsson22742662007-07-21 05:21:51 +0000121 IT = PreDefinedExpr::Func;
122 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000124 IT = PreDefinedExpr::Function;
125 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000126 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000127 IT = PreDefinedExpr::PrettyFunction;
128 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000129 }
Anders Carlsson22742662007-07-21 05:21:51 +0000130
131 // Pre-defined identifiers are always of type char *.
132 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000133}
134
Steve Narofff69936d2007-09-16 03:34:24 +0000135Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofff69936d2007-09-16 03:34:24 +0000149Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner701e5eb2007-09-04 02:45:27 +0000155 unsigned IntSize = static_cast<unsigned>(
156 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner5d661452007-08-26 03:42:43 +0000172 Expr *Res;
173
174 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-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 Kremenek9c728dc2007-12-12 22:39:36 +0000181 Context.Target.getFloatInfo(Size, Align, Format,
182 Context.getFullLoc(Tok.getLocation()));
183
Chris Lattner525a0502007-09-22 18:29:59 +0000184 } else if (Literal.isLong) {
185 Ty = Context.LongDoubleTy;
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000186 Context.Target.getLongDoubleInfo(Size, Align, Format,
187 Context.getFullLoc(Tok.getLocation()));
Chris Lattner525a0502007-09-22 18:29:59 +0000188 } else {
189 Ty = Context.DoubleTy;
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000190 Context.Target.getDoubleInfo(Size, Align, Format,
191 Context.getFullLoc(Tok.getLocation()));
Chris Lattner525a0502007-09-22 18:29:59 +0000192 }
193
Ted Kremenek720c4ec2007-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 Lattner5d661452007-08-26 03:42:43 +0000200 } else if (!Literal.isIntegerLiteral()) {
201 return ExprResult(true);
202 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000203 QualType t;
204
Neil Boothb9449512007-08-29 22:00:19 +0000205 // long long is a C99 feature.
206 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000207 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000208 Diag(Tok.getLocation(), diag::ext_longlong);
209
Reid Spencer5f016e22007-07-11 17:01:13 +0000210 // Get the value in the widest-possible width.
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000211 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(
212 Context.getFullLoc(Tok.getLocation())), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +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;
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000218 assert(Context.getTypeSize(t, Tok.getLocation()) ==
Reid Spencer5f016e22007-07-11 17:01:13 +0000219 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 Lattner97c51562007-08-23 21:58:08 +0000229 if (!Literal.isLong && !Literal.isLongLong) {
230 // Are int/unsigned possibilities?
Chris Lattner701e5eb2007-09-04 02:45:27 +0000231 unsigned IntSize = static_cast<unsigned>(
232 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner701e5eb2007-09-04 02:45:27 +0000248 unsigned LongSize = static_cast<unsigned>(
249 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner701e5eb2007-09-04 02:45:27 +0000265 unsigned LongLongSize = static_cast<unsigned>(
266 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner5d661452007-08-26 03:42:43 +0000286 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000287 }
Chris Lattner5d661452007-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;
Reid Spencer5f016e22007-07-11 17:01:13 +0000294}
295
Steve Narofff69936d2007-09-16 03:34:24 +0000296Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 ExprTy *Val) {
298 Expr *e = (Expr *)Val;
Steve Narofff69936d2007-09-16 03:34:24 +0000299 assert((e != 0) && "ActOnParenExpr() missing expr");
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofff69936d2007-09-16 03:34:24 +0000324ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner5d794252007-08-24 21:41:10 +0000340QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000341 DefaultFunctionArrayConversion(V);
342
Chris Lattnercc26ed72007-08-26 05:39:26 +0000343 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000344 if (const ComplexType *CT = V->getType()->getAsComplexType())
345 return CT->getElementType();
Chris Lattnercc26ed72007-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 Lattnerdbb36972007-08-24 21:16:53 +0000354}
355
356
Reid Spencer5f016e22007-07-11 17:01:13 +0000357
Steve Narofff69936d2007-09-16 03:34:24 +0000358Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofff69936d2007-09-16 03:34:24 +0000374ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000376 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000377
378 // Perform default conversions.
379 DefaultFunctionArrayConversion(LHSExp);
380 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000381
Chris Lattner12d9ff62007-07-16 00:14:47 +0000382 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000383
Reid Spencer5f016e22007-07-11 17:01:13 +0000384 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000385 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 // in the subscript position. As a result, we need to derive the array base
387 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000388 Expr *BaseExpr, *IndexExpr;
389 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000390 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000391 BaseExpr = LHSExp;
392 IndexExpr = RHSExp;
393 // FIXME: need to deal with const...
394 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000395 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000396 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000397 BaseExpr = RHSExp;
398 IndexExpr = LHSExp;
399 // FIXME: need to deal with const...
400 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000401 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
402 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000403 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-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 Lattner12d9ff62007-07-16 00:14:47 +0000409 // FIXME: need to deal with const...
410 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000412 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
413 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 }
415 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000416 if (!IndexExpr->getType()->isIntegerType())
417 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
418 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000419
Chris Lattner12d9ff62007-07-16 00:14:47 +0000420 // 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);
Reid Spencer5f016e22007-07-11 17:01:13 +0000429}
430
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000431QualType Sema::
432CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
433 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnerc8629632007-07-31 19:29:30 +0000434 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroffe1b31fe2007-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 Lattner88dca042007-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 Naroffe1b31fe2007-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 Naroffbea0b342007-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 Naroffe1b31fe2007-07-27 22:15:19 +0000495}
496
Reid Spencer5f016e22007-07-11 17:01:13 +0000497Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000498ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000499 tok::TokenKind OpKind, SourceLocation MemberLoc,
500 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000501 Expr *BaseExpr = static_cast<Expr *>(Base);
502 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +0000503
504 // Perform default conversions.
505 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000506
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000507 QualType BaseType = BaseExpr->getType();
508 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000509
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000511 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000512 BaseType = PT->getPointeeType();
513 else
514 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
515 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000516 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000517 // The base type is either a record or an OCUVectorType.
Chris Lattnerc8629632007-07-31 19:29:30 +0000518 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-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 Naroffe1b31fe2007-07-27 22:15:19 +0000524 FieldDecl *MemberDecl = RDecl->getMember(&Member);
525 if (!MemberDecl)
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000526 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
527 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000528 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
529 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff608e0ee2007-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 Naroffe1b31fe2007-07-27 22:15:19 +0000534 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
535 if (ret.isNull())
536 return true;
Chris Lattner6481a572007-08-03 17:31:20 +0000537 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Fariborz Jahanian232220c2007-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 Jahanian06cef252007-12-13 20:47:42 +0000543 IFace = dyn_cast<ObjcQualifiedInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian232220c2007-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));
Reid Spencer5f016e22007-07-11 17:01:13 +0000551}
552
Steve Narofff69936d2007-09-16 03:34:24 +0000553/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +0000554/// This provides the location of the left/right parens and a list of comma
555/// locations.
556Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000557ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +0000558 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000560 Expr *Fn = static_cast<Expr *>(fn);
561 Expr **Args = reinterpret_cast<Expr**>(args);
562 assert(Fn && "no function call expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000563
Chris Lattner925e60d2007-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
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
573 // type pointer to function".
Chris Lattner925e60d2007-12-28 05:29:59 +0000574 const PointerType *PT = Fn->getType()->getAsPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000575 if (PT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000576 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
577 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner925e60d2007-12-28 05:29:59 +0000578 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
579 if (FuncT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000580 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
581 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner925e60d2007-12-28 05:29:59 +0000582
583 // We know the result type of the call, set it.
584 TheCall->setType(FuncT->getResultType());
Reid Spencer5f016e22007-07-11 17:01:13 +0000585
Chris Lattner925e60d2007-12-28 05:29:59 +0000586 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000587 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
588 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +0000589 unsigned NumArgsInProto = Proto->getNumArgs();
590 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000591
Chris Lattner925e60d2007-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());
Reid Spencer5f016e22007-07-11 17:01:13 +0000596
Chris Lattner925e60d2007-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 Lattnerd472b312007-07-21 03:09:58 +0000601 Diag(Args[NumArgsInProto]->getLocStart(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000602 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +0000603 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner925e60d2007-12-28 05:29:59 +0000604 Args[NumArgs-1]->getLocEnd()));
605 // This deletes the extra arguments.
606 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +0000607 }
608 NumArgsToCheck = NumArgsInProto;
609 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000610
Reid Spencer5f016e22007-07-11 17:01:13 +0000611 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +0000612 for (unsigned i = 0; i != NumArgsToCheck; i++) {
613 Expr *Arg = Args[i];
Chris Lattner5cf216b2008-01-04 18:04:52 +0000614 QualType ProtoArgType = Proto->getArgType(i);
615 QualType ArgType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +0000616
Chris Lattner925e60d2007-12-28 05:29:59 +0000617 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000618 AssignConvertType ConvTy =
619 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner925e60d2007-12-28 05:29:59 +0000620 TheCall->setArg(i, Arg);
621
Chris Lattner5cf216b2008-01-04 18:04:52 +0000622 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
623 ArgType, Arg, "passing"))
624 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000625 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000626
627 // If this is a variadic call, handle args passed through "...".
628 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +0000629 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-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 Naroffb291ab62007-08-28 23:30:39 +0000634 }
Steve Naroffb291ab62007-08-28 23:30:39 +0000635 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000636 } else {
637 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
638
Steve Naroffb291ab62007-08-28 23:30:39 +0000639 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-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 Naroffb291ab62007-08-28 23:30:39 +0000644 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000646
Chris Lattner59907c42007-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 Lattner925e60d2007-12-28 05:29:59 +0000651 if (CheckFunctionCall(FDecl, TheCall.get()))
Anders Carlsson71993dd2007-08-17 05:31:46 +0000652 return true;
Chris Lattner59907c42007-08-10 20:18:51 +0000653
Chris Lattner925e60d2007-12-28 05:29:59 +0000654 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +0000655}
656
657Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000658ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +0000659 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +0000660 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +0000661 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +0000662 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +0000663 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +0000664 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +0000665
Steve Naroff2fdc3742007-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 Carlssond35c8322007-12-05 07:24:19 +0000669
Chris Lattner0fc53df2008-01-02 21:46:24 +0000670 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000671}
672
673Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000674ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000675 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +0000676 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000677
Steve Naroff08d92e42007-09-15 18:49:24 +0000678 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +0000679 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000680
Steve Naroff38374b02007-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;
Steve Naroff4aa88f82007-07-19 01:06:55 +0000684}
685
Chris Lattnerfe23e212007-12-20 00:44:32 +0000686bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-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
Steve Naroff4aa88f82007-07-19 01:06:55 +0000707Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000708ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +0000710 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +0000711
712 Expr *castExpr = static_cast<Expr*>(Op);
713 QualType castType = QualType::getFromOpaquePtr(Ty);
714
Steve Naroff711602b2007-08-31 00:32:44 +0000715 UsualUnaryConversions(castExpr);
716
Chris Lattner75af4802007-07-18 16:00:06 +0000717 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
718 // type needs to be scalar.
Chris Lattner3da2db42007-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 Carlssona64db8f2007-11-27 05:51:55 +0000723 if (!castExpr->getType()->isScalarType())
Chris Lattner3da2db42007-10-29 04:26:44 +0000724 return Diag(castExpr->getLocStart(),
725 diag::err_typecheck_expect_scalar_operand,
726 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssona64db8f2007-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 Lattner3da2db42007-10-29 04:26:44 +0000736 }
Steve Naroff16beff82007-07-16 23:25:18 +0000737 }
738 return new CastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000739}
740
Steve Naroffd4dd30f2007-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 Lattnera21ddb32007-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.
Reid Spencer5f016e22007-07-11 17:01:13 +0000753inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +0000754 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000755 UsualUnaryConversions(cond);
756 UsualUnaryConversions(lex);
757 UsualUnaryConversions(rex);
758 QualType condT = cond->getType();
759 QualType lexT = lex->getType();
760 QualType rexT = rex->getType();
761
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +0000763 if (!condT->isScalarType()) { // C99 6.5.15p2
764 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
765 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +0000766 return QualType();
767 }
768 // now check the two expressions.
Steve Naroffa4332e22007-07-17 00:58:39 +0000769 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
770 UsualArithmeticConversions(lex, rex);
771 return lex->getType();
772 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000773 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
774 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
Chris Lattnera21ddb32007-11-26 01:40:58 +0000775 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000776 return lexT;
777
Reid Spencer5f016e22007-07-11 17:01:13 +0000778 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000779 lexT.getAsString(), rexT.getAsString(),
780 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000781 return QualType();
782 }
783 }
Chris Lattner590b6642007-07-15 23:26:56 +0000784 // C99 6.5.15p3
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000785 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
786 promoteExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff49b45262007-07-13 16:58:59 +0000787 return lexT;
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000788 }
789 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
790 promoteExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff49b45262007-07-13 16:58:59 +0000791 return rexT;
Steve Naroffd4dd30f2007-10-18 05:13:08 +0000792 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000793 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
794 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
795 // get the "pointed to" types
796 QualType lhptee = LHSPT->getPointeeType();
797 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000798
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000799 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
800 if (lhptee->isVoidType() &&
801 (rhptee->isObjectType() || rhptee->isIncompleteType()))
802 return lexT;
803 if (rhptee->isVoidType() &&
804 (lhptee->isObjectType() || lhptee->isIncompleteType()))
805 return rexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000806
Steve Naroffec0550f2007-10-15 20:41:53 +0000807 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
808 rhptee.getUnqualifiedType())) {
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000809 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
810 lexT.getAsString(), rexT.getAsString(),
811 lex->getSourceRange(), rex->getSourceRange());
812 return lexT; // FIXME: this is an _ext - is this return o.k?
813 }
814 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000815 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
816 // differently qualified versions of compatible types, the result type is
817 // a pointer to an appropriately qualified version of the *composite*
818 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000819 return lexT; // FIXME: Need to return the composite type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000820 }
821 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000822
Steve Naroff49b45262007-07-13 16:58:59 +0000823 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
824 return lexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000825
826 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000827 lexT.getAsString(), rexT.getAsString(),
828 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000829 return QualType();
830}
831
Steve Narofff69936d2007-09-16 03:34:24 +0000832/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +0000833/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +0000834Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000835 SourceLocation ColonLoc,
836 ExprTy *Cond, ExprTy *LHS,
837 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +0000838 Expr *CondExpr = (Expr *) Cond;
839 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +0000840
841 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
842 // was the condition.
843 bool isLHSNull = LHSExpr == 0;
844 if (isLHSNull)
845 LHSExpr = CondExpr;
846
Chris Lattner26824902007-07-16 21:39:03 +0000847 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
848 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000849 if (result.isNull())
850 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +0000851 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
852 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000853}
854
Steve Naroffb291ab62007-08-28 23:30:39 +0000855/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
856/// do not have a prototype. Integer promotions are performed on each
857/// argument, and arguments that have type float are promoted to double.
Chris Lattner925e60d2007-12-28 05:29:59 +0000858void Sema::DefaultArgumentPromotion(Expr *&Expr) {
859 QualType Ty = Expr->getType();
860 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffb291ab62007-08-28 23:30:39 +0000861
Chris Lattner925e60d2007-12-28 05:29:59 +0000862 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
863 promoteExprToType(Expr, Context.IntTy);
864 if (Ty == Context.FloatTy)
865 promoteExprToType(Expr, Context.DoubleTy);
Steve Naroffb291ab62007-08-28 23:30:39 +0000866}
867
Steve Narofffa2eaab2007-07-15 02:02:06 +0000868/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000869void Sema::DefaultFunctionArrayConversion(Expr *&e) {
Steve Narofffa2eaab2007-07-15 02:02:06 +0000870 QualType t = e->getType();
Steve Naroff90045e82007-07-13 23:32:42 +0000871 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
Bill Wendling08ad47c2007-07-17 03:52:31 +0000872
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000873 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000874 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
875 t = e->getType();
876 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000877 if (t->isFunctionType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000878 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnerc8629632007-07-31 19:29:30 +0000879 else if (const ArrayType *ary = t->getAsArrayType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000880 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000881}
882
883/// UsualUnaryConversion - Performs various conversions that are common to most
884/// operators (C99 6.3). The conversions of array and function types are
885/// sometimes surpressed. For example, the array->pointer conversion doesn't
886/// apply if the array is an argument to the sizeof or address (&) operators.
887/// In these instances, this routine should *not* be called.
Chris Lattner925e60d2007-12-28 05:29:59 +0000888Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
889 QualType Ty = Expr->getType();
890 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000891
Chris Lattner925e60d2007-12-28 05:29:59 +0000892 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
893 promoteExprToType(Expr, Ref->getReferenceeType()); // C++ [expr]
894 Ty = Expr->getType();
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000895 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000896 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
897 promoteExprToType(Expr, Context.IntTy);
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000898 else
Chris Lattner925e60d2007-12-28 05:29:59 +0000899 DefaultFunctionArrayConversion(Expr);
900
901 return Expr;
Reid Spencer5f016e22007-07-11 17:01:13 +0000902}
903
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000904/// UsualArithmeticConversions - Performs various conversions that are common to
Reid Spencer5f016e22007-07-11 17:01:13 +0000905/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
906/// routine returns the first non-arithmetic type found. The client is
907/// responsible for emitting appropriate error diagnostics.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000908QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
909 bool isCompAssign) {
Steve Naroff8702a0f2007-08-25 19:54:59 +0000910 if (!isCompAssign) {
911 UsualUnaryConversions(lhsExpr);
912 UsualUnaryConversions(rhsExpr);
913 }
Steve Naroff3187e202007-10-18 18:55:53 +0000914 // For conversion purposes, we ignore any qualifiers.
915 // For example, "const float" and "float" are equivalent.
Steve Narofff68a63f2007-11-10 19:45:54 +0000916 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
917 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000918
919 // If both types are identical, no conversion is needed.
Steve Naroff3187e202007-10-18 18:55:53 +0000920 if (lhs == rhs)
921 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000922
923 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
924 // The caller can deal with this (e.g. pointer + int).
Steve Naroffa4332e22007-07-17 00:58:39 +0000925 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000926 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000927
928 // At this point, we have two different arithmetic types.
929
930 // Handle complex types first (C99 6.3.1.8p1).
931 if (lhs->isComplexType() || rhs->isComplexType()) {
932 // if we have an integer operand, the result is the complex type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000933 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000934 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
935 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000936 }
937 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000938 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
939 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000940 }
Steve Narofff1448a02007-08-27 01:27:54 +0000941 // This handles complex/complex, complex/float, or float/complex.
942 // When both operands are complex, the shorter operand is converted to the
943 // type of the longer, and that is the type of the result. This corresponds
944 // to what is done when combining two real floating-point operands.
945 // The fun begins when size promotion occur across type domains.
946 // From H&S 6.3.4: When one operand is complex and the other is a real
947 // floating-point type, the less precise type is converted, within it's
948 // real or complex domain, to the precision of the other type. For example,
949 // when combining a "long double" with a "double _Complex", the
950 // "double _Complex" is promoted to "long double _Complex".
Steve Narofffb0d4962007-08-27 15:30:22 +0000951 int result = Context.compareFloatingType(lhs, rhs);
952
953 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff55fe4552007-08-27 21:32:55 +0000954 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
955 if (!isCompAssign)
956 promoteExprToType(rhsExpr, rhs);
957 } else if (result < 0) { // The right side is bigger, convert lhs.
958 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
959 if (!isCompAssign)
960 promoteExprToType(lhsExpr, lhs);
961 }
962 // At this point, lhs and rhs have the same rank/size. Now, make sure the
963 // domains match. This is a requirement for our implementation, C99
964 // does not require this promotion.
965 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
966 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff29960362007-08-27 21:43:43 +0000967 if (!isCompAssign)
968 promoteExprToType(lhsExpr, rhs);
969 return rhs;
Steve Naroff55fe4552007-08-27 21:32:55 +0000970 } else { // handle "_Complex double, double".
Steve Naroff29960362007-08-27 21:43:43 +0000971 if (!isCompAssign)
972 promoteExprToType(rhsExpr, lhs);
973 return lhs;
Steve Naroff55fe4552007-08-27 21:32:55 +0000974 }
Steve Naroffa4332e22007-07-17 00:58:39 +0000975 }
Steve Naroff29960362007-08-27 21:43:43 +0000976 return lhs; // The domain/size match exactly.
Reid Spencer5f016e22007-07-11 17:01:13 +0000977 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000978 // Now handle "real" floating types (i.e. float, double, long double).
979 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
980 // if we have an integer operand, the result is the real floating type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000981 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000982 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
983 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000984 }
985 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000986 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
987 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000988 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000989 // We have two real floating types, float/complex combos were handled above.
990 // Convert the smaller operand to the bigger result.
Steve Narofffb0d4962007-08-27 15:30:22 +0000991 int result = Context.compareFloatingType(lhs, rhs);
992
993 if (result > 0) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000994 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
995 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000996 }
Steve Narofffb0d4962007-08-27 15:30:22 +0000997 if (result < 0) { // convert the lhs
998 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
999 return rhs;
1000 }
1001 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Reid Spencer5f016e22007-07-11 17:01:13 +00001002 }
Steve Narofffa2eaab2007-07-15 02:02:06 +00001003 // Finally, we have two differing integer types.
Steve Naroffa4332e22007-07-17 00:58:39 +00001004 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001005 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1006 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001007 }
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001008 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1009 return rhs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001010}
1011
1012// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1013// being closely modeled after the C99 spec:-). The odd characteristic of this
1014// routine is it effectively iqnores the qualifiers on the top level pointee.
1015// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1016// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001017Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001018Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1019 QualType lhptee, rhptee;
1020
1021 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001022 lhptee = lhsType->getAsPointerType()->getPointeeType();
1023 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001024
1025 // make sure we operate on the canonical type
1026 lhptee = lhptee.getCanonicalType();
1027 rhptee = rhptee.getCanonicalType();
1028
Chris Lattner5cf216b2008-01-04 18:04:52 +00001029 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001030
1031 // C99 6.5.16.1p1: This following citation is common to constraints
1032 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1033 // qualifiers of the type *pointed to* by the right;
1034 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1035 rhptee.getQualifiers())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001036 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001037
1038 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1039 // incomplete type and the other is a pointer to a qualified or unqualified
1040 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001041 if (lhptee->isVoidType()) {
1042 if (rhptee->isObjectType() || rhptee->isIncompleteType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001043 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001044
1045 // As an extension, we allow cast to/from void* to function pointer.
1046 if (rhptee->isFunctionType())
1047 return FunctionVoidPointer;
1048 }
1049
1050 if (rhptee->isVoidType()) {
1051 if (lhptee->isObjectType() || lhptee->isIncompleteType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001052 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001053
1054 // As an extension, we allow cast to/from void* to function pointer.
1055 if (lhptee->isFunctionType())
1056 return FunctionVoidPointer;
1057 }
1058
Reid Spencer5f016e22007-07-11 17:01:13 +00001059 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1060 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001061 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1062 rhptee.getUnqualifiedType()))
1063 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00001064 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001065}
1066
1067/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1068/// has code to accommodate several GCC extensions when type checking
1069/// pointers. Here are some objectionable examples that GCC considers warnings:
1070///
1071/// int a, *pint;
1072/// short *pshort;
1073/// struct foo *pfoo;
1074///
1075/// pint = pshort; // warning: assignment from incompatible pointer type
1076/// a = pint; // warning: assignment makes integer from pointer without a cast
1077/// pint = a; // warning: assignment makes pointer from integer without a cast
1078/// pint = pfoo; // warning: assignment from incompatible pointer type
1079///
1080/// As a result, the code for dealing with pointers is more complex than the
1081/// C99 spec dictates.
1082/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1083///
Chris Lattner5cf216b2008-01-04 18:04:52 +00001084Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001085Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Steve Naroff8eabdff2007-11-13 00:31:42 +00001086 if (lhsType.getCanonicalType().getUnqualifiedType() ==
1087 rhsType.getCanonicalType().getUnqualifiedType())
Chris Lattner84d35ce2007-10-29 05:15:40 +00001088 return Compatible; // common case, fast path...
Steve Naroff700204c2007-07-24 21:46:40 +00001089
Anders Carlsson793680e2007-10-12 23:56:29 +00001090 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroffec0550f2007-10-15 20:41:53 +00001091 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001092 return Compatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001093 }
1094 else if (lhsType->isObjcQualifiedIdType()
1095 || rhsType->isObjcQualifiedIdType()) {
1096 if (Context.ObjcQualifiedIdTypesAreCompatible(lhsType, rhsType))
1097 return Compatible;
1098 }
1099 else if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001100 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman4119d1a2007-12-30 02:59:45 +00001101 // For OCUVector, allow vector splats; float -> <n x float>
1102 if (const OCUVectorType *LV = lhsType->getAsOCUVectorType()) {
1103 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1104 return Compatible;
1105 }
Anders Carlsson695dbb62007-11-30 04:21:22 +00001106 if (!getLangOptions().LaxVectorConversions) {
1107 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1108 return Incompatible;
1109 } else {
1110 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman4288c432007-12-30 01:45:55 +00001111 // If LHS and RHS are both integer or both floating point types, and
1112 // the total vector length is the same, allow the conversion. This is
1113 // a bitcast; no bits are changed but the result type is different.
Anders Carlsson695dbb62007-11-30 04:21:22 +00001114 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1115 (lhsType->isRealFloatingType() &&
1116 rhsType->isRealFloatingType())) {
1117 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1118 Context.getTypeSize(rhsType, SourceLocation()))
1119 return Compatible;
1120 }
1121 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001122 return Incompatible;
Anders Carlsson695dbb62007-11-30 04:21:22 +00001123 }
1124 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001125 return Compatible;
1126 } else if (lhsType->isPointerType()) {
1127 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001128 return IntToPointer;
Reid Spencer5f016e22007-07-11 17:01:13 +00001129
1130 if (rhsType->isPointerType())
1131 return CheckPointerTypesForAssignment(lhsType, rhsType);
1132 } else if (rhsType->isPointerType()) {
1133 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1134 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
Chris Lattnerb7b61152008-01-04 18:22:42 +00001135 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00001136
1137 if (lhsType->isPointerType())
1138 return CheckPointerTypesForAssignment(lhsType, rhsType);
1139 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroffec0550f2007-10-15 20:41:53 +00001140 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001142 }
1143 return Incompatible;
1144}
1145
Chris Lattner5cf216b2008-01-04 18:04:52 +00001146Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001147Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroff529a4ad2007-11-27 17:58:44 +00001148 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1149 // a null pointer constant.
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00001150 if ((lhsType->isPointerType() || lhsType->isObjcQualifiedIdType())
1151 && rExpr->isNullPointerConstant(Context)) {
Steve Naroff529a4ad2007-11-27 17:58:44 +00001152 promoteExprToType(rExpr, lhsType);
1153 return Compatible;
1154 }
Chris Lattner943140e2007-10-16 02:55:40 +00001155 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001156 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001157 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001158 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001159 //
1160 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1161 // are better understood.
1162 if (!lhsType->isReferenceType())
1163 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001164
Chris Lattner5cf216b2008-01-04 18:04:52 +00001165 Sema::AssignConvertType result =
1166 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00001167
1168 // C99 6.5.16.1p2: The value of the right operand is converted to the
1169 // type of the assignment expression.
1170 if (rExpr->getType() != lhsType)
1171 promoteExprToType(rExpr, lhsType);
1172 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001173}
1174
Chris Lattner5cf216b2008-01-04 18:04:52 +00001175Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001176Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1177 return CheckAssignmentConstraints(lhsType, rhsType);
1178}
1179
Chris Lattnerca5eede2007-12-12 05:47:28 +00001180QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001181 Diag(loc, diag::err_typecheck_invalid_operands,
1182 lex->getType().getAsString(), rex->getType().getAsString(),
1183 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerca5eede2007-12-12 05:47:28 +00001184 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001185}
1186
Steve Naroff49b45262007-07-13 16:58:59 +00001187inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1188 Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001189 QualType lhsType = lex->getType(), rhsType = rex->getType();
1190
1191 // make sure the vector types are identical.
1192 if (lhsType == rhsType)
1193 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00001194
1195 // if the lhs is an ocu vector and the rhs is a scalar of the same type,
1196 // promote the rhs to the vector type.
1197 if (const OCUVectorType *V = lhsType->getAsOCUVectorType()) {
1198 if (V->getElementType().getCanonicalType().getTypePtr()
1199 == rhsType.getCanonicalType().getTypePtr()) {
1200 promoteExprToType(rex, lhsType);
1201 return lhsType;
1202 }
1203 }
1204
1205 // if the rhs is an ocu vector and the lhs is a scalar of the same type,
1206 // promote the lhs to the vector type.
1207 if (const OCUVectorType *V = rhsType->getAsOCUVectorType()) {
1208 if (V->getElementType().getCanonicalType().getTypePtr()
1209 == lhsType.getCanonicalType().getTypePtr()) {
1210 promoteExprToType(lex, rhsType);
1211 return rhsType;
1212 }
1213 }
1214
Reid Spencer5f016e22007-07-11 17:01:13 +00001215 // You cannot convert between vector values of different size.
1216 Diag(loc, diag::err_typecheck_vector_not_convertable,
1217 lex->getType().getAsString(), rex->getType().getAsString(),
1218 lex->getSourceRange(), rex->getSourceRange());
1219 return QualType();
1220}
1221
1222inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001223 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001224{
Steve Naroff90045e82007-07-13 23:32:42 +00001225 QualType lhsType = lex->getType(), rhsType = rex->getType();
1226
1227 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001229
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001230 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001231
Steve Naroffa4332e22007-07-17 00:58:39 +00001232 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001233 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001234 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001235}
1236
1237inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001238 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001239{
Steve Naroff90045e82007-07-13 23:32:42 +00001240 QualType lhsType = lex->getType(), rhsType = rex->getType();
1241
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001242 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001243
Steve Naroffa4332e22007-07-17 00:58:39 +00001244 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001245 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001246 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001247}
1248
1249inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001250 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001251{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001252 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001253 return CheckVectorOperands(loc, lex, rex);
1254
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001255 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Steve Naroff3e5e5562007-07-16 22:23:01 +00001256
Reid Spencer5f016e22007-07-11 17:01:13 +00001257 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001258 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001259 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001260
Steve Naroffa4332e22007-07-17 00:58:39 +00001261 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1262 return lex->getType();
1263 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1264 return rex->getType();
Chris Lattnerca5eede2007-12-12 05:47:28 +00001265 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001266}
1267
1268inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001269 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001270{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001271 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001272 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001273
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001274 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001275
Chris Lattner6e4ab612007-12-09 21:53:25 +00001276 // Enforce type constraints: C99 6.5.6p3.
1277
1278 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001279 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001280 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001281
1282 // Either ptr - int or ptr - ptr.
1283 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1284 // The LHS must be an object type, not incomplete, function, etc.
1285 if (!LHSPTy->getPointeeType()->isObjectType()) {
1286 // Handle the GNU void* extension.
1287 if (LHSPTy->getPointeeType()->isVoidType()) {
1288 Diag(loc, diag::ext_gnu_void_ptr,
1289 lex->getSourceRange(), rex->getSourceRange());
1290 } else {
1291 Diag(loc, diag::err_typecheck_sub_ptr_object,
1292 lex->getType().getAsString(), lex->getSourceRange());
1293 return QualType();
1294 }
1295 }
1296
1297 // The result type of a pointer-int computation is the pointer type.
1298 if (rex->getType()->isIntegerType())
1299 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001300
Chris Lattner6e4ab612007-12-09 21:53:25 +00001301 // Handle pointer-pointer subtractions.
1302 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1303 // RHS must be an object type, unless void (GNU).
1304 if (!RHSPTy->getPointeeType()->isObjectType()) {
1305 // Handle the GNU void* extension.
1306 if (RHSPTy->getPointeeType()->isVoidType()) {
1307 if (!LHSPTy->getPointeeType()->isVoidType())
1308 Diag(loc, diag::ext_gnu_void_ptr,
1309 lex->getSourceRange(), rex->getSourceRange());
1310 } else {
1311 Diag(loc, diag::err_typecheck_sub_ptr_object,
1312 rex->getType().getAsString(), rex->getSourceRange());
1313 return QualType();
1314 }
1315 }
1316
1317 // Pointee types must be compatible.
1318 if (!Context.typesAreCompatible(LHSPTy->getPointeeType(),
1319 RHSPTy->getPointeeType())) {
1320 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1321 lex->getType().getAsString(), rex->getType().getAsString(),
1322 lex->getSourceRange(), rex->getSourceRange());
1323 return QualType();
1324 }
1325
1326 return Context.getPointerDiffType();
1327 }
1328 }
1329
Chris Lattnerca5eede2007-12-12 05:47:28 +00001330 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001331}
1332
1333inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Chris Lattnerca5eede2007-12-12 05:47:28 +00001334 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1335 // C99 6.5.7p2: Each of the operands shall have integer type.
1336 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1337 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001338
Chris Lattnerca5eede2007-12-12 05:47:28 +00001339 // Shifts don't perform usual arithmetic conversions, they just do integer
1340 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00001341 if (!isCompAssign)
1342 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00001343 UsualUnaryConversions(rex);
1344
1345 // "The type of the result is that of the promoted left operand."
1346 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001347}
1348
Chris Lattnera5937dd2007-08-26 01:18:55 +00001349inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1350 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Reid Spencer5f016e22007-07-11 17:01:13 +00001351{
Chris Lattnera5937dd2007-08-26 01:18:55 +00001352 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00001353 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1354 UsualArithmeticConversions(lex, rex);
1355 else {
1356 UsualUnaryConversions(lex);
1357 UsualUnaryConversions(rex);
1358 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001359 QualType lType = lex->getType();
1360 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001361
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001362 // For non-floating point types, check for self-comparisons of the form
1363 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1364 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001365 if (!lType->isFloatingType()) {
1366 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1367 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1368 if (DRL->getDecl() == DRR->getDecl())
1369 Diag(loc, diag::warn_selfcomparison);
1370 }
1371
Chris Lattnera5937dd2007-08-26 01:18:55 +00001372 if (isRelational) {
1373 if (lType->isRealType() && rType->isRealType())
1374 return Context.IntTy;
1375 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001376 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001377 if (lType->isFloatingType()) {
1378 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001379 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00001380 }
1381
Chris Lattnera5937dd2007-08-26 01:18:55 +00001382 if (lType->isArithmeticType() && rType->isArithmeticType())
1383 return Context.IntTy;
1384 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001385
Chris Lattnerd28f8152007-08-26 01:10:14 +00001386 bool LHSIsNull = lex->isNullPointerConstant(Context);
1387 bool RHSIsNull = rex->isNullPointerConstant(Context);
1388
Chris Lattnera5937dd2007-08-26 01:18:55 +00001389 // All of the following pointer related warnings are GCC extensions, except
1390 // when handling null pointer constants. One day, we can consider making them
1391 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00001392 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff66296cb2007-11-13 14:57:38 +00001393
1394 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1395 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1396 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroffec0550f2007-10-15 20:41:53 +00001397 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1398 rType.getUnqualifiedType())) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001399 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1400 lType.getAsString(), rType.getAsString(),
1401 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001402 }
Chris Lattnerd28f8152007-08-26 01:10:14 +00001403 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001404 return Context.IntTy;
1405 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00001406 if ((lType->isObjcQualifiedIdType() || rType->isObjcQualifiedIdType())
Fariborz Jahaniand0c89c42007-12-21 00:33:59 +00001407 && Context.ObjcQualifiedIdTypesAreCompatible(lType, rType, true)) {
Fariborz Jahanian7359f042007-12-20 01:06:58 +00001408 promoteExprToType(rex, lType);
1409 return Context.IntTy;
1410 }
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001411 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001412 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001413 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1414 lType.getAsString(), rType.getAsString(),
1415 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001416 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001417 return Context.IntTy;
1418 }
1419 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001420 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001421 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1422 lType.getAsString(), rType.getAsString(),
1423 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001424 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001425 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 }
Chris Lattnerca5eede2007-12-12 05:47:28 +00001427 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001428}
1429
Reid Spencer5f016e22007-07-11 17:01:13 +00001430inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001431 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001432{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001433 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001434 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001435
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001436 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001437
Steve Naroffa4332e22007-07-17 00:58:39 +00001438 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001439 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001440 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001441}
1442
1443inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00001444 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001445{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001446 UsualUnaryConversions(lex);
1447 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001448
Steve Naroffa4332e22007-07-17 00:58:39 +00001449 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001450 return Context.IntTy;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001451 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001452}
1453
1454inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00001455 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001456{
1457 QualType lhsType = lex->getType();
1458 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001459 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1460
1461 switch (mlval) { // C99 6.5.16p2
Chris Lattner5cf216b2008-01-04 18:04:52 +00001462 case Expr::MLV_Valid:
1463 break;
1464 case Expr::MLV_ConstQualified:
1465 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1466 return QualType();
1467 case Expr::MLV_ArrayType:
1468 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1469 lhsType.getAsString(), lex->getSourceRange());
1470 return QualType();
1471 case Expr::MLV_NotObjectType:
1472 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1473 lhsType.getAsString(), lex->getSourceRange());
1474 return QualType();
1475 case Expr::MLV_InvalidExpression:
1476 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1477 lex->getSourceRange());
1478 return QualType();
1479 case Expr::MLV_IncompleteType:
1480 case Expr::MLV_IncompleteVoidType:
1481 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1482 lhsType.getAsString(), lex->getSourceRange());
1483 return QualType();
1484 case Expr::MLV_DuplicateVectorComponents:
1485 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1486 lex->getSourceRange());
1487 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00001489
Chris Lattner5cf216b2008-01-04 18:04:52 +00001490 AssignConvertType ConvTy;
1491 if (compoundType.isNull())
1492 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1493 else
1494 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1495
1496 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1497 rex, "assigning"))
1498 return QualType();
1499
Reid Spencer5f016e22007-07-11 17:01:13 +00001500 // C99 6.5.16p3: The type of an assignment expression is the type of the
1501 // left operand unless the left operand has qualified type, in which case
1502 // it is the unqualified version of the type of the left operand.
1503 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1504 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001505 // C++ 5.17p1: the type of the assignment expression is that of its left
1506 // oprdu.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001507 return lhsType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001508}
1509
1510inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00001511 Expr *&lex, Expr *&rex, SourceLocation loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001512 UsualUnaryConversions(rex);
1513 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001514}
1515
Steve Naroff49b45262007-07-13 16:58:59 +00001516/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1517/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00001518QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00001519 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001520 assert(!resType.isNull() && "no type for increment/decrement expression");
1521
Steve Naroff084f9ed2007-08-24 17:20:07 +00001522 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00001523 if (const PointerType *pt = resType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1525 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1526 resType.getAsString(), op->getSourceRange());
1527 return QualType();
1528 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00001529 } else if (!resType->isRealType()) {
1530 if (resType->isComplexType())
1531 // C99 does not support ++/-- on complex types.
1532 Diag(OpLoc, diag::ext_integer_increment_complex,
1533 resType.getAsString(), op->getSourceRange());
1534 else {
1535 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1536 resType.getAsString(), op->getSourceRange());
1537 return QualType();
1538 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 }
Steve Naroffdd10e022007-08-23 21:37:33 +00001540 // At this point, we know we have a real, complex or pointer type.
1541 // Now make sure the operand is a modifiable lvalue.
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1543 if (mlval != Expr::MLV_Valid) {
1544 // FIXME: emit a more precise diagnostic...
1545 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1546 op->getSourceRange());
1547 return QualType();
1548 }
1549 return resType;
1550}
1551
1552/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1553/// This routine allows us to typecheck complex/recursive expressions
1554/// where the declaration is needed for type checking. Here are some
1555/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1556static Decl *getPrimaryDeclaration(Expr *e) {
1557 switch (e->getStmtClass()) {
1558 case Stmt::DeclRefExprClass:
1559 return cast<DeclRefExpr>(e)->getDecl();
1560 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00001561 // Fields cannot be declared with a 'register' storage class.
1562 // &X->f is always ok, even if X is declared register.
1563 if (cast<MemberExpr>(e)->isArrow())
1564 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1566 case Stmt::ArraySubscriptExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00001567 // &X[4] and &4[X] is invalid if X is invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +00001568 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 case Stmt::UnaryOperatorClass:
1570 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1571 case Stmt::ParenExprClass:
1572 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00001573 case Stmt::ImplicitCastExprClass:
1574 // &X[4] when X is an array, has an implicit cast from array to pointer.
1575 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 default:
1577 return 0;
1578 }
1579}
1580
1581/// CheckAddressOfOperand - The operand of & must be either a function
1582/// designator or an lvalue designating an object. If it is an lvalue, the
1583/// object cannot be declared with storage class register or be a bit field.
1584/// Note: The usual conversions are *not* applied to the operand of the &
1585/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1586QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1587 Decl *dcl = getPrimaryDeclaration(op);
1588 Expr::isLvalueResult lval = op->isLvalue();
1589
1590 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00001591 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1592 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1594 op->getSourceRange());
1595 return QualType();
1596 }
1597 } else if (dcl) {
1598 // We have an lvalue with a decl. Make sure the decl is not declared
1599 // with the register storage-class specifier.
1600 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1601 if (vd->getStorageClass() == VarDecl::Register) {
1602 Diag(OpLoc, diag::err_typecheck_address_of_register,
1603 op->getSourceRange());
1604 return QualType();
1605 }
1606 } else
1607 assert(0 && "Unknown/unexpected decl type");
1608
1609 // FIXME: add check for bitfields!
1610 }
1611 // If the operand has type "type", the result has type "pointer to type".
1612 return Context.getPointerType(op->getType());
1613}
1614
1615QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001616 UsualUnaryConversions(op);
1617 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001618
Chris Lattnerbefee482007-07-31 16:53:04 +00001619 if (const PointerType *PT = qType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001620 QualType ptype = PT->getPointeeType();
1621 // C99 6.5.3.2p4. "if it points to an object,...".
1622 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1623 // GCC compat: special case 'void *' (treat as warning).
1624 if (ptype->isVoidType()) {
1625 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1626 qType.getAsString(), op->getSourceRange());
1627 } else {
1628 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1629 ptype.getAsString(), op->getSourceRange());
1630 return QualType();
1631 }
1632 }
1633 return ptype;
1634 }
1635 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1636 qType.getAsString(), op->getSourceRange());
1637 return QualType();
1638}
1639
1640static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1641 tok::TokenKind Kind) {
1642 BinaryOperator::Opcode Opc;
1643 switch (Kind) {
1644 default: assert(0 && "Unknown binop!");
1645 case tok::star: Opc = BinaryOperator::Mul; break;
1646 case tok::slash: Opc = BinaryOperator::Div; break;
1647 case tok::percent: Opc = BinaryOperator::Rem; break;
1648 case tok::plus: Opc = BinaryOperator::Add; break;
1649 case tok::minus: Opc = BinaryOperator::Sub; break;
1650 case tok::lessless: Opc = BinaryOperator::Shl; break;
1651 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1652 case tok::lessequal: Opc = BinaryOperator::LE; break;
1653 case tok::less: Opc = BinaryOperator::LT; break;
1654 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1655 case tok::greater: Opc = BinaryOperator::GT; break;
1656 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1657 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1658 case tok::amp: Opc = BinaryOperator::And; break;
1659 case tok::caret: Opc = BinaryOperator::Xor; break;
1660 case tok::pipe: Opc = BinaryOperator::Or; break;
1661 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1662 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1663 case tok::equal: Opc = BinaryOperator::Assign; break;
1664 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1665 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1666 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1667 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1668 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1669 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1670 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1671 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1672 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1673 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1674 case tok::comma: Opc = BinaryOperator::Comma; break;
1675 }
1676 return Opc;
1677}
1678
1679static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1680 tok::TokenKind Kind) {
1681 UnaryOperator::Opcode Opc;
1682 switch (Kind) {
1683 default: assert(0 && "Unknown unary op!");
1684 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1685 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1686 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1687 case tok::star: Opc = UnaryOperator::Deref; break;
1688 case tok::plus: Opc = UnaryOperator::Plus; break;
1689 case tok::minus: Opc = UnaryOperator::Minus; break;
1690 case tok::tilde: Opc = UnaryOperator::Not; break;
1691 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1692 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1693 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1694 case tok::kw___real: Opc = UnaryOperator::Real; break;
1695 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1696 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1697 }
1698 return Opc;
1699}
1700
1701// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001702Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 ExprTy *LHS, ExprTy *RHS) {
1704 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1705 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1706
Steve Narofff69936d2007-09-16 03:34:24 +00001707 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1708 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00001709
1710 QualType ResultTy; // Result type of the binary operator.
1711 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1712
1713 switch (Opc) {
1714 default:
1715 assert(0 && "Unknown binary expr!");
1716 case BinaryOperator::Assign:
1717 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1718 break;
1719 case BinaryOperator::Mul:
1720 case BinaryOperator::Div:
1721 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1722 break;
1723 case BinaryOperator::Rem:
1724 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1725 break;
1726 case BinaryOperator::Add:
1727 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1728 break;
1729 case BinaryOperator::Sub:
1730 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1731 break;
1732 case BinaryOperator::Shl:
1733 case BinaryOperator::Shr:
1734 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1735 break;
1736 case BinaryOperator::LE:
1737 case BinaryOperator::LT:
1738 case BinaryOperator::GE:
1739 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001740 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001741 break;
1742 case BinaryOperator::EQ:
1743 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001744 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001745 break;
1746 case BinaryOperator::And:
1747 case BinaryOperator::Xor:
1748 case BinaryOperator::Or:
1749 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1750 break;
1751 case BinaryOperator::LAnd:
1752 case BinaryOperator::LOr:
1753 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1754 break;
1755 case BinaryOperator::MulAssign:
1756 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001757 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 if (!CompTy.isNull())
1759 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1760 break;
1761 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001762 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001763 if (!CompTy.isNull())
1764 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1765 break;
1766 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001767 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001768 if (!CompTy.isNull())
1769 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1770 break;
1771 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001772 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001773 if (!CompTy.isNull())
1774 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1775 break;
1776 case BinaryOperator::ShlAssign:
1777 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001778 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 if (!CompTy.isNull())
1780 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1781 break;
1782 case BinaryOperator::AndAssign:
1783 case BinaryOperator::XorAssign:
1784 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001785 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 if (!CompTy.isNull())
1787 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1788 break;
1789 case BinaryOperator::Comma:
1790 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1791 break;
1792 }
1793 if (ResultTy.isNull())
1794 return true;
1795 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001796 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001797 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001798 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001799}
1800
1801// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00001802Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00001803 ExprTy *input) {
1804 Expr *Input = (Expr*)input;
1805 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1806 QualType resultType;
1807 switch (Opc) {
1808 default:
1809 assert(0 && "Unimplemented unary expr!");
1810 case UnaryOperator::PreInc:
1811 case UnaryOperator::PreDec:
1812 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1813 break;
1814 case UnaryOperator::AddrOf:
1815 resultType = CheckAddressOfOperand(Input, OpLoc);
1816 break;
1817 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00001818 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00001819 resultType = CheckIndirectionOperand(Input, OpLoc);
1820 break;
1821 case UnaryOperator::Plus:
1822 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001823 UsualUnaryConversions(Input);
1824 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001825 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1826 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1827 resultType.getAsString());
1828 break;
1829 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001830 UsualUnaryConversions(Input);
1831 resultType = Input->getType();
Steve Naroff084f9ed2007-08-24 17:20:07 +00001832 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1833 if (!resultType->isIntegerType()) {
1834 if (resultType->isComplexType())
1835 // C99 does not support '~' for complex conjugation.
1836 Diag(OpLoc, diag::ext_integer_complement_complex,
1837 resultType.getAsString());
1838 else
1839 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1840 resultType.getAsString());
1841 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001842 break;
1843 case UnaryOperator::LNot: // logical negation
1844 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001845 DefaultFunctionArrayConversion(Input);
1846 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001847 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1848 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1849 resultType.getAsString());
1850 // LNot always has type int. C99 6.5.3.3p5.
1851 resultType = Context.IntTy;
1852 break;
1853 case UnaryOperator::SizeOf:
1854 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1855 break;
1856 case UnaryOperator::AlignOf:
1857 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1858 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00001859 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00001860 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00001861 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00001862 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001863 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00001864 resultType = Input->getType();
1865 break;
1866 }
1867 if (resultType.isNull())
1868 return true;
1869 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1870}
1871
Steve Naroff1b273c42007-09-16 14:56:35 +00001872/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1873Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001874 SourceLocation LabLoc,
1875 IdentifierInfo *LabelII) {
1876 // Look up the record for this label identifier.
1877 LabelStmt *&LabelDecl = LabelMap[LabelII];
1878
1879 // If we haven't seen this label yet, create a forward reference.
1880 if (LabelDecl == 0)
1881 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1882
1883 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00001884 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1885 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001886}
1887
Steve Naroff1b273c42007-09-16 14:56:35 +00001888Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001889 SourceLocation RPLoc) { // "({..})"
1890 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1891 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1892 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1893
1894 // FIXME: there are a variety of strange constraints to enforce here, for
1895 // example, it is not possible to goto into a stmt expression apparently.
1896 // More semantic analysis is needed.
1897
1898 // FIXME: the last statement in the compount stmt has its value used. We
1899 // should not warn about it being unused.
1900
1901 // If there are sub stmts in the compound stmt, take the type of the last one
1902 // as the type of the stmtexpr.
1903 QualType Ty = Context.VoidTy;
1904
1905 if (!Compound->body_empty())
1906 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1907 Ty = LastExpr->getType();
1908
1909 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1910}
Steve Naroffd34e9152007-08-01 22:05:33 +00001911
Steve Naroff1b273c42007-09-16 14:56:35 +00001912Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001913 SourceLocation TypeLoc,
1914 TypeTy *argty,
1915 OffsetOfComponent *CompPtr,
1916 unsigned NumComponents,
1917 SourceLocation RPLoc) {
1918 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1919 assert(!ArgTy.isNull() && "Missing type argument!");
1920
1921 // We must have at least one component that refers to the type, and the first
1922 // one is known to be a field designator. Verify that the ArgTy represents
1923 // a struct/union/class.
1924 if (!ArgTy->isRecordType())
1925 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1926
1927 // Otherwise, create a compound literal expression as the base, and
1928 // iteratively process the offsetof designators.
Chris Lattner0fc53df2008-01-02 21:46:24 +00001929 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001930
Chris Lattner9e2b75c2007-08-31 21:49:13 +00001931 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1932 // GCC extension, diagnose them.
1933 if (NumComponents != 1)
1934 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1935 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1936
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001937 for (unsigned i = 0; i != NumComponents; ++i) {
1938 const OffsetOfComponent &OC = CompPtr[i];
1939 if (OC.isBrackets) {
1940 // Offset of an array sub-field. TODO: Should we allow vector elements?
1941 const ArrayType *AT = Res->getType()->getAsArrayType();
1942 if (!AT) {
1943 delete Res;
1944 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1945 Res->getType().getAsString());
1946 }
1947
Chris Lattner704fe352007-08-30 17:59:59 +00001948 // FIXME: C++: Verify that operator[] isn't overloaded.
1949
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001950 // C99 6.5.2.1p1
1951 Expr *Idx = static_cast<Expr*>(OC.U.E);
1952 if (!Idx->getType()->isIntegerType())
1953 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1954 Idx->getSourceRange());
1955
1956 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1957 continue;
1958 }
1959
1960 const RecordType *RC = Res->getType()->getAsRecordType();
1961 if (!RC) {
1962 delete Res;
1963 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1964 Res->getType().getAsString());
1965 }
1966
1967 // Get the decl corresponding to this.
1968 RecordDecl *RD = RC->getDecl();
1969 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1970 if (!MemberDecl)
1971 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1972 OC.U.IdentInfo->getName(),
1973 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00001974
1975 // FIXME: C++: Verify that MemberDecl isn't a static field.
1976 // FIXME: Verify that MemberDecl isn't a bitfield.
1977
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001978 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1979 }
1980
1981 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1982 BuiltinLoc);
1983}
1984
1985
Steve Naroff1b273c42007-09-16 14:56:35 +00001986Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00001987 TypeTy *arg1, TypeTy *arg2,
1988 SourceLocation RPLoc) {
1989 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1990 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1991
1992 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1993
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001994 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00001995}
1996
Steve Naroff1b273c42007-09-16 14:56:35 +00001997Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00001998 ExprTy *expr1, ExprTy *expr2,
1999 SourceLocation RPLoc) {
2000 Expr *CondExpr = static_cast<Expr*>(cond);
2001 Expr *LHSExpr = static_cast<Expr*>(expr1);
2002 Expr *RHSExpr = static_cast<Expr*>(expr2);
2003
2004 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2005
2006 // The conditional expression is required to be a constant expression.
2007 llvm::APSInt condEval(32);
2008 SourceLocation ExpLoc;
2009 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2010 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2011 CondExpr->getSourceRange());
2012
2013 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2014 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2015 RHSExpr->getType();
2016 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2017}
2018
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002019Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2020 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00002021 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002022 Expr *E = static_cast<Expr*>(expr);
2023 QualType T = QualType::getFromOpaquePtr(type);
2024
2025 InitBuiltinVaListType();
2026
Chris Lattner5cf216b2008-01-04 18:04:52 +00002027 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2028 != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002029 return Diag(E->getLocStart(),
2030 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2031 E->getType().getAsString(),
2032 E->getSourceRange());
2033
2034 // FIXME: Warn if a non-POD type is passed in.
2035
2036 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2037}
2038
Chris Lattner5cf216b2008-01-04 18:04:52 +00002039bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2040 SourceLocation Loc,
2041 QualType DstType, QualType SrcType,
2042 Expr *SrcExpr, const char *Flavor) {
2043 // Decode the result (notice that AST's are still created for extensions).
2044 bool isInvalid = false;
2045 unsigned DiagKind;
2046 switch (ConvTy) {
2047 default: assert(0 && "Unknown conversion type");
2048 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00002049 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00002050 DiagKind = diag::ext_typecheck_convert_pointer_int;
2051 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00002052 case IntToPointer:
2053 DiagKind = diag::ext_typecheck_convert_int_pointer;
2054 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002055 case IncompatiblePointer:
2056 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2057 break;
2058 case FunctionVoidPointer:
2059 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2060 break;
2061 case CompatiblePointerDiscardsQualifiers:
2062 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2063 break;
2064 case Incompatible:
2065 DiagKind = diag::err_typecheck_convert_incompatible;
2066 isInvalid = true;
2067 break;
2068 }
2069
2070 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2071 SrcExpr->getSourceRange());
2072 return isInvalid;
2073}
2074