blob: 7ba795f47e4ce6018c9c07f45782fa51ebfa579d [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/Expr.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Lex/LiteralSupport.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/LangOptions.h"
23#include "clang/Basic/TargetInfo.h"
24#include "llvm/ADT/SmallString.h"
25using namespace clang;
26
27/// ParseStringLiteral - The specified tokens were lexed as pasted string
28/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
29/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
30/// multiple tokens. However, the common case is that StringToks points to one
31/// string.
32///
33Action::ExprResult
Chris Lattnerd2177732007-07-20 16:59:19 +000034Sema::ParseStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +000035 assert(NumStringToks && "Must have at least one string!");
36
37 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
38 if (Literal.hadError)
39 return ExprResult(true);
40
41 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
42 for (unsigned i = 0; i != NumStringToks; ++i)
43 StringTokLocs.push_back(StringToks[i].getLocation());
44
45 // FIXME: handle wchar_t
46 QualType t = Context.getPointerType(Context.CharTy);
47
48 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
49 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
50 Literal.AnyWide, t, StringToks[0].getLocation(),
51 StringToks[NumStringToks-1].getLocation());
52}
53
54
55/// ParseIdentifierExpr - The parser read an identifier in expression context,
56/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
57/// identifier is used in an function call context.
58Sema::ExprResult Sema::ParseIdentifierExpr(Scope *S, SourceLocation Loc,
59 IdentifierInfo &II,
60 bool HasTrailingLParen) {
61 // Could be enum-constant or decl.
62 Decl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
63 if (D == 0) {
64 // Otherwise, this could be an implicitly declared function reference (legal
65 // in C90, extension in C99).
66 if (HasTrailingLParen &&
67 // Not in C++.
68 !getLangOptions().CPlusPlus)
69 D = ImplicitlyDefineFunction(Loc, II, S);
70 else {
71 // If this name wasn't predeclared and if this is not a function call,
72 // diagnose the problem.
73 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
74 }
75 }
76
77 if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
78 return new DeclRefExpr(VD, VD->getType(), Loc);
79 if (isa<TypedefDecl>(D))
80 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
81
82 assert(0 && "Invalid decl");
Chris Lattnereddbe032007-07-21 04:57:45 +000083 abort();
Reid Spencer5f016e22007-07-11 17:01:13 +000084}
85
86Sema::ExprResult Sema::ParseSimplePrimaryExpr(SourceLocation Loc,
87 tok::TokenKind Kind) {
88 switch (Kind) {
89 default:
90 assert(0 && "Unknown simple primary expr!");
91 // TODO: MOVE this to be some other callback.
92 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
93 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
94 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
95 return 0;
96 }
97}
98
Chris Lattnerd2177732007-07-20 16:59:19 +000099Sema::ExprResult Sema::ParseCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000100 llvm::SmallString<16> CharBuffer;
101 CharBuffer.resize(Tok.getLength());
102 const char *ThisTokBegin = &CharBuffer[0];
103 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
104
105 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
106 Tok.getLocation(), PP);
107 if (Literal.hadError())
108 return ExprResult(true);
109 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
110 Tok.getLocation());
111}
112
Chris Lattnerd2177732007-07-20 16:59:19 +0000113Action::ExprResult Sema::ParseNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000114 // fast path for a single digit (which is quite common). A single digit
115 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
116 if (Tok.getLength() == 1) {
117 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
118
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000119 unsigned IntSize = Context.getTypeSize(Context.IntTy, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
121 Context.IntTy,
122 Tok.getLocation()));
123 }
124 llvm::SmallString<512> IntegerBuffer;
125 IntegerBuffer.resize(Tok.getLength());
126 const char *ThisTokBegin = &IntegerBuffer[0];
127
128 // Get the spelling of the token, which eliminates trigraphs, etc.
129 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
130 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
131 Tok.getLocation(), PP);
132 if (Literal.hadError)
133 return ExprResult(true);
134
135 if (Literal.isIntegerLiteral()) {
136 QualType t;
137
138 // Get the value in the widest-possible width.
139 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
140
141 if (Literal.GetIntegerValue(ResultVal)) {
142 // If this value didn't fit into uintmax_t, warn and force to ull.
143 Diag(Tok.getLocation(), diag::warn_integer_too_large);
144 t = Context.UnsignedLongLongTy;
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000145 assert(Context.getTypeSize(t, Tok.getLocation()) ==
Reid Spencer5f016e22007-07-11 17:01:13 +0000146 ResultVal.getBitWidth() && "long long is not intmax_t?");
147 } else {
148 // If this value fits into a ULL, try to figure out what else it fits into
149 // according to the rules of C99 6.4.4.1p5.
150
151 // Octal, Hexadecimal, and integers with a U suffix are allowed to
152 // be an unsigned int.
153 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
154
155 // Check from smallest to largest, picking the smallest type we can.
156 if (!Literal.isLong) { // Are int/unsigned possibilities?
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000157 unsigned IntSize = Context.getTypeSize(Context.IntTy,Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000158 // Does it fit in a unsigned int?
159 if (ResultVal.isIntN(IntSize)) {
160 // Does it fit in a signed int?
161 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
162 t = Context.IntTy;
163 else if (AllowUnsigned)
164 t = Context.UnsignedIntTy;
165 }
166
167 if (!t.isNull())
168 ResultVal.trunc(IntSize);
169 }
170
171 // Are long/unsigned long possibilities?
172 if (t.isNull() && !Literal.isLongLong) {
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000173 unsigned LongSize = Context.getTypeSize(Context.LongTy,
174 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000175
176 // Does it fit in a unsigned long?
177 if (ResultVal.isIntN(LongSize)) {
178 // Does it fit in a signed long?
179 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
180 t = Context.LongTy;
181 else if (AllowUnsigned)
182 t = Context.UnsignedLongTy;
183 }
184 if (!t.isNull())
185 ResultVal.trunc(LongSize);
186 }
187
188 // Finally, check long long if needed.
189 if (t.isNull()) {
190 unsigned LongLongSize =
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000191 Context.getTypeSize(Context.LongLongTy, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000192
193 // Does it fit in a unsigned long long?
194 if (ResultVal.isIntN(LongLongSize)) {
195 // Does it fit in a signed long long?
196 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
197 t = Context.LongLongTy;
198 else if (AllowUnsigned)
199 t = Context.UnsignedLongLongTy;
200 }
201 }
202
203 // If we still couldn't decide a type, we probably have something that
204 // does not fit in a signed long long, but has no U suffix.
205 if (t.isNull()) {
206 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
207 t = Context.UnsignedLongLongTy;
208 }
209 }
210
211 return new IntegerLiteral(ResultVal, t, Tok.getLocation());
212 } else if (Literal.isFloatingLiteral()) {
213 // FIXME: handle float values > 32 (including compute the real type...).
214 return new FloatingLiteral(Literal.GetFloatValue(), Context.FloatTy,
215 Tok.getLocation());
216 }
217 return ExprResult(true);
218}
219
220Action::ExprResult Sema::ParseParenExpr(SourceLocation L, SourceLocation R,
221 ExprTy *Val) {
222 Expr *e = (Expr *)Val;
223 assert((e != 0) && "ParseParenExpr() missing expr");
224 return new ParenExpr(L, R, e);
225}
226
227/// The UsualUnaryConversions() function is *not* called by this routine.
228/// See C99 6.3.2.1p[2-4] for more details.
229QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
230 SourceLocation OpLoc, bool isSizeof) {
231 // C99 6.5.3.4p1:
232 if (isa<FunctionType>(exprType) && isSizeof)
233 // alignof(function) is allowed.
234 Diag(OpLoc, diag::ext_sizeof_function_type);
235 else if (exprType->isVoidType())
236 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
237 else if (exprType->isIncompleteType()) {
238 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
239 diag::err_alignof_incomplete_type,
240 exprType.getAsString());
241 return QualType(); // error
242 }
243 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
244 return Context.getSizeType();
245}
246
247Action::ExprResult Sema::
248ParseSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
249 SourceLocation LPLoc, TypeTy *Ty,
250 SourceLocation RPLoc) {
251 // If error parsing type, ignore.
252 if (Ty == 0) return true;
253
254 // Verify that this is a valid expression.
255 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
256
257 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
258
259 if (resultType.isNull())
260 return true;
261 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
262}
263
264
265Action::ExprResult Sema::ParsePostfixUnaryOp(SourceLocation OpLoc,
266 tok::TokenKind Kind,
267 ExprTy *Input) {
268 UnaryOperator::Opcode Opc;
269 switch (Kind) {
270 default: assert(0 && "Unknown unary op!");
271 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
272 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
273 }
274 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
275 if (result.isNull())
276 return true;
277 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
278}
279
280Action::ExprResult Sema::
281ParseArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
282 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000283 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000284
285 // Perform default conversions.
286 DefaultFunctionArrayConversion(LHSExp);
287 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000288
Chris Lattner12d9ff62007-07-16 00:14:47 +0000289 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000290
Reid Spencer5f016e22007-07-11 17:01:13 +0000291 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
292 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
293 // in the subscript position. As a result, we need to derive the array base
294 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000295 Expr *BaseExpr, *IndexExpr;
296 QualType ResultType;
Chris Lattner7a2e0472007-07-16 00:23:25 +0000297 if (const PointerType *PTy = LHSTy->isPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000298 BaseExpr = LHSExp;
299 IndexExpr = RHSExp;
300 // FIXME: need to deal with const...
301 ResultType = PTy->getPointeeType();
Chris Lattner7a2e0472007-07-16 00:23:25 +0000302 } else if (const PointerType *PTy = RHSTy->isPointerType()) {
303 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000304 BaseExpr = RHSExp;
305 IndexExpr = LHSExp;
306 // FIXME: need to deal with const...
307 ResultType = PTy->getPointeeType();
Chris Lattner7a2e0472007-07-16 00:23:25 +0000308 } else if (const VectorType *VTy = LHSTy->isVectorType()) { // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000309 BaseExpr = LHSExp;
310 IndexExpr = RHSExp;
311 // FIXME: need to deal with const...
312 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000314 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
315 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000316 }
317 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000318 if (!IndexExpr->getType()->isIntegerType())
319 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
320 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000321
Chris Lattner12d9ff62007-07-16 00:14:47 +0000322 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
323 // the following check catches trying to index a pointer to a function (e.g.
324 // void (*)(int)). Functions are not objects in C99.
325 if (!ResultType->isObjectType())
326 return Diag(BaseExpr->getLocStart(),
327 diag::err_typecheck_subscript_not_object,
328 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
329
330 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000331}
332
333Action::ExprResult Sema::
334ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
335 tok::TokenKind OpKind, SourceLocation MemberLoc,
336 IdentifierInfo &Member) {
337 QualType qualifiedType = ((Expr *)Base)->getType();
338
339 assert(!qualifiedType.isNull() && "no type for member expression");
340
341 QualType canonType = qualifiedType.getCanonicalType();
342
343 if (OpKind == tok::arrow) {
344 if (PointerType *PT = dyn_cast<PointerType>(canonType)) {
345 qualifiedType = PT->getPointeeType();
346 canonType = qualifiedType.getCanonicalType();
347 } else
348 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow);
349 }
350 if (!isa<RecordType>(canonType))
351 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion);
352
353 // get the struct/union definition from the type.
354 RecordDecl *RD = cast<RecordType>(canonType)->getDecl();
355
356 if (canonType->isIncompleteType())
357 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RD->getName());
358
359 FieldDecl *MemberDecl = RD->getMember(&Member);
360 if (!MemberDecl)
361 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName());
362
363 return new MemberExpr((Expr*)Base, OpKind == tok::arrow,
364 MemberDecl, MemberLoc);
365}
366
367/// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
368/// This provides the location of the left/right parens and a list of comma
369/// locations.
370Action::ExprResult Sema::
Chris Lattner74c469f2007-07-21 03:03:59 +0000371ParseCallExpr(ExprTy *fn, SourceLocation LParenLoc,
372 ExprTy **args, unsigned NumArgsInCall,
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000374 Expr *Fn = static_cast<Expr *>(fn);
375 Expr **Args = reinterpret_cast<Expr**>(args);
376 assert(Fn && "no function call expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000377
Chris Lattner74c469f2007-07-21 03:03:59 +0000378 UsualUnaryConversions(Fn);
379 QualType funcType = Fn->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000380
381 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
382 // type pointer to function".
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000383 const PointerType *PT = dyn_cast<PointerType>(funcType);
384 if (PT == 0) PT = dyn_cast<PointerType>(funcType.getCanonicalType());
Reid Spencer5f016e22007-07-11 17:01:13 +0000385
386 if (PT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000387 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
388 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000389
390 const FunctionType *funcT = dyn_cast<FunctionType>(PT->getPointeeType());
391 if (funcT == 0)
392 funcT = dyn_cast<FunctionType>(PT->getPointeeType().getCanonicalType());
393
394 if (funcT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000395 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
396 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000397
398 // If a prototype isn't declared, the parser implicitly defines a func decl
399 QualType resultType = funcT->getResultType();
400
401 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
402 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
403 // assignment, to the types of the corresponding parameter, ...
404
405 unsigned NumArgsInProto = proto->getNumArgs();
406 unsigned NumArgsToCheck = NumArgsInCall;
407
408 if (NumArgsInCall < NumArgsInProto)
409 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
Chris Lattner74c469f2007-07-21 03:03:59 +0000410 Fn->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 else if (NumArgsInCall > NumArgsInProto) {
412 if (!proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +0000413 Diag(Args[NumArgsInProto]->getLocStart(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000414 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +0000415 SourceRange(Args[NumArgsInProto]->getLocStart(),
416 Args[NumArgsInCall-1]->getLocEnd()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 }
418 NumArgsToCheck = NumArgsInProto;
419 }
420 // Continue to check argument types (even if we have too few/many args).
421 for (unsigned i = 0; i < NumArgsToCheck; i++) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000422 Expr *argExpr = Args[i];
Reid Spencer5f016e22007-07-11 17:01:13 +0000423 assert(argExpr && "ParseCallExpr(): missing argument expression");
424
425 QualType lhsType = proto->getArgType(i);
426 QualType rhsType = argExpr->getType();
427
428 if (lhsType == rhsType) // common case, fast path...
429 continue;
430
Steve Naroff90045e82007-07-13 23:32:42 +0000431 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
432 argExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 SourceLocation l = argExpr->getLocStart();
434
435 // decode the result (notice that AST's are still created for extensions).
436 switch (result) {
437 case Compatible:
438 break;
439 case PointerFromInt:
440 // check for null pointer constant (C99 6.3.2.3p3)
Chris Lattner590b6642007-07-15 23:26:56 +0000441 if (!argExpr->isNullPointerConstant(Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000442 Diag(l, diag::ext_typecheck_passing_pointer_int,
443 lhsType.getAsString(), rhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000444 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000445 }
446 break;
447 case IntFromPointer:
448 Diag(l, diag::ext_typecheck_passing_pointer_int,
449 lhsType.getAsString(), rhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000450 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 break;
452 case IncompatiblePointer:
453 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
454 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000455 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000456 break;
457 case CompatiblePointerDiscardsQualifiers:
458 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
459 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000460 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000461 break;
462 case Incompatible:
463 return Diag(l, diag::err_typecheck_passing_incompatible,
464 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000465 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 }
467 }
468 // Even if the types checked, bail if we had the wrong number of arguments.
Chris Lattner74c469f2007-07-21 03:03:59 +0000469 if (NumArgsInCall != NumArgsInProto && !proto->isVariadic())
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 return true;
471 }
Chris Lattner74c469f2007-07-21 03:03:59 +0000472 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000473}
474
475Action::ExprResult Sema::
Steve Naroff4aa88f82007-07-19 01:06:55 +0000476ParseCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +0000477 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff4aa88f82007-07-19 01:06:55 +0000478 assert((Ty != 0) && "ParseCompoundLiteral(): missing type");
479 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +0000480 // FIXME: put back this assert when initializers are worked out.
481 //assert((InitExpr != 0) && "ParseCompoundLiteral(): missing expression");
482 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000483
484 // FIXME: add semantic analysis (C99 6.5.2.5).
Steve Naroffaff1edd2007-07-19 21:32:11 +0000485 return new CompoundLiteralExpr(literalType, literalExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000486}
487
488Action::ExprResult Sema::
489ParseInitList(SourceLocation LParenLoc, ExprTy **InitList, unsigned NumInit,
490 SourceLocation RParenLoc) {
491 // FIXME: add semantic analysis (C99 6.7.8). This involves
492 // knowledge of the object being intialized. As a result, the code for
493 // doing the semantic analysis will likely be located elsewhere (i.e. in
494 // consumers of InitListExpr (e.g. ParseDeclarator, ParseCompoundLiteral).
495 return false; // FIXME instantiate an InitListExpr.
496}
497
498Action::ExprResult Sema::
Reid Spencer5f016e22007-07-11 17:01:13 +0000499ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
500 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff16beff82007-07-16 23:25:18 +0000501 assert((Ty != 0) && (Op != 0) && "ParseCastExpr(): missing type or expr");
502
503 Expr *castExpr = static_cast<Expr*>(Op);
504 QualType castType = QualType::getFromOpaquePtr(Ty);
505
Chris Lattner75af4802007-07-18 16:00:06 +0000506 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
507 // type needs to be scalar.
508 if (!castType->isScalarType() && !castType->isVoidType()) {
Steve Naroff16beff82007-07-16 23:25:18 +0000509 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
510 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
511 }
512 if (!castExpr->getType()->isScalarType()) {
513 return Diag(castExpr->getLocStart(),
514 diag::err_typecheck_expect_scalar_operand,
515 castExpr->getType().getAsString(), castExpr->getSourceRange());
516 }
517 return new CastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000518}
519
520inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +0000521 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000522 UsualUnaryConversions(cond);
523 UsualUnaryConversions(lex);
524 UsualUnaryConversions(rex);
525 QualType condT = cond->getType();
526 QualType lexT = lex->getType();
527 QualType rexT = rex->getType();
528
Reid Spencer5f016e22007-07-11 17:01:13 +0000529 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +0000530 if (!condT->isScalarType()) { // C99 6.5.15p2
531 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
532 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +0000533 return QualType();
534 }
535 // now check the two expressions.
Steve Naroffa4332e22007-07-17 00:58:39 +0000536 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
537 UsualArithmeticConversions(lex, rex);
538 return lex->getType();
539 }
Steve Naroff49b45262007-07-13 16:58:59 +0000540 if ((lexT->isStructureType() && rexT->isStructureType()) || // C99 6.5.15p3
541 (lexT->isUnionType() && rexT->isUnionType())) {
542 TagType *lTag = cast<TagType>(lexT.getCanonicalType());
543 TagType *rTag = cast<TagType>(rexT.getCanonicalType());
Reid Spencer5f016e22007-07-11 17:01:13 +0000544
545 if (lTag->getDecl()->getIdentifier() == rTag->getDecl()->getIdentifier())
Steve Naroff49b45262007-07-13 16:58:59 +0000546 return lexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000547 else {
548 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000549 lexT.getAsString(), rexT.getAsString(),
550 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000551 return QualType();
552 }
553 }
Chris Lattner590b6642007-07-15 23:26:56 +0000554 // C99 6.5.15p3
555 if (lexT->isPointerType() && rex->isNullPointerConstant(Context))
Steve Naroff49b45262007-07-13 16:58:59 +0000556 return lexT;
Chris Lattner590b6642007-07-15 23:26:56 +0000557 if (rexT->isPointerType() && lex->isNullPointerConstant(Context))
Steve Naroff49b45262007-07-13 16:58:59 +0000558 return rexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000559
Steve Naroff49b45262007-07-13 16:58:59 +0000560 if (lexT->isPointerType() && rexT->isPointerType()) { // C99 6.5.15p3,6
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 QualType lhptee, rhptee;
562
563 // get the "pointed to" type
Steve Naroff49b45262007-07-13 16:58:59 +0000564 lhptee = cast<PointerType>(lexT.getCanonicalType())->getPointeeType();
565 rhptee = cast<PointerType>(rexT.getCanonicalType())->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000566
567 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
568 if (lhptee.getUnqualifiedType()->isVoidType() &&
569 (rhptee->isObjectType() || rhptee->isIncompleteType()))
Steve Naroff49b45262007-07-13 16:58:59 +0000570 return lexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000571 if (rhptee.getUnqualifiedType()->isVoidType() &&
572 (lhptee->isObjectType() || lhptee->isIncompleteType()))
Steve Naroff49b45262007-07-13 16:58:59 +0000573 return rexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000574
575 // FIXME: C99 6.5.15p6: If both operands are pointers to compatible types
576 // *or* to differently qualified versions of compatible types, the result
577 // type is a pointer to an appropriately qualified version of the
578 // *composite* type.
579 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
580 rhptee.getUnqualifiedType())) {
581 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
Steve Naroff49b45262007-07-13 16:58:59 +0000582 lexT.getAsString(), rexT.getAsString(),
583 lex->getSourceRange(), rex->getSourceRange());
584 return lexT; // FIXME: this is an _ext - is this return o.k?
Reid Spencer5f016e22007-07-11 17:01:13 +0000585 }
586 }
Steve Naroff49b45262007-07-13 16:58:59 +0000587 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
588 return lexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000589
590 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000591 lexT.getAsString(), rexT.getAsString(),
592 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000593 return QualType();
594}
595
596/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
597/// in the case of a the GNU conditional expr extension.
598Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
599 SourceLocation ColonLoc,
600 ExprTy *Cond, ExprTy *LHS,
601 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +0000602 Expr *CondExpr = (Expr *) Cond;
603 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
604 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
605 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000606 if (result.isNull())
607 return true;
Chris Lattner26824902007-07-16 21:39:03 +0000608 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000609}
610
Steve Narofffa2eaab2007-07-15 02:02:06 +0000611// promoteExprToType - a helper function to ensure we create exactly one
612// ImplicitCastExpr. As a convenience (to the caller), we return the type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000613static void promoteExprToType(Expr *&expr, QualType type) {
Steve Narofffa2eaab2007-07-15 02:02:06 +0000614 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
615 impCast->setType(type);
616 else
617 expr = new ImplicitCastExpr(type, expr);
Steve Naroffa4332e22007-07-17 00:58:39 +0000618 return;
Steve Narofffa2eaab2007-07-15 02:02:06 +0000619}
620
621/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000622void Sema::DefaultFunctionArrayConversion(Expr *&e) {
Steve Narofffa2eaab2007-07-15 02:02:06 +0000623 QualType t = e->getType();
Steve Naroff90045e82007-07-13 23:32:42 +0000624 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
Bill Wendling08ad47c2007-07-17 03:52:31 +0000625
Bill Wendlingccb4af82007-07-17 05:09:22 +0000626 if (const ReferenceType *ref = t->isReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000627 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
628 t = e->getType();
629 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000630 if (t->isFunctionType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000631 promoteExprToType(e, Context.getPointerType(t));
632 else if (const ArrayType *ary = dyn_cast<ArrayType>(t.getCanonicalType()))
633 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000634}
635
636/// UsualUnaryConversion - Performs various conversions that are common to most
637/// operators (C99 6.3). The conversions of array and function types are
638/// sometimes surpressed. For example, the array->pointer conversion doesn't
639/// apply if the array is an argument to the sizeof or address (&) operators.
640/// In these instances, this routine should *not* be called.
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000641void Sema::UsualUnaryConversions(Expr *&expr) {
Steve Naroff49b45262007-07-13 16:58:59 +0000642 QualType t = expr->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000643 assert(!t.isNull() && "UsualUnaryConversions - missing type");
644
Bill Wendlingccb4af82007-07-17 05:09:22 +0000645 if (const ReferenceType *ref = t->isReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000646 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
647 t = expr->getType();
648 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000649 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000650 promoteExprToType(expr, Context.IntTy);
651 else
652 DefaultFunctionArrayConversion(expr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000653}
654
655/// UsualArithmeticConversions - Performs various conversions that are common to
656/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
657/// routine returns the first non-arithmetic type found. The client is
658/// responsible for emitting appropriate error diagnostics.
Steve Naroffa4332e22007-07-17 00:58:39 +0000659void Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000660 UsualUnaryConversions(lhsExpr);
661 UsualUnaryConversions(rhsExpr);
662
Steve Naroff3e5e5562007-07-16 22:23:01 +0000663 QualType lhs = lhsExpr->getType();
664 QualType rhs = rhsExpr->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000665
666 // If both types are identical, no conversion is needed.
667 if (lhs == rhs)
Steve Naroffa4332e22007-07-17 00:58:39 +0000668 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000669
670 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
671 // The caller can deal with this (e.g. pointer + int).
Steve Naroffa4332e22007-07-17 00:58:39 +0000672 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
673 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000674
675 // At this point, we have two different arithmetic types.
676
677 // Handle complex types first (C99 6.3.1.8p1).
678 if (lhs->isComplexType() || rhs->isComplexType()) {
679 // if we have an integer operand, the result is the complex type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000680 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
681 promoteExprToType(rhsExpr, lhs);
682 return;
683 }
684 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
685 promoteExprToType(lhsExpr, rhs);
686 return;
687 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000688 // Two complex types. Convert the smaller operand to the bigger result.
Steve Naroffa4332e22007-07-17 00:58:39 +0000689 if (Context.maxComplexType(lhs, rhs) == lhs) { // convert the rhs
690 promoteExprToType(rhsExpr, lhs);
691 return;
692 }
693 promoteExprToType(lhsExpr, rhs); // convert the lhs
694 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000695 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000696 // Now handle "real" floating types (i.e. float, double, long double).
697 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
698 // if we have an integer operand, the result is the real floating type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000699 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
700 promoteExprToType(rhsExpr, lhs);
701 return;
702 }
703 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
704 promoteExprToType(lhsExpr, rhs);
705 return;
706 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000707 // We have two real floating types, float/complex combos were handled above.
708 // Convert the smaller operand to the bigger result.
Steve Naroffa4332e22007-07-17 00:58:39 +0000709 if (Context.maxFloatingType(lhs, rhs) == lhs) { // convert the rhs
710 promoteExprToType(rhsExpr, lhs);
711 return;
712 }
713 promoteExprToType(lhsExpr, rhs); // convert the lhs
714 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000716 // Finally, we have two differing integer types.
Steve Naroffa4332e22007-07-17 00:58:39 +0000717 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
718 promoteExprToType(rhsExpr, lhs);
719 return;
720 }
721 promoteExprToType(lhsExpr, rhs); // convert the lhs
722 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000723}
724
725// CheckPointerTypesForAssignment - This is a very tricky routine (despite
726// being closely modeled after the C99 spec:-). The odd characteristic of this
727// routine is it effectively iqnores the qualifiers on the top level pointee.
728// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
729// FIXME: add a couple examples in this comment.
730Sema::AssignmentCheckResult
731Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
732 QualType lhptee, rhptee;
733
734 // get the "pointed to" type (ignoring qualifiers at the top level)
735 lhptee = cast<PointerType>(lhsType.getCanonicalType())->getPointeeType();
736 rhptee = cast<PointerType>(rhsType.getCanonicalType())->getPointeeType();
737
738 // make sure we operate on the canonical type
739 lhptee = lhptee.getCanonicalType();
740 rhptee = rhptee.getCanonicalType();
741
742 AssignmentCheckResult r = Compatible;
743
744 // C99 6.5.16.1p1: This following citation is common to constraints
745 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
746 // qualifiers of the type *pointed to* by the right;
747 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
748 rhptee.getQualifiers())
749 r = CompatiblePointerDiscardsQualifiers;
750
751 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
752 // incomplete type and the other is a pointer to a qualified or unqualified
753 // version of void...
754 if (lhptee.getUnqualifiedType()->isVoidType() &&
755 (rhptee->isObjectType() || rhptee->isIncompleteType()))
756 ;
757 else if (rhptee.getUnqualifiedType()->isVoidType() &&
758 (lhptee->isObjectType() || lhptee->isIncompleteType()))
759 ;
760 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
761 // unqualified versions of compatible types, ...
762 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
763 rhptee.getUnqualifiedType()))
764 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
765 return r;
766}
767
768/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
769/// has code to accommodate several GCC extensions when type checking
770/// pointers. Here are some objectionable examples that GCC considers warnings:
771///
772/// int a, *pint;
773/// short *pshort;
774/// struct foo *pfoo;
775///
776/// pint = pshort; // warning: assignment from incompatible pointer type
777/// a = pint; // warning: assignment makes integer from pointer without a cast
778/// pint = a; // warning: assignment makes pointer from integer without a cast
779/// pint = pfoo; // warning: assignment from incompatible pointer type
780///
781/// As a result, the code for dealing with pointers is more complex than the
782/// C99 spec dictates.
783/// Note: the warning above turn into errors when -pedantic-errors is enabled.
784///
785Sema::AssignmentCheckResult
786Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
788 if (lhsType->isVectorType() || rhsType->isVectorType()) {
789 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
790 return Incompatible;
791 }
792 return Compatible;
793 } else if (lhsType->isPointerType()) {
794 if (rhsType->isIntegerType())
795 return PointerFromInt;
796
797 if (rhsType->isPointerType())
798 return CheckPointerTypesForAssignment(lhsType, rhsType);
799 } else if (rhsType->isPointerType()) {
800 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
801 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
802 return IntFromPointer;
803
804 if (lhsType->isPointerType())
805 return CheckPointerTypesForAssignment(lhsType, rhsType);
806 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
807 if (Type::tagTypesAreCompatible(lhsType, rhsType))
808 return Compatible;
809 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
810 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
811 return Compatible;
812 }
813 return Incompatible;
814}
815
Steve Naroff90045e82007-07-13 23:32:42 +0000816Sema::AssignmentCheckResult
817Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
818 // This check seems unnatural, however it is necessary to insure the proper
819 // conversion of functions/arrays. If the conversion were done for all
820 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
821 // expressions that surpress this implicit conversion (&, sizeof).
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000822 DefaultFunctionArrayConversion(rExpr);
Steve Naroff90045e82007-07-13 23:32:42 +0000823
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000824 return CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff90045e82007-07-13 23:32:42 +0000825}
826
827Sema::AssignmentCheckResult
828Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
829 return CheckAssignmentConstraints(lhsType, rhsType);
830}
831
Steve Naroff49b45262007-07-13 16:58:59 +0000832inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000833 Diag(loc, diag::err_typecheck_invalid_operands,
834 lex->getType().getAsString(), rex->getType().getAsString(),
835 lex->getSourceRange(), rex->getSourceRange());
836}
837
Steve Naroff49b45262007-07-13 16:58:59 +0000838inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
839 Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000840 QualType lhsType = lex->getType(), rhsType = rex->getType();
841
842 // make sure the vector types are identical.
843 if (lhsType == rhsType)
844 return lhsType;
845 // You cannot convert between vector values of different size.
846 Diag(loc, diag::err_typecheck_vector_not_convertable,
847 lex->getType().getAsString(), rex->getType().getAsString(),
848 lex->getSourceRange(), rex->getSourceRange());
849 return QualType();
850}
851
852inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff49b45262007-07-13 16:58:59 +0000853 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +0000854{
Steve Naroff90045e82007-07-13 23:32:42 +0000855 QualType lhsType = lex->getType(), rhsType = rex->getType();
856
857 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +0000858 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +0000859
Steve Naroffa4332e22007-07-17 00:58:39 +0000860 UsualArithmeticConversions(lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +0000861
Steve Naroffa4332e22007-07-17 00:58:39 +0000862 // handle the common case first (both operands are arithmetic).
863 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
864 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000865 InvalidOperands(loc, lex, rex);
866 return QualType();
867}
868
869inline QualType Sema::CheckRemainderOperands(
Steve Naroff49b45262007-07-13 16:58:59 +0000870 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +0000871{
Steve Naroff90045e82007-07-13 23:32:42 +0000872 QualType lhsType = lex->getType(), rhsType = rex->getType();
873
Steve Naroffa4332e22007-07-17 00:58:39 +0000874 UsualArithmeticConversions(lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +0000875
Steve Naroffa4332e22007-07-17 00:58:39 +0000876 // handle the common case first (both operands are arithmetic).
877 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
878 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000879 InvalidOperands(loc, lex, rex);
880 return QualType();
881}
882
883inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff49b45262007-07-13 16:58:59 +0000884 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +0000885{
Steve Naroff3e5e5562007-07-16 22:23:01 +0000886 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +0000887 return CheckVectorOperands(loc, lex, rex);
888
Steve Naroffa4332e22007-07-17 00:58:39 +0000889 UsualArithmeticConversions(lex, rex);
Steve Naroff3e5e5562007-07-16 22:23:01 +0000890
Reid Spencer5f016e22007-07-11 17:01:13 +0000891 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +0000892 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
893 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000894
Steve Naroffa4332e22007-07-17 00:58:39 +0000895 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
896 return lex->getType();
897 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
898 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000899 InvalidOperands(loc, lex, rex);
900 return QualType();
901}
902
903inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff49b45262007-07-13 16:58:59 +0000904 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +0000905{
Steve Naroff3e5e5562007-07-16 22:23:01 +0000906 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +0000907 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +0000908
Steve Naroffa4332e22007-07-17 00:58:39 +0000909 UsualArithmeticConversions(lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +0000910
911 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +0000912 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
913 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +0000914
915 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroffa4332e22007-07-17 00:58:39 +0000916 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +0000917 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
Chris Lattner8b9023b2007-07-13 03:05:23 +0000918 return Context.getPointerDiffType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000919 InvalidOperands(loc, lex, rex);
920 return QualType();
921}
922
923inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff49b45262007-07-13 16:58:59 +0000924 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +0000925{
926 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
927 // for int << longlong -> the result type should be int, not long long.
Steve Naroffa4332e22007-07-17 00:58:39 +0000928 UsualArithmeticConversions(lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +0000929
Steve Naroffa4332e22007-07-17 00:58:39 +0000930 // handle the common case first (both operands are arithmetic).
931 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
932 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000933 InvalidOperands(loc, lex, rex);
934 return QualType();
935}
936
937inline QualType Sema::CheckRelationalOperands( // C99 6.5.8
Steve Naroff49b45262007-07-13 16:58:59 +0000938 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +0000939{
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000940 UsualUnaryConversions(lex);
941 UsualUnaryConversions(rex);
942 QualType lType = lex->getType();
943 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000944
945 if (lType->isRealType() && rType->isRealType())
946 return Context.IntTy;
947
948 if (lType->isPointerType()) {
949 if (rType->isPointerType())
950 return Context.IntTy;
951 if (rType->isIntegerType()) {
Chris Lattner590b6642007-07-15 23:26:56 +0000952 if (!rex->isNullPointerConstant(Context))
Reid Spencer5f016e22007-07-11 17:01:13 +0000953 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
954 lex->getSourceRange(), rex->getSourceRange());
955 return Context.IntTy; // the previous diagnostic is a GCC extension.
956 }
957 } else if (rType->isPointerType()) {
958 if (lType->isIntegerType()) {
Chris Lattner590b6642007-07-15 23:26:56 +0000959 if (!lex->isNullPointerConstant(Context))
Reid Spencer5f016e22007-07-11 17:01:13 +0000960 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
961 lex->getSourceRange(), rex->getSourceRange());
962 return Context.IntTy; // the previous diagnostic is a GCC extension.
963 }
964 }
965 InvalidOperands(loc, lex, rex);
966 return QualType();
967}
968
969inline QualType Sema::CheckEqualityOperands( // C99 6.5.9
Steve Naroff49b45262007-07-13 16:58:59 +0000970 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +0000971{
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000972 UsualUnaryConversions(lex);
973 UsualUnaryConversions(rex);
974 QualType lType = lex->getType();
975 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000976
977 if (lType->isArithmeticType() && rType->isArithmeticType())
978 return Context.IntTy;
979
980 if (lType->isPointerType()) {
981 if (rType->isPointerType())
982 return Context.IntTy;
983 if (rType->isIntegerType()) {
Chris Lattner590b6642007-07-15 23:26:56 +0000984 if (!rex->isNullPointerConstant(Context))
Reid Spencer5f016e22007-07-11 17:01:13 +0000985 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
986 lex->getSourceRange(), rex->getSourceRange());
987 return Context.IntTy; // the previous diagnostic is a GCC extension.
988 }
989 } else if (rType->isPointerType()) {
990 if (lType->isIntegerType()) {
Chris Lattner590b6642007-07-15 23:26:56 +0000991 if (!lex->isNullPointerConstant(Context))
Reid Spencer5f016e22007-07-11 17:01:13 +0000992 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
993 lex->getSourceRange(), rex->getSourceRange());
994 return Context.IntTy; // the previous diagnostic is a GCC extension.
995 }
996 }
997 InvalidOperands(loc, lex, rex);
998 return QualType();
999}
1000
1001inline QualType Sema::CheckBitwiseOperands(
Steve Naroff49b45262007-07-13 16:58:59 +00001002 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001003{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001004 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001005 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001006
Steve Naroffa4332e22007-07-17 00:58:39 +00001007 UsualArithmeticConversions(lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001008
Steve Naroffa4332e22007-07-17 00:58:39 +00001009 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1010 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001011 InvalidOperands(loc, lex, rex);
1012 return QualType();
1013}
1014
1015inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00001016 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001017{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001018 UsualUnaryConversions(lex);
1019 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001020
Steve Naroffa4332e22007-07-17 00:58:39 +00001021 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001022 return Context.IntTy;
1023 InvalidOperands(loc, lex, rex);
1024 return QualType();
1025}
1026
1027inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
1028 Expr *lex, Expr *rex, SourceLocation loc, QualType compoundType)
1029{
1030 QualType lhsType = lex->getType();
1031 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1032 bool hadError = false;
1033 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1034
1035 switch (mlval) { // C99 6.5.16p2
1036 case Expr::MLV_Valid:
1037 break;
1038 case Expr::MLV_ConstQualified:
1039 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1040 hadError = true;
1041 break;
1042 case Expr::MLV_ArrayType:
1043 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1044 lhsType.getAsString(), lex->getSourceRange());
1045 return QualType();
1046 case Expr::MLV_NotObjectType:
1047 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1048 lhsType.getAsString(), lex->getSourceRange());
1049 return QualType();
1050 case Expr::MLV_InvalidExpression:
1051 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1052 lex->getSourceRange());
1053 return QualType();
1054 case Expr::MLV_IncompleteType:
1055 case Expr::MLV_IncompleteVoidType:
1056 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1057 lhsType.getAsString(), lex->getSourceRange());
1058 return QualType();
1059 }
1060 if (lhsType == rhsType) // common case, fast path...
1061 return lhsType;
1062
Steve Naroff90045e82007-07-13 23:32:42 +00001063 AssignmentCheckResult result;
1064
1065 if (compoundType.isNull())
1066 result = CheckSingleAssignmentConstraints(lhsType, rex);
1067 else
1068 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1069
Reid Spencer5f016e22007-07-11 17:01:13 +00001070 // decode the result (notice that extensions still return a type).
1071 switch (result) {
1072 case Compatible:
1073 break;
1074 case Incompatible:
1075 Diag(loc, diag::err_typecheck_assign_incompatible,
1076 lhsType.getAsString(), rhsType.getAsString(),
1077 lex->getSourceRange(), rex->getSourceRange());
1078 hadError = true;
1079 break;
1080 case PointerFromInt:
1081 // check for null pointer constant (C99 6.3.2.3p3)
Chris Lattner590b6642007-07-15 23:26:56 +00001082 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1084 lhsType.getAsString(), rhsType.getAsString(),
1085 lex->getSourceRange(), rex->getSourceRange());
1086 }
1087 break;
1088 case IntFromPointer:
1089 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1090 lhsType.getAsString(), rhsType.getAsString(),
1091 lex->getSourceRange(), rex->getSourceRange());
1092 break;
1093 case IncompatiblePointer:
1094 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1095 lhsType.getAsString(), rhsType.getAsString(),
1096 lex->getSourceRange(), rex->getSourceRange());
1097 break;
1098 case CompatiblePointerDiscardsQualifiers:
1099 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1100 lhsType.getAsString(), rhsType.getAsString(),
1101 lex->getSourceRange(), rex->getSourceRange());
1102 break;
1103 }
1104 // C99 6.5.16p3: The type of an assignment expression is the type of the
1105 // left operand unless the left operand has qualified type, in which case
1106 // it is the unqualified version of the type of the left operand.
1107 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1108 // is converted to the type of the assignment expression (above).
1109 // C++ 5.17p1: the type of the assignment expression is that of its left oprdu.
1110 return hadError ? QualType() : lhsType.getUnqualifiedType();
1111}
1112
1113inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00001114 Expr *&lex, Expr *&rex, SourceLocation loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001115 UsualUnaryConversions(rex);
1116 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001117}
1118
Steve Naroff49b45262007-07-13 16:58:59 +00001119/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1120/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00001121QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00001122 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001123 assert(!resType.isNull() && "no type for increment/decrement expression");
1124
1125 // C99 6.5.2.4p1
1126 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1127 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1128 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1129 resType.getAsString(), op->getSourceRange());
1130 return QualType();
1131 }
1132 } else if (!resType->isRealType()) {
1133 // FIXME: Allow Complex as a GCC extension.
1134 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1135 resType.getAsString(), op->getSourceRange());
1136 return QualType();
1137 }
1138 // At this point, we know we have a real or pointer type. Now make sure
1139 // the operand is a modifiable lvalue.
1140 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1141 if (mlval != Expr::MLV_Valid) {
1142 // FIXME: emit a more precise diagnostic...
1143 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1144 op->getSourceRange());
1145 return QualType();
1146 }
1147 return resType;
1148}
1149
1150/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1151/// This routine allows us to typecheck complex/recursive expressions
1152/// where the declaration is needed for type checking. Here are some
1153/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1154static Decl *getPrimaryDeclaration(Expr *e) {
1155 switch (e->getStmtClass()) {
1156 case Stmt::DeclRefExprClass:
1157 return cast<DeclRefExpr>(e)->getDecl();
1158 case Stmt::MemberExprClass:
1159 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1160 case Stmt::ArraySubscriptExprClass:
1161 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1162 case Stmt::CallExprClass:
1163 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1164 case Stmt::UnaryOperatorClass:
1165 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1166 case Stmt::ParenExprClass:
1167 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1168 default:
1169 return 0;
1170 }
1171}
1172
1173/// CheckAddressOfOperand - The operand of & must be either a function
1174/// designator or an lvalue designating an object. If it is an lvalue, the
1175/// object cannot be declared with storage class register or be a bit field.
1176/// Note: The usual conversions are *not* applied to the operand of the &
1177/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1178QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1179 Decl *dcl = getPrimaryDeclaration(op);
1180 Expr::isLvalueResult lval = op->isLvalue();
1181
1182 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1183 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1184 ;
1185 else { // FIXME: emit more specific diag...
1186 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1187 op->getSourceRange());
1188 return QualType();
1189 }
1190 } else if (dcl) {
1191 // We have an lvalue with a decl. Make sure the decl is not declared
1192 // with the register storage-class specifier.
1193 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1194 if (vd->getStorageClass() == VarDecl::Register) {
1195 Diag(OpLoc, diag::err_typecheck_address_of_register,
1196 op->getSourceRange());
1197 return QualType();
1198 }
1199 } else
1200 assert(0 && "Unknown/unexpected decl type");
1201
1202 // FIXME: add check for bitfields!
1203 }
1204 // If the operand has type "type", the result has type "pointer to type".
1205 return Context.getPointerType(op->getType());
1206}
1207
1208QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001209 UsualUnaryConversions(op);
1210 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001211
Reid Spencer5f016e22007-07-11 17:01:13 +00001212 if (PointerType *PT = dyn_cast<PointerType>(qType.getCanonicalType())) {
1213 QualType ptype = PT->getPointeeType();
1214 // C99 6.5.3.2p4. "if it points to an object,...".
1215 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1216 // GCC compat: special case 'void *' (treat as warning).
1217 if (ptype->isVoidType()) {
1218 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1219 qType.getAsString(), op->getSourceRange());
1220 } else {
1221 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1222 ptype.getAsString(), op->getSourceRange());
1223 return QualType();
1224 }
1225 }
1226 return ptype;
1227 }
1228 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1229 qType.getAsString(), op->getSourceRange());
1230 return QualType();
1231}
1232
1233static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1234 tok::TokenKind Kind) {
1235 BinaryOperator::Opcode Opc;
1236 switch (Kind) {
1237 default: assert(0 && "Unknown binop!");
1238 case tok::star: Opc = BinaryOperator::Mul; break;
1239 case tok::slash: Opc = BinaryOperator::Div; break;
1240 case tok::percent: Opc = BinaryOperator::Rem; break;
1241 case tok::plus: Opc = BinaryOperator::Add; break;
1242 case tok::minus: Opc = BinaryOperator::Sub; break;
1243 case tok::lessless: Opc = BinaryOperator::Shl; break;
1244 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1245 case tok::lessequal: Opc = BinaryOperator::LE; break;
1246 case tok::less: Opc = BinaryOperator::LT; break;
1247 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1248 case tok::greater: Opc = BinaryOperator::GT; break;
1249 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1250 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1251 case tok::amp: Opc = BinaryOperator::And; break;
1252 case tok::caret: Opc = BinaryOperator::Xor; break;
1253 case tok::pipe: Opc = BinaryOperator::Or; break;
1254 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1255 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1256 case tok::equal: Opc = BinaryOperator::Assign; break;
1257 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1258 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1259 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1260 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1261 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1262 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1263 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1264 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1265 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1266 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1267 case tok::comma: Opc = BinaryOperator::Comma; break;
1268 }
1269 return Opc;
1270}
1271
1272static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1273 tok::TokenKind Kind) {
1274 UnaryOperator::Opcode Opc;
1275 switch (Kind) {
1276 default: assert(0 && "Unknown unary op!");
1277 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1278 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1279 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1280 case tok::star: Opc = UnaryOperator::Deref; break;
1281 case tok::plus: Opc = UnaryOperator::Plus; break;
1282 case tok::minus: Opc = UnaryOperator::Minus; break;
1283 case tok::tilde: Opc = UnaryOperator::Not; break;
1284 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1285 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1286 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1287 case tok::kw___real: Opc = UnaryOperator::Real; break;
1288 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1289 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1290 }
1291 return Opc;
1292}
1293
1294// Binary Operators. 'Tok' is the token for the operator.
1295Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1296 ExprTy *LHS, ExprTy *RHS) {
1297 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1298 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1299
1300 assert((lhs != 0) && "ParseBinOp(): missing left expression");
1301 assert((rhs != 0) && "ParseBinOp(): missing right expression");
1302
1303 QualType ResultTy; // Result type of the binary operator.
1304 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1305
1306 switch (Opc) {
1307 default:
1308 assert(0 && "Unknown binary expr!");
1309 case BinaryOperator::Assign:
1310 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1311 break;
1312 case BinaryOperator::Mul:
1313 case BinaryOperator::Div:
1314 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1315 break;
1316 case BinaryOperator::Rem:
1317 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1318 break;
1319 case BinaryOperator::Add:
1320 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1321 break;
1322 case BinaryOperator::Sub:
1323 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1324 break;
1325 case BinaryOperator::Shl:
1326 case BinaryOperator::Shr:
1327 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1328 break;
1329 case BinaryOperator::LE:
1330 case BinaryOperator::LT:
1331 case BinaryOperator::GE:
1332 case BinaryOperator::GT:
1333 ResultTy = CheckRelationalOperands(lhs, rhs, TokLoc);
1334 break;
1335 case BinaryOperator::EQ:
1336 case BinaryOperator::NE:
1337 ResultTy = CheckEqualityOperands(lhs, rhs, TokLoc);
1338 break;
1339 case BinaryOperator::And:
1340 case BinaryOperator::Xor:
1341 case BinaryOperator::Or:
1342 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1343 break;
1344 case BinaryOperator::LAnd:
1345 case BinaryOperator::LOr:
1346 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1347 break;
1348 case BinaryOperator::MulAssign:
1349 case BinaryOperator::DivAssign:
1350 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1351 if (!CompTy.isNull())
1352 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1353 break;
1354 case BinaryOperator::RemAssign:
1355 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1356 if (!CompTy.isNull())
1357 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1358 break;
1359 case BinaryOperator::AddAssign:
1360 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1361 if (!CompTy.isNull())
1362 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1363 break;
1364 case BinaryOperator::SubAssign:
1365 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1366 if (!CompTy.isNull())
1367 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1368 break;
1369 case BinaryOperator::ShlAssign:
1370 case BinaryOperator::ShrAssign:
1371 CompTy = CheckShiftOperands(lhs, rhs, TokLoc);
1372 if (!CompTy.isNull())
1373 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1374 break;
1375 case BinaryOperator::AndAssign:
1376 case BinaryOperator::XorAssign:
1377 case BinaryOperator::OrAssign:
1378 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1379 if (!CompTy.isNull())
1380 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1381 break;
1382 case BinaryOperator::Comma:
1383 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1384 break;
1385 }
1386 if (ResultTy.isNull())
1387 return true;
1388 if (CompTy.isNull())
1389 return new BinaryOperator(lhs, rhs, Opc, ResultTy);
1390 else
1391 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy);
1392}
1393
1394// Unary Operators. 'Tok' is the token for the operator.
1395Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1396 ExprTy *input) {
1397 Expr *Input = (Expr*)input;
1398 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1399 QualType resultType;
1400 switch (Opc) {
1401 default:
1402 assert(0 && "Unimplemented unary expr!");
1403 case UnaryOperator::PreInc:
1404 case UnaryOperator::PreDec:
1405 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1406 break;
1407 case UnaryOperator::AddrOf:
1408 resultType = CheckAddressOfOperand(Input, OpLoc);
1409 break;
1410 case UnaryOperator::Deref:
1411 resultType = CheckIndirectionOperand(Input, OpLoc);
1412 break;
1413 case UnaryOperator::Plus:
1414 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001415 UsualUnaryConversions(Input);
1416 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001417 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1418 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1419 resultType.getAsString());
1420 break;
1421 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001422 UsualUnaryConversions(Input);
1423 resultType = Input->getType();
Steve Naroffc63b96a2007-07-12 21:46:55 +00001424 if (!resultType->isIntegerType()) // C99 6.5.3.3p1
1425 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1426 resultType.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +00001427 break;
1428 case UnaryOperator::LNot: // logical negation
1429 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001430 DefaultFunctionArrayConversion(Input);
1431 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001432 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1433 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1434 resultType.getAsString());
1435 // LNot always has type int. C99 6.5.3.3p5.
1436 resultType = Context.IntTy;
1437 break;
1438 case UnaryOperator::SizeOf:
1439 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1440 break;
1441 case UnaryOperator::AlignOf:
1442 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1443 break;
1444 case UnaryOperator::Extension:
1445 // FIXME: does __extension__ cause any promotions? I would think not.
1446 resultType = Input->getType();
1447 break;
1448 }
1449 if (resultType.isNull())
1450 return true;
1451 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1452}
1453
1454/// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
1455Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
1456 SourceLocation LabLoc,
1457 IdentifierInfo *LabelII) {
1458 // Look up the record for this label identifier.
1459 LabelStmt *&LabelDecl = LabelMap[LabelII];
1460
1461 // If we haven't seen this label yet, create a forward reference.
1462 if (LabelDecl == 0)
1463 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1464
1465 // Create the AST node. The address of a label always has type 'void*'.
1466 return new AddrLabel(OpLoc, LabLoc, LabelDecl,
1467 Context.getPointerType(Context.VoidTy));
1468}
1469