blob: b4a81b82595106a06670313a174be38573fc6053 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000015#include "clang/AST/ASTContext.h"
Chris Lattner17ed4872006-11-20 04:58:19 +000016#include "clang/AST/Decl.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000017#include "clang/AST/Expr.h"
18#include "clang/Lex/Preprocessor.h"
Steve Naroff09ef4742007-03-09 23:16:33 +000019#include "clang/Lex/LiteralSupport.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000020#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerac18be92006-11-20 06:49:47 +000022#include "clang/Basic/LangOptions.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000023#include "clang/Basic/TargetInfo.h"
24#include "llvm/ADT/SmallString.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000025using namespace llvm;
26using namespace clang;
27
Steve Naroffdf7855b2007-02-21 23:46:25 +000028/// ParseStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +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 Naroffdf7855b2007-02-21 23:46:25 +000035Sema::ParseStringLiteral(const LexerToken *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +000036 assert(NumStringToks && "Must have at least one string!");
37
Steve Naroff4f88b312007-03-13 22:37:02 +000038 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
39 if (Literal.hadError)
40 return ExprResult(true);
Chris Lattner5b183d82006-11-10 05:03:26 +000041
Chris Lattner5b183d82006-11-10 05:03:26 +000042 SmallVector<SourceLocation, 4> StringTokLocs;
43 for (unsigned i = 0; i != NumStringToks; ++i)
44 StringTokLocs.push_back(StringToks[i].getLocation());
Steve Narofff1e53692007-03-23 22:27:02 +000045
46 // FIXME: handle wchar_t
Steve Naroffe5aa9be2007-04-05 22:36:20 +000047 QualType t = Context.getPointerType(Context.CharTy);
Steve Narofff1e53692007-03-23 22:27:02 +000048
Chris Lattner5b183d82006-11-10 05:03:26 +000049 // FIXME: use factory.
Chris Lattner5b183d82006-11-10 05:03:26 +000050 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Steve Naroff4f88b312007-03-13 22:37:02 +000051 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Steve Narofff1e53692007-03-23 22:27:02 +000052 Literal.AnyWide, t);
Chris Lattner5b183d82006-11-10 05:03:26 +000053}
54
Chris Lattnere168f762006-11-10 05:29:30 +000055
Chris Lattnerac18be92006-11-20 06:49:47 +000056/// ParseIdentifierExpr - The parser read an identifier in expression context,
57/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
58/// identifier is used in an function call context.
59Sema::ExprResult Sema::ParseIdentifierExpr(Scope *S, SourceLocation Loc,
60 IdentifierInfo &II,
61 bool HasTrailingLParen) {
Chris Lattner17ed4872006-11-20 04:58:19 +000062 // Could be enum-constant or decl.
Chris Lattner9561a0b2007-01-28 08:20:04 +000063 Decl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Chris Lattner17ed4872006-11-20 04:58:19 +000064 if (D == 0) {
Bill Wendling4073ed52007-02-13 01:51:42 +000065 // Otherwise, this could be an implicitly declared function reference (legal
Chris Lattner9561a0b2007-01-28 08:20:04 +000066 // in C90, extension in C99).
Chris Lattnerac18be92006-11-20 06:49:47 +000067 if (HasTrailingLParen &&
68 // Not in C++.
Steve Narofff1e53692007-03-23 22:27:02 +000069 !getLangOptions().CPlusPlus)
Chris Lattnerac18be92006-11-20 06:49:47 +000070 D = ImplicitlyDefineFunction(Loc, II, S);
Steve Naroff92e30f82007-04-02 22:35:25 +000071 else {
Chris Lattnerac18be92006-11-20 06:49:47 +000072 // If this name wasn't predeclared and if this is not a function call,
73 // diagnose the problem.
Steve Narofff1e53692007-03-23 22:27:02 +000074 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
Steve Naroff92e30f82007-04-02 22:35:25 +000075 }
Chris Lattner17ed4872006-11-20 04:58:19 +000076 }
77
Steve Naroff46ba1eb2007-04-03 23:13:13 +000078 if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
79 return new DeclRefExpr(VD, VD->getType());
80 if (isa<TypedefDecl>(D))
Steve Narofff1e53692007-03-23 22:27:02 +000081 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
82
83 assert(0 && "Invalid decl");
Chris Lattner17ed4872006-11-20 04:58:19 +000084}
Chris Lattnere168f762006-11-10 05:29:30 +000085
Chris Lattner17ed4872006-11-20 04:58:19 +000086Sema::ExprResult Sema::ParseSimplePrimaryExpr(SourceLocation Loc,
87 tok::TokenKind Kind) {
Chris Lattnere168f762006-11-10 05:29:30 +000088 switch (Kind) {
89 default:
90 assert(0 && "Unknown simple primary expr!");
Chris Lattnere168f762006-11-10 05:29:30 +000091 case tok::char_constant: // constant: character-constant
Chris Lattner17ed4872006-11-20 04:58:19 +000092 // TODO: MOVE this to be some other callback.
Chris Lattnere168f762006-11-10 05:29:30 +000093 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
94 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
95 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Chris Lattner17ed4872006-11-20 04:58:19 +000096 return 0;
Chris Lattnere168f762006-11-10 05:29:30 +000097 }
98}
99
Steve Naroff8160ea22007-03-06 01:09:46 +0000100Action::ExprResult Sema::ParseNumericConstant(const LexerToken &Tok) {
Steve Narofff2fb89e2007-03-13 20:29:44 +0000101 // fast path for a single digit (which is quite common). A single digit
102 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
103 if (Tok.getLength() == 1) {
104 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
105 return ExprResult(new IntegerLiteral(*t-'0', Context.IntTy));
106 }
Steve Naroff8160ea22007-03-06 01:09:46 +0000107 SmallString<512> IntegerBuffer;
108 IntegerBuffer.resize(Tok.getLength());
109 const char *ThisTokBegin = &IntegerBuffer[0];
110
111 // Get the spelling of the token, which eliminates trigraphs, etc. Notes:
112 // - We know that ThisTokBuf points to a buffer that is big enough for the
113 // whole token and 'spelled' tokens can only shrink.
114 // - In practice, the local buffer is only used when the spelling doesn't
115 // match the original token (which is rare). The common case simply returns
116 // a pointer to a *constant* buffer (avoiding a copy).
117
118 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Steve Naroff09ef4742007-03-09 23:16:33 +0000119 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +0000120 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +0000121 if (Literal.hadError)
122 return ExprResult(true);
123
Steve Naroff09ef4742007-03-09 23:16:33 +0000124 if (Literal.isIntegerLiteral()) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000125 QualType t;
Steve Naroff09ef4742007-03-09 23:16:33 +0000126 if (Literal.hasSuffix()) {
127 if (Literal.isLong)
128 t = Literal.isUnsigned ? Context.UnsignedLongTy : Context.LongTy;
129 else if (Literal.isLongLong)
130 t = Literal.isUnsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
131 else
132 t = Context.UnsignedIntTy;
133 } else {
134 t = Context.IntTy; // implicit type is "int"
135 }
Steve Naroff451d8f162007-03-12 23:22:38 +0000136 uintmax_t val;
137 if (Literal.GetIntegerValue(val)) {
Steve Narofff2fb89e2007-03-13 20:29:44 +0000138 return new IntegerLiteral(val, t);
Steve Naroff09ef4742007-03-09 23:16:33 +0000139 }
140 } else if (Literal.isFloatingLiteral()) {
Steve Narofff1e53692007-03-23 22:27:02 +0000141 // FIXME: fill in the value and compute the real type...
142 return new FloatingLiteral(7.7, Context.FloatTy);
Steve Naroff09ef4742007-03-09 23:16:33 +0000143 }
Steve Narofff2fb89e2007-03-13 20:29:44 +0000144 return ExprResult(true);
Chris Lattnere168f762006-11-10 05:29:30 +0000145}
146
147Action::ExprResult Sema::ParseParenExpr(SourceLocation L, SourceLocation R,
148 ExprTy *Val) {
149 return Val;
150}
151
152
153// Unary Operators. 'Tok' is the token for the operator.
154Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
155 ExprTy *Input) {
156 UnaryOperator::Opcode Opc;
157 switch (Op) {
158 default: assert(0 && "Unknown unary op!");
159 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
160 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
161 case tok::amp: Opc = UnaryOperator::AddrOf; break;
162 case tok::star: Opc = UnaryOperator::Deref; break;
163 case tok::plus: Opc = UnaryOperator::Plus; break;
164 case tok::minus: Opc = UnaryOperator::Minus; break;
165 case tok::tilde: Opc = UnaryOperator::Not; break;
166 case tok::exclaim: Opc = UnaryOperator::LNot; break;
167 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
168 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
169 case tok::kw___real: Opc = UnaryOperator::Real; break;
170 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
171 case tok::ampamp: Opc = UnaryOperator::AddrLabel; break;
172 case tok::kw___extension__:
173 return Input;
174 //Opc = UnaryOperator::Extension;
175 //break;
176 }
Steve Naroff95af0132007-03-30 23:47:58 +0000177 if (Opc == UnaryOperator::PreInc || Opc == UnaryOperator::PreDec)
178 return CheckIncrementDecrementOperand((Expr *)Input, OpLoc, Opc);
Steve Naroff47500512007-04-19 23:00:49 +0000179 else if (Opc == UnaryOperator::AddrOf)
180 return CheckAddressOfOperand((Expr *)Input, OpLoc, Opc);
181 else if (Opc == UnaryOperator::Deref)
182 return CheckIndirectionOperand((Expr *)Input, OpLoc, Opc);
Steve Naroff1926c832007-04-24 00:23:05 +0000183 else if (UnaryOperator::isArithmeticOp(Opc))
184 return CheckArithmeticOperand((Expr *)Input, OpLoc, Opc);
185
186 // will go away when all cases are handled...
187 return new UnaryOperator((Expr *)Input, Opc, QualType());
Chris Lattnere168f762006-11-10 05:29:30 +0000188}
189
190Action::ExprResult Sema::
191ParseSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
192 SourceLocation LParenLoc, TypeTy *Ty,
193 SourceLocation RParenLoc) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +0000194 // If error parsing type, ignore.
195 if (Ty == 0) return true;
Chris Lattner6531c102007-01-23 22:29:49 +0000196
197 // Verify that this is a valid expression.
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000198 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
Chris Lattner6531c102007-01-23 22:29:49 +0000199
200 if (isa<FunctionType>(ArgTy) && isSizeof) {
201 // alignof(function) is allowed.
202 Diag(OpLoc, diag::ext_sizeof_function_type);
Steve Naroff26c8ea52007-03-21 21:08:52 +0000203 return new IntegerLiteral(1, Context.IntTy);
Chris Lattner6531c102007-01-23 22:29:49 +0000204 } else if (ArgTy->isVoidType()) {
205 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
206 } else if (ArgTy->isIncompleteType()) {
207 std::string TypeName;
208 ArgTy->getAsString(TypeName);
209 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
210 diag::err_alignof_incomplete_type, TypeName);
Steve Naroff26c8ea52007-03-21 21:08:52 +0000211 return new IntegerLiteral(0, Context.IntTy);
Chris Lattner6531c102007-01-23 22:29:49 +0000212 }
Steve Naroff92e30f82007-04-02 22:35:25 +0000213 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
214 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, Context.getSizeType());
Chris Lattnere168f762006-11-10 05:29:30 +0000215}
216
217
218Action::ExprResult Sema::ParsePostfixUnaryOp(SourceLocation OpLoc,
219 tok::TokenKind Kind,
220 ExprTy *Input) {
221 UnaryOperator::Opcode Opc;
222 switch (Kind) {
223 default: assert(0 && "Unknown unary op!");
224 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
225 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
226 }
Steve Naroff95af0132007-03-30 23:47:58 +0000227 return CheckIncrementDecrementOperand((Expr *)Input, OpLoc, Opc);
Chris Lattnere168f762006-11-10 05:29:30 +0000228}
229
230Action::ExprResult Sema::
231ParseArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
232 ExprTy *Idx, SourceLocation RLoc) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000233 QualType t1 = ((Expr *)Base)->getType();
234 QualType t2 = ((Expr *)Idx)->getType();
Steve Narofff1e53692007-03-23 22:27:02 +0000235
236 assert(!t1.isNull() && "no type for array base expression");
Steve Naroffc1aadb12007-03-28 21:49:40 +0000237 assert(!t2.isNull() && "no type for array index expression");
Steve Narofff1e53692007-03-23 22:27:02 +0000238
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000239 QualType canonT1 = t1.getCanonicalType();
240 QualType canonT2 = t2.getCanonicalType();
Steve Naroffd50c88e2007-04-05 21:15:20 +0000241
Steve Naroffc1aadb12007-03-28 21:49:40 +0000242 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
243 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Steve Narofff1e53692007-03-23 22:27:02 +0000244 // in the subscript position. As a result, we need to derive the array base
245 // and index from the expression types.
246
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000247 QualType baseType, indexType;
Steve Naroffd50c88e2007-04-05 21:15:20 +0000248 if (isa<ArrayType>(canonT1) || isa<PointerType>(canonT1)) {
249 baseType = canonT1;
250 indexType = canonT2;
251 } else if (isa<ArrayType>(canonT2) || isa<PointerType>(canonT2)) { // uncommon
252 baseType = canonT2;
253 indexType = canonT1;
Steve Narofff1e53692007-03-23 22:27:02 +0000254 } else
255 return Diag(LLoc, diag::err_typecheck_subscript_value);
256
Steve Naroffc1aadb12007-03-28 21:49:40 +0000257 // C99 6.5.2.1p1
Steve Naroff1926c832007-04-24 00:23:05 +0000258 if (!indexType->isIntegerType())
Steve Narofff1e53692007-03-23 22:27:02 +0000259 return Diag(LLoc, diag::err_typecheck_subscript);
Steve Naroffc1aadb12007-03-28 21:49:40 +0000260
Steve Naroff95af0132007-03-30 23:47:58 +0000261 // FIXME: need to deal with const...
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000262 QualType resultType;
Steve Naroffc1aadb12007-03-28 21:49:40 +0000263 if (ArrayType *ary = dyn_cast<ArrayType>(baseType)) {
264 resultType = ary->getElementType();
265 } else if (PointerType *ary = dyn_cast<PointerType>(baseType)) {
266 resultType = ary->getPointeeType();
267 // in practice, the following check catches trying to index a pointer
268 // to a function (e.g. void (*)(int)). Functions are not objects in c99.
Steve Naroffbc2f0992007-03-30 20:09:34 +0000269 if (!resultType->isObjectType())
270 return Diag(LLoc, diag::err_typecheck_subscript_not_object, baseType);
Steve Naroffc1aadb12007-03-28 21:49:40 +0000271 }
272 return new ArraySubscriptExpr((Expr*)Base, (Expr*)Idx, resultType);
Chris Lattnere168f762006-11-10 05:29:30 +0000273}
274
275Action::ExprResult Sema::
276ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
277 tok::TokenKind OpKind, SourceLocation MemberLoc,
278 IdentifierInfo &Member) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000279 QualType qualifiedType = ((Expr *)Base)->getType();
Steve Naroffca8f7122007-04-01 01:41:35 +0000280
281 assert(!qualifiedType.isNull() && "no type for member expression");
282
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000283 QualType canonType = qualifiedType.getCanonicalType();
Steve Narofff1e53692007-03-23 22:27:02 +0000284
285 if (OpKind == tok::arrow) {
Steve Naroffca8f7122007-04-01 01:41:35 +0000286 if (PointerType *PT = dyn_cast<PointerType>(canonType)) {
287 qualifiedType = PT->getPointeeType();
Steve Naroffd50c88e2007-04-05 21:15:20 +0000288 canonType = qualifiedType.getCanonicalType();
Steve Naroffca8f7122007-04-01 01:41:35 +0000289 } else
Steve Narofff1e53692007-03-23 22:27:02 +0000290 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow);
291 }
Steve Naroff92e30f82007-04-02 22:35:25 +0000292 if (!isa<RecordType>(canonType))
293 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion);
294
295 // get the struct/union definition from the type.
296 RecordDecl *RD = cast<RecordType>(canonType)->getDecl();
Steve Naroffcc321422007-03-26 23:09:51 +0000297
Steve Naroff92e30f82007-04-02 22:35:25 +0000298 if (canonType->isIncompleteType())
299 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RD->getName());
Steve Naroffcc321422007-03-26 23:09:51 +0000300
Steve Naroff92e30f82007-04-02 22:35:25 +0000301 FieldDecl *MemberDecl = RD->getMember(&Member);
302 if (!MemberDecl)
303 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName());
304
305 return new MemberExpr((Expr*)Base, OpKind == tok::arrow, MemberDecl);
Chris Lattnere168f762006-11-10 05:29:30 +0000306}
307
308/// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
309/// This provides the location of the left/right parens and a list of comma
310/// locations.
311Action::ExprResult Sema::
312ParseCallExpr(ExprTy *Fn, SourceLocation LParenLoc,
313 ExprTy **Args, unsigned NumArgs,
314 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
315 return new CallExpr((Expr*)Fn, (Expr**)Args, NumArgs);
316}
317
318Action::ExprResult Sema::
319ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
320 SourceLocation RParenLoc, ExprTy *Op) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +0000321 // If error parsing type, ignore.
322 if (Ty == 0) return true;
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000323 return new CastExpr(QualType::getFromOpaquePtr(Ty), (Expr*)Op);
Chris Lattnere168f762006-11-10 05:29:30 +0000324}
325
326
327
328// Binary Operators. 'Tok' is the token for the operator.
329Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
330 ExprTy *LHS, ExprTy *RHS) {
331 BinaryOperator::Opcode Opc;
332 switch (Kind) {
333 default: assert(0 && "Unknown binop!");
334 case tok::star: Opc = BinaryOperator::Mul; break;
335 case tok::slash: Opc = BinaryOperator::Div; break;
336 case tok::percent: Opc = BinaryOperator::Rem; break;
337 case tok::plus: Opc = BinaryOperator::Add; break;
338 case tok::minus: Opc = BinaryOperator::Sub; break;
339 case tok::lessless: Opc = BinaryOperator::Shl; break;
340 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
341 case tok::lessequal: Opc = BinaryOperator::LE; break;
342 case tok::less: Opc = BinaryOperator::LT; break;
343 case tok::greaterequal: Opc = BinaryOperator::GE; break;
344 case tok::greater: Opc = BinaryOperator::GT; break;
345 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
346 case tok::equalequal: Opc = BinaryOperator::EQ; break;
347 case tok::amp: Opc = BinaryOperator::And; break;
348 case tok::caret: Opc = BinaryOperator::Xor; break;
349 case tok::pipe: Opc = BinaryOperator::Or; break;
350 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
351 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
352 case tok::equal: Opc = BinaryOperator::Assign; break;
353 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
354 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
355 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
356 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
357 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
358 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
359 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
360 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
361 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
362 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
363 case tok::comma: Opc = BinaryOperator::Comma; break;
364 }
Steve Narofff1e53692007-03-23 22:27:02 +0000365
Steve Naroff1926c832007-04-24 00:23:05 +0000366 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
Chris Lattnere168f762006-11-10 05:29:30 +0000367
Steve Naroff26c8ea52007-03-21 21:08:52 +0000368 if (BinaryOperator::isMultiplicativeOp(Opc))
Steve Naroff5c10d4b2007-04-20 23:42:24 +0000369 return CheckMultiplicativeOperands(lhs, rhs, TokLoc, Opc);
Steve Naroff26c8ea52007-03-21 21:08:52 +0000370 else if (BinaryOperator::isAdditiveOp(Opc))
Steve Naroff1926c832007-04-24 00:23:05 +0000371 return CheckAdditiveOperands(lhs, rhs, TokLoc, Opc);
Steve Naroff26c8ea52007-03-21 21:08:52 +0000372 else if (BinaryOperator::isShiftOp(Opc))
Steve Naroff1926c832007-04-24 00:23:05 +0000373 return CheckShiftOperands(lhs, rhs, TokLoc, Opc);
Steve Naroff26c8ea52007-03-21 21:08:52 +0000374 else if (BinaryOperator::isRelationalOp(Opc))
Steve Naroff1926c832007-04-24 00:23:05 +0000375 return CheckRelationalOperands(lhs, rhs, TokLoc, Opc);
Steve Naroff26c8ea52007-03-21 21:08:52 +0000376 else if (BinaryOperator::isEqualityOp(Opc))
Steve Naroff1926c832007-04-24 00:23:05 +0000377 return CheckEqualityOperands(lhs, rhs, TokLoc, Opc);
Steve Naroff26c8ea52007-03-21 21:08:52 +0000378 else if (BinaryOperator::isBitwiseOp(Opc))
Steve Naroff1926c832007-04-24 00:23:05 +0000379 return CheckBitwiseOperands(lhs, rhs, TokLoc, Opc);
Steve Naroff26c8ea52007-03-21 21:08:52 +0000380 else if (BinaryOperator::isLogicalOp(Opc))
Steve Naroff1926c832007-04-24 00:23:05 +0000381 return CheckLogicalOperands(lhs, rhs, TokLoc, Opc);
382
383 assert(0 && "ParseBinOp() not handling all binary ops properly");
Chris Lattnere168f762006-11-10 05:29:30 +0000384}
385
386/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
387/// in the case of a the GNU conditional expr extension.
388Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
389 SourceLocation ColonLoc,
390 ExprTy *Cond, ExprTy *LHS,
391 ExprTy *RHS) {
392 return new ConditionalOperator((Expr*)Cond, (Expr*)LHS, (Expr*)RHS);
393}
394
Steve Naroff1926c832007-04-24 00:23:05 +0000395/// UsualUnaryConversion - Performs various conversions that are common to most
396/// operators (C99 6.3). The conversions of array and function types are
397/// sometimes surpressed. For example, the array->pointer conversion doesn't
398/// apply if the array is an argument to the sizeof or address (&) operators.
399/// In these instances, this routine should *not* be called.
400QualType Sema::UsualUnaryConversion(QualType t) {
401 assert(!t.isNull() && "UsualUnaryConversion - missing type");
Steve Naroff4b7ce032007-04-20 22:26:17 +0000402
Steve Naroff1926c832007-04-24 00:23:05 +0000403 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
404 return Context.IntTy;
405 else if (t->isFunctionType()) // C99 6.3.2.1p4
406 return Context.getPointerType(t);
407 else if (t->isArrayType()) // C99 6.3.2.1p3
408 return Context.getPointerType(cast<ArrayType>(t)->getElementType());
409 return t;
410}
411
412/// UsualArithmeticConversions - Performs various conversions that are common to
413/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
414/// routine returns the first non-arithmetic type found. The client is
415/// responsible for emitting appropriate error diagnostics.
416QualType Sema::UsualArithmeticConversions(QualType t1, QualType t2) {
417 t1 = UsualUnaryConversion(t1);
418 t2 = UsualUnaryConversion(t2);
419
420 // if either operand is not of arithmetic type, no conversion is possible.
421 if (!t1->isArithmeticType())
422 return t1;
423 else if (!t2->isArithmeticType())
424 return t2;
425
426 // if both operands have the same type, no conversion is needed.
427 if (t1 == t2)
428 return t1;
429
430 // at this point, we have two different arithmetic types. Handle the
Steve Naroffbf223ba2007-04-24 20:56:26 +0000431 // six floating types first (C99 6.3.1.8p1).
432 if (t1->isFloatingType() || t2->isFloatingType()) {
433 if (t1->isRealFloatingType() && t2->isRealFloatingType()) {
434 // types are homogeneous, return the type with the greatest precision
435 if (t1->isLongDoubleType())
436 return t1;
437 else if (t2->isLongDoubleType())
438 return t2;
439 if (t1->isDoubleType())
440 return t1;
441 else if (t2->isDoubleType())
442 return t2;
443 assert(0 && "UsualArithmeticConversions(): floating point conversion");
444 } else if (t1->isComplexType() && t2->isComplexType()) {
445 // types are homogeneous, return the type with the greatest precision
446 if (t1->isLongDoubleComplexType())
447 return t1;
448 else if (t2->isLongDoubleComplexType())
449 return t2;
450 if (t1->isDoubleComplexType())
451 return t1;
452 else if (t2->isDoubleComplexType())
453 return t2;
454 assert(0 && "UsualArithmeticConversions(): floating point conversion");
455 }
456 // type are heterogeneous, handle various permutations.
457 if (t1->isRealFloatingType()) {
458 if (t2->isIntegerType())
459 return t1;
460
461 // return the complex type with the greatest precision (across domains).
462 if (t2->isComplexType()) {
463 if (t1->isLongDoubleType()) {
464 if (t2->isLongDoubleComplexType())
465 return t2;
466 else
467 return t1; // FIXME: need to return "long double _Complex"?
468 } else if (t1->isDoubleType()) {
469 if (t2->isLongDoubleComplexType() || t2->isDoubleComplexType())
470 return t2;
471 else
472 return t1; // FIXME: need to return "double _Complex"?
473 } else {
474 // t1 is a float, there is no need to promote t2 (the complex type).
475 return t2;
476 }
477 }
478 assert(0 && "UsualArithmeticConversions(): floating point conversion");
479 }
480 if (t1->isComplexType()) {
481 if (t2->isIntegerType())
482 return t1;
483
484 if (t2->isRealFloatingType()) {
485 // return the complex type with the greatest precision (across domains).
486 if (t2->isLongDoubleType()) {
487 if (t1->isLongDoubleComplexType())
488 return t1;
489 else
490 return t2; // FIXME: need to return "long double _Complex"?
491 } else if (t2->isDoubleType()) {
492 if (t1->isLongDoubleComplexType() || t1->isDoubleComplexType())
493 return t1;
494 else
495 return t2; // FIXME: need to return "double _Complex"?
496 } else {
497 // t2 is a float, there is no need to promote t1 (the complex type).
498 return t1;
499 }
500 }
501 assert(0 && "UsualArithmeticConversions(): floating point conversion");
502 }
503 if (t1->isIntegerType())
504 return t2;
505 }
Steve Naroff1926c832007-04-24 00:23:05 +0000506 bool t1Unsigned = t1->isUnsignedIntegerType();
507 bool t2Unsigned = t2->isUnsignedIntegerType();
508
509 if (t1Unsigned && t2Unsigned)
510 return t1; // FIXME: return the unsigned type with the greatest rank
511 else if (!t1Unsigned && !t2Unsigned)
512 return t1; // FIXME: return the signed type with the greatest rank
513 else
514 return t1; // FIXME: we have a mixture...
Steve Narofff1e53692007-03-23 22:27:02 +0000515}
516
Steve Naroff5c10d4b2007-04-20 23:42:24 +0000517Action::ExprResult Sema::CheckMultiplicativeOperands(
Steve Naroff1926c832007-04-24 00:23:05 +0000518 Expr *lex, Expr *rex, SourceLocation loc, unsigned code)
Steve Naroff5c10d4b2007-04-20 23:42:24 +0000519{
Steve Naroff1926c832007-04-24 00:23:05 +0000520 QualType resType = UsualArithmeticConversions(lex->getType(), rex->getType());
Steve Naroff5c10d4b2007-04-20 23:42:24 +0000521
522 if ((BinaryOperator::Opcode)code == BinaryOperator::Rem) {
Steve Naroff1926c832007-04-24 00:23:05 +0000523 if (!resType->isIntegerType())
Steve Naroff5c10d4b2007-04-20 23:42:24 +0000524 return Diag(loc, diag::err_typecheck_invalid_operands);
Steve Naroff1926c832007-04-24 00:23:05 +0000525 } else { // *, /
526 if (!resType->isArithmeticType())
Steve Naroff5c10d4b2007-04-20 23:42:24 +0000527 return Diag(loc, diag::err_typecheck_invalid_operands);
528 }
Steve Naroff1926c832007-04-24 00:23:05 +0000529 return new BinaryOperator(lex, rex, (BinaryOperator::Opcode)code, resType);
Steve Naroff26c8ea52007-03-21 21:08:52 +0000530}
531
Steve Naroff1926c832007-04-24 00:23:05 +0000532Action::ExprResult Sema::CheckAdditiveOperands( // C99 6.5.6
533 Expr *lex, Expr *rex, SourceLocation loc, unsigned code)
534{
535 return new BinaryOperator(lex, rex, (BinaryOperator::Opcode)code, Context.IntTy);
Steve Naroff26c8ea52007-03-21 21:08:52 +0000536}
537
Steve Naroff1926c832007-04-24 00:23:05 +0000538Action::ExprResult Sema::CheckShiftOperands( // C99 6.5.7
539 Expr *lex, Expr *rex, SourceLocation loc, unsigned code)
540{
541 QualType resType = UsualArithmeticConversions(lex->getType(), rex->getType());
542
543 if (!resType->isIntegerType())
544 return Diag(loc, diag::err_typecheck_invalid_operands);
545
546 return new BinaryOperator(lex, rex, (BinaryOperator::Opcode)code, resType);
Steve Naroff26c8ea52007-03-21 21:08:52 +0000547}
548
Steve Naroff1926c832007-04-24 00:23:05 +0000549Action::ExprResult Sema::CheckRelationalOperands( // C99 6.5.8
550 Expr *lex, Expr *rex, SourceLocation loc, unsigned code)
551{
552 QualType lType = lex->getType(), rType = rex->getType();
553
554 if (lType->isRealType() && rType->isRealType())
555 ;
556 else if (lType->isPointerType() && rType->isPointerType())
557 ;
558 else {
559 // The following test is for GCC compatibility.
560 if (lType->isIntegerType() || rType->isIntegerType())
561 return Diag(loc, diag::err_typecheck_comparison_of_pointer_integer);
562 return Diag(loc, diag::err_typecheck_invalid_operands);
563 }
564 return new BinaryOperator(lex, rex, (BinaryOperator::Opcode)code,
565 Context.IntTy);
Steve Naroff26c8ea52007-03-21 21:08:52 +0000566}
567
Steve Naroff1926c832007-04-24 00:23:05 +0000568Action::ExprResult Sema::CheckEqualityOperands( // C99 6.5.9
569 Expr *lex, Expr *rex, SourceLocation loc, unsigned code)
570{
571 QualType lType = lex->getType(), rType = rex->getType();
572
573 if (lType->isArithmeticType() && rType->isArithmeticType())
574 ;
575 else if (lType->isPointerType() && rType->isPointerType())
576 ;
577 else {
578 // The following test is for GCC compatibility.
579 if (lType->isIntegerType() || rType->isIntegerType())
580 return Diag(loc, diag::err_typecheck_comparison_of_pointer_integer);
581 return Diag(loc, diag::err_typecheck_invalid_operands);
582 }
583 return new BinaryOperator(lex, rex, (BinaryOperator::Opcode)code,
584 Context.IntTy);
Steve Naroff26c8ea52007-03-21 21:08:52 +0000585}
586
Steve Naroff1926c832007-04-24 00:23:05 +0000587Action::ExprResult Sema::CheckBitwiseOperands(
588 Expr *lex, Expr *rex, SourceLocation loc, unsigned code)
589{
590 QualType resType = UsualArithmeticConversions(lex->getType(), rex->getType());
591
592 if (!resType->isIntegerType())
593 return Diag(loc, diag::err_typecheck_invalid_operands);
594
595 return new BinaryOperator(lex, rex, (BinaryOperator::Opcode)code, resType);
Steve Naroff26c8ea52007-03-21 21:08:52 +0000596}
597
Steve Naroff1926c832007-04-24 00:23:05 +0000598Action::ExprResult Sema::CheckLogicalOperands( // C99 6.5.[13,14]
599 Expr *lex, Expr *rex, SourceLocation loc, unsigned code)
600{
601 return new BinaryOperator(lex, rex, (BinaryOperator::Opcode)code);
Steve Naroff95af0132007-03-30 23:47:58 +0000602}
603
604Action::ExprResult
605Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc,
Steve Naroff78403362007-04-02 22:55:05 +0000606 unsigned OpCode) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000607 QualType qType = op->getType();
Steve Naroff95af0132007-03-30 23:47:58 +0000608
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000609 assert(!qType.isNull() && "no type for increment/decrement expression");
610
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000611 QualType canonType = qType.getCanonicalType();
Steve Naroffd50c88e2007-04-05 21:15:20 +0000612
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000613 // C99 6.5.2.4p1
614 if (const PointerType *pt = dyn_cast<PointerType>(canonType)) {
615 if (!pt->getPointeeType()->isObjectType()) // C99 6.5.2.4p2, 6.5.6p2
616 return Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type, qType);
617 } else if (!canonType->isRealType()) {
Steve Naroff95af0132007-03-30 23:47:58 +0000618 // FIXME: Allow Complex as a GCC extension.
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000619 return Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement, qType);
620 }
Steve Naroff95af0132007-03-30 23:47:58 +0000621 // At this point, we know we have a real or pointer type. As a result, the
622 // following predicate is overkill (i.e. it will check for types we know we
623 // don't have in this context). Nevertheless, we model the C99 spec closely.
Steve Naroffd50c88e2007-04-05 21:15:20 +0000624 if (!canonType.isModifiableLvalue())
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000625 return Diag(OpLoc, diag::err_typecheck_not_modifiable, qType);
Steve Naroff95af0132007-03-30 23:47:58 +0000626
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000627 return new UnaryOperator(op, (UnaryOperator::Opcode)OpCode, qType);
Steve Naroff26c8ea52007-03-21 21:08:52 +0000628}
629
Steve Naroff1926c832007-04-24 00:23:05 +0000630/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +0000631/// This routine allows us to typecheck complex/recursive expressions
632/// where the declaration is needed for type checking. Here are some
633/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
Steve Naroff1926c832007-04-24 00:23:05 +0000634static Decl *getPrimaryDeclaration(Expr *e) {
Steve Naroff47500512007-04-19 23:00:49 +0000635 switch (e->getStmtClass()) {
636 case Stmt::DeclRefExprClass:
637 return cast<DeclRefExpr>(e)->getDecl();
638 case Stmt::MemberExprClass:
Steve Naroff1926c832007-04-24 00:23:05 +0000639 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
Steve Naroff47500512007-04-19 23:00:49 +0000640 case Stmt::ArraySubscriptExprClass:
Steve Naroff1926c832007-04-24 00:23:05 +0000641 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Steve Naroff47500512007-04-19 23:00:49 +0000642 case Stmt::CallExprClass:
Steve Naroff1926c832007-04-24 00:23:05 +0000643 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
Steve Naroff47500512007-04-19 23:00:49 +0000644 case Stmt::UnaryOperatorClass:
Steve Naroff1926c832007-04-24 00:23:05 +0000645 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +0000646 case Stmt::ParenExprClass:
Steve Naroff1926c832007-04-24 00:23:05 +0000647 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +0000648 default:
649 return 0;
650 }
651}
652
653/// CheckAddressOfOperand - The operand of & must be either a function
654/// designator or an lvalue designating an object. If it is an lvalue, the
655/// object cannot be declared with storage class register or be a bit field.
656/// Note: The usual conversions are *not* applied to the operand of the &
657/// operator, and its result is never an lvalue.
658Action::ExprResult
659Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc, unsigned OpCode) {
Steve Naroff1926c832007-04-24 00:23:05 +0000660 Decl *dcl = getPrimaryDeclaration(op);
Steve Naroff47500512007-04-19 23:00:49 +0000661
662 if (!op->isLvalue()) {
663 if (dcl && isa<FunctionDecl>(dcl))
664 ; // C99 6.5.3.2p1: Allow function designators.
665 else
666 return Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof);
667 } else if (dcl) {
668 // We have an lvalue with a decl. Make sure the decl is not declared
669 // with the register storage-class specifier.
670 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
671 if (vd->getStorageClass() == VarDecl::Register)
672 return Diag(OpLoc, diag::err_typecheck_address_of_register);
673 }
674 // FIXME: add check for bitfields!
675 }
676 // If the operand has type "type", the result has type "pointer to type".
677 return new UnaryOperator(op, (UnaryOperator::Opcode)OpCode,
678 Context.getPointerType(op->getType()));
679}
680
681Action::ExprResult
682Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc, unsigned OpCode) {
683 QualType qType = op->getType();
684
685 assert(!qType.isNull() && "no type for * expression");
686
687 QualType canonType = qType.getCanonicalType();
688
689 return new UnaryOperator(op, (UnaryOperator::Opcode)OpCode, QualType());
690}
Steve Naroff1926c832007-04-24 00:23:05 +0000691
692/// CheckArithmeticOperand - Check the arithmetic unary operators (C99 6.5.3.3).
693Action::ExprResult
694Sema::CheckArithmeticOperand(Expr *op, SourceLocation OpLoc, unsigned Opc) {
695 QualType resultType = UsualUnaryConversion(op->getType());
696
697 switch (Opc) {
698 case UnaryOperator::Plus:
699 case UnaryOperator::Minus:
700 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
701 return Diag(OpLoc, diag::err_typecheck_unary_expr, resultType);
702 break;
703 case UnaryOperator::Not: // bitwise complement
704 if (!resultType->isIntegerType()) // C99 6.5.3.3p1
705 return Diag(OpLoc, diag::err_typecheck_unary_expr, resultType);
706 break;
707 case UnaryOperator::LNot: // logical negation
708 if (!resultType->isScalarType()) // C99 6.5.3.3p1
709 return Diag(OpLoc, diag::err_typecheck_unary_expr, resultType);
710 break;
711 }
712 return new UnaryOperator(op, (UnaryOperator::Opcode)Opc, resultType);
713}