blob: 9208db26a8eb11cfd299c906d07197576069d333 [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"
Chris Lattner59907c42007-08-10 20:18:51 +000025#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27
28/// ParseStringLiteral - The specified tokens were lexed as pasted string
29/// 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
Chris Lattnerd2177732007-07-20 16:59:19 +000035Sema::ParseStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +000036 assert(NumStringToks && "Must have at least one string!");
37
38 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
39 if (Literal.hadError)
40 return ExprResult(true);
41
42 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
43 for (unsigned i = 0; i != NumStringToks; ++i)
44 StringTokLocs.push_back(StringToks[i].getLocation());
45
46 // FIXME: handle wchar_t
47 QualType t = Context.getPointerType(Context.CharTy);
48
49 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
50 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
51 Literal.AnyWide, t, StringToks[0].getLocation(),
52 StringToks[NumStringToks-1].getLocation());
53}
54
55
56/// 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) {
62 // Could be enum-constant or decl.
63 Decl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
64 if (D == 0) {
65 // Otherwise, this could be an implicitly declared function reference (legal
66 // in C90, extension in C99).
67 if (HasTrailingLParen &&
68 // Not in C++.
69 !getLangOptions().CPlusPlus)
70 D = ImplicitlyDefineFunction(Loc, II, S);
71 else {
72 // If this name wasn't predeclared and if this is not a function call,
73 // diagnose the problem.
74 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
75 }
76 }
Steve Naroffe1223f72007-08-28 03:03:08 +000077 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroff53a32342007-08-28 18:45:29 +000078 // Only create DeclRefExpr's for valid Decl's.
Steve Naroff5912a352007-08-28 20:14:24 +000079 if (VD->isInvalidDecl())
Steve Naroffe1223f72007-08-28 03:03:08 +000080 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +000081 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroffe1223f72007-08-28 03:03:08 +000082 }
Reid Spencer5f016e22007-07-11 17:01:13 +000083 if (isa<TypedefDecl>(D))
84 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
85
86 assert(0 && "Invalid decl");
Chris Lattnereddbe032007-07-21 04:57:45 +000087 abort();
Reid Spencer5f016e22007-07-11 17:01:13 +000088}
89
Anders Carlsson22742662007-07-21 05:21:51 +000090Sema::ExprResult Sema::ParsePreDefinedExpr(SourceLocation Loc,
91 tok::TokenKind Kind) {
92 PreDefinedExpr::IdentType IT;
93
Reid Spencer5f016e22007-07-11 17:01:13 +000094 switch (Kind) {
95 default:
96 assert(0 && "Unknown simple primary expr!");
Reid Spencer5f016e22007-07-11 17:01:13 +000097 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
Anders Carlsson22742662007-07-21 05:21:51 +000098 IT = PreDefinedExpr::Func;
99 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000100 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000101 IT = PreDefinedExpr::Function;
102 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000103 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000104 IT = PreDefinedExpr::PrettyFunction;
105 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000106 }
Anders Carlsson22742662007-07-21 05:21:51 +0000107
108 // Pre-defined identifiers are always of type char *.
109 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000110}
111
Chris Lattnerd2177732007-07-20 16:59:19 +0000112Sema::ExprResult Sema::ParseCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 llvm::SmallString<16> CharBuffer;
114 CharBuffer.resize(Tok.getLength());
115 const char *ThisTokBegin = &CharBuffer[0];
116 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
117
118 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
119 Tok.getLocation(), PP);
120 if (Literal.hadError())
121 return ExprResult(true);
122 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
123 Tok.getLocation());
124}
125
Chris Lattnerd2177732007-07-20 16:59:19 +0000126Action::ExprResult Sema::ParseNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 // fast path for a single digit (which is quite common). A single digit
128 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
129 if (Tok.getLength() == 1) {
130 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
131
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000132 unsigned IntSize = Context.getTypeSize(Context.IntTy, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000133 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
134 Context.IntTy,
135 Tok.getLocation()));
136 }
137 llvm::SmallString<512> IntegerBuffer;
138 IntegerBuffer.resize(Tok.getLength());
139 const char *ThisTokBegin = &IntegerBuffer[0];
140
141 // Get the spelling of the token, which eliminates trigraphs, etc.
142 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
143 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
144 Tok.getLocation(), PP);
145 if (Literal.hadError)
146 return ExprResult(true);
147
Chris Lattner5d661452007-08-26 03:42:43 +0000148 Expr *Res;
149
150 if (Literal.isFloatingLiteral()) {
151 // FIXME: handle float values > 32 (including compute the real type...).
152 QualType Ty = Literal.isFloat ? Context.FloatTy : Context.DoubleTy;
153 Res = new FloatingLiteral(Literal.GetFloatValue(), Ty, Tok.getLocation());
154 } else if (!Literal.isIntegerLiteral()) {
155 return ExprResult(true);
156 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 QualType t;
158
159 // Get the value in the widest-possible width.
160 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
161
162 if (Literal.GetIntegerValue(ResultVal)) {
163 // If this value didn't fit into uintmax_t, warn and force to ull.
164 Diag(Tok.getLocation(), diag::warn_integer_too_large);
165 t = Context.UnsignedLongLongTy;
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000166 assert(Context.getTypeSize(t, Tok.getLocation()) ==
Reid Spencer5f016e22007-07-11 17:01:13 +0000167 ResultVal.getBitWidth() && "long long is not intmax_t?");
168 } else {
169 // If this value fits into a ULL, try to figure out what else it fits into
170 // according to the rules of C99 6.4.4.1p5.
171
172 // Octal, Hexadecimal, and integers with a U suffix are allowed to
173 // be an unsigned int.
174 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
175
176 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner97c51562007-08-23 21:58:08 +0000177 if (!Literal.isLong && !Literal.isLongLong) {
178 // Are int/unsigned possibilities?
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000179 unsigned IntSize = Context.getTypeSize(Context.IntTy,Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000180 // Does it fit in a unsigned int?
181 if (ResultVal.isIntN(IntSize)) {
182 // Does it fit in a signed int?
183 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
184 t = Context.IntTy;
185 else if (AllowUnsigned)
186 t = Context.UnsignedIntTy;
187 }
188
189 if (!t.isNull())
190 ResultVal.trunc(IntSize);
191 }
192
193 // Are long/unsigned long possibilities?
194 if (t.isNull() && !Literal.isLongLong) {
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000195 unsigned LongSize = Context.getTypeSize(Context.LongTy,
196 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000197
198 // Does it fit in a unsigned long?
199 if (ResultVal.isIntN(LongSize)) {
200 // Does it fit in a signed long?
201 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
202 t = Context.LongTy;
203 else if (AllowUnsigned)
204 t = Context.UnsignedLongTy;
205 }
206 if (!t.isNull())
207 ResultVal.trunc(LongSize);
208 }
209
210 // Finally, check long long if needed.
211 if (t.isNull()) {
212 unsigned LongLongSize =
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000213 Context.getTypeSize(Context.LongLongTy, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000214
215 // Does it fit in a unsigned long long?
216 if (ResultVal.isIntN(LongLongSize)) {
217 // Does it fit in a signed long long?
218 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
219 t = Context.LongLongTy;
220 else if (AllowUnsigned)
221 t = Context.UnsignedLongLongTy;
222 }
223 }
224
225 // If we still couldn't decide a type, we probably have something that
226 // does not fit in a signed long long, but has no U suffix.
227 if (t.isNull()) {
228 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
229 t = Context.UnsignedLongLongTy;
230 }
231 }
232
Chris Lattner5d661452007-08-26 03:42:43 +0000233 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000234 }
Chris Lattner5d661452007-08-26 03:42:43 +0000235
236 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
237 if (Literal.isImaginary)
238 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
239
240 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000241}
242
243Action::ExprResult Sema::ParseParenExpr(SourceLocation L, SourceLocation R,
244 ExprTy *Val) {
245 Expr *e = (Expr *)Val;
246 assert((e != 0) && "ParseParenExpr() missing expr");
247 return new ParenExpr(L, R, e);
248}
249
250/// The UsualUnaryConversions() function is *not* called by this routine.
251/// See C99 6.3.2.1p[2-4] for more details.
252QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
253 SourceLocation OpLoc, bool isSizeof) {
254 // C99 6.5.3.4p1:
255 if (isa<FunctionType>(exprType) && isSizeof)
256 // alignof(function) is allowed.
257 Diag(OpLoc, diag::ext_sizeof_function_type);
258 else if (exprType->isVoidType())
259 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
260 else if (exprType->isIncompleteType()) {
261 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
262 diag::err_alignof_incomplete_type,
263 exprType.getAsString());
264 return QualType(); // error
265 }
266 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
267 return Context.getSizeType();
268}
269
270Action::ExprResult Sema::
271ParseSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
272 SourceLocation LPLoc, TypeTy *Ty,
273 SourceLocation RPLoc) {
274 // If error parsing type, ignore.
275 if (Ty == 0) return true;
276
277 // Verify that this is a valid expression.
278 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
279
280 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
281
282 if (resultType.isNull())
283 return true;
284 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
285}
286
Chris Lattner5d794252007-08-24 21:41:10 +0000287QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000288 DefaultFunctionArrayConversion(V);
289
Chris Lattnercc26ed72007-08-26 05:39:26 +0000290 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000291 if (const ComplexType *CT = V->getType()->getAsComplexType())
292 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000293
294 // Otherwise they pass through real integer and floating point types here.
295 if (V->getType()->isArithmeticType())
296 return V->getType();
297
298 // Reject anything else.
299 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
300 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000301}
302
303
Reid Spencer5f016e22007-07-11 17:01:13 +0000304
305Action::ExprResult Sema::ParsePostfixUnaryOp(SourceLocation OpLoc,
306 tok::TokenKind Kind,
307 ExprTy *Input) {
308 UnaryOperator::Opcode Opc;
309 switch (Kind) {
310 default: assert(0 && "Unknown unary op!");
311 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
312 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
313 }
314 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
315 if (result.isNull())
316 return true;
317 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
318}
319
320Action::ExprResult Sema::
321ParseArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
322 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000323 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000324
325 // Perform default conversions.
326 DefaultFunctionArrayConversion(LHSExp);
327 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000328
Chris Lattner12d9ff62007-07-16 00:14:47 +0000329 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000330
Reid Spencer5f016e22007-07-11 17:01:13 +0000331 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
332 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
333 // in the subscript position. As a result, we need to derive the array base
334 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000335 Expr *BaseExpr, *IndexExpr;
336 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000337 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000338 BaseExpr = LHSExp;
339 IndexExpr = RHSExp;
340 // FIXME: need to deal with const...
341 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000342 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000343 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000344 BaseExpr = RHSExp;
345 IndexExpr = LHSExp;
346 // FIXME: need to deal with const...
347 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000348 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
349 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000350 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000351
352 // Component access limited to variables (reject vec4.rg[1]).
353 if (!isa<DeclRefExpr>(BaseExpr))
354 return Diag(LLoc, diag::err_ocuvector_component_access,
355 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000356 // FIXME: need to deal with const...
357 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000359 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
360 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 }
362 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000363 if (!IndexExpr->getType()->isIntegerType())
364 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
365 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000366
Chris Lattner12d9ff62007-07-16 00:14:47 +0000367 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
368 // the following check catches trying to index a pointer to a function (e.g.
369 // void (*)(int)). Functions are not objects in C99.
370 if (!ResultType->isObjectType())
371 return Diag(BaseExpr->getLocStart(),
372 diag::err_typecheck_subscript_not_object,
373 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
374
375 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000376}
377
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000378QualType Sema::
379CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
380 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnerc8629632007-07-31 19:29:30 +0000381 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000382
383 // The vector accessor can't exceed the number of elements.
384 const char *compStr = CompName.getName();
385 if (strlen(compStr) > vecType->getNumElements()) {
386 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
387 baseType.getAsString(), SourceRange(CompLoc));
388 return QualType();
389 }
390 // The component names must come from the same set.
Chris Lattner88dca042007-08-02 22:33:49 +0000391 if (vecType->getPointAccessorIdx(*compStr) != -1) {
392 do
393 compStr++;
394 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
395 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
396 do
397 compStr++;
398 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
399 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
400 do
401 compStr++;
402 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
403 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000404
405 if (*compStr) {
406 // We didn't get to the end of the string. This means the component names
407 // didn't come from the same set *or* we encountered an illegal name.
408 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
409 std::string(compStr,compStr+1), SourceRange(CompLoc));
410 return QualType();
411 }
412 // Each component accessor can't exceed the vector type.
413 compStr = CompName.getName();
414 while (*compStr) {
415 if (vecType->isAccessorWithinNumElements(*compStr))
416 compStr++;
417 else
418 break;
419 }
420 if (*compStr) {
421 // We didn't get to the end of the string. This means a component accessor
422 // exceeds the number of elements in the vector.
423 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
424 baseType.getAsString(), SourceRange(CompLoc));
425 return QualType();
426 }
427 // The component accessor looks fine - now we need to compute the actual type.
428 // The vector type is implied by the component accessor. For example,
429 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
430 unsigned CompSize = strlen(CompName.getName());
431 if (CompSize == 1)
432 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000433
434 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
435 // Now look up the TypeDefDecl from the vector type. Without this,
436 // diagostics look bad. We want OCU vector types to appear built-in.
437 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
438 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
439 return Context.getTypedefType(OCUVectorDecls[i]);
440 }
441 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000442}
443
Reid Spencer5f016e22007-07-11 17:01:13 +0000444Action::ExprResult Sema::
445ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
446 tok::TokenKind OpKind, SourceLocation MemberLoc,
447 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000448 Expr *BaseExpr = static_cast<Expr *>(Base);
449 assert(BaseExpr && "no record expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000450
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000451 QualType BaseType = BaseExpr->getType();
452 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000453
Reid Spencer5f016e22007-07-11 17:01:13 +0000454 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000455 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000456 BaseType = PT->getPointeeType();
457 else
458 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
459 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000460 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000461 // The base type is either a record or an OCUVectorType.
Chris Lattnerc8629632007-07-31 19:29:30 +0000462 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000463 RecordDecl *RDecl = RTy->getDecl();
464 if (RTy->isIncompleteType())
465 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
466 BaseExpr->getSourceRange());
467 // The record definition is complete, now make sure the member is valid.
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000468 FieldDecl *MemberDecl = RDecl->getMember(&Member);
469 if (!MemberDecl)
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000470 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
471 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000472 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
473 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff608e0ee2007-08-03 22:40:33 +0000474 // Component access limited to variables (reject vec4.rg.g).
475 if (!isa<DeclRefExpr>(BaseExpr))
476 return Diag(OpLoc, diag::err_ocuvector_component_access,
477 SourceRange(MemberLoc));
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000478 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
479 if (ret.isNull())
480 return true;
Chris Lattner6481a572007-08-03 17:31:20 +0000481 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000482 } else
483 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
484 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000485}
486
487/// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
488/// This provides the location of the left/right parens and a list of comma
489/// locations.
490Action::ExprResult Sema::
Chris Lattner74c469f2007-07-21 03:03:59 +0000491ParseCallExpr(ExprTy *fn, SourceLocation LParenLoc,
492 ExprTy **args, unsigned NumArgsInCall,
Reid Spencer5f016e22007-07-11 17:01:13 +0000493 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000494 Expr *Fn = static_cast<Expr *>(fn);
495 Expr **Args = reinterpret_cast<Expr**>(args);
496 assert(Fn && "no function call expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000497
Chris Lattner74c469f2007-07-21 03:03:59 +0000498 UsualUnaryConversions(Fn);
499 QualType funcType = Fn->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000500
501 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
502 // type pointer to function".
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000503 const PointerType *PT = funcType->getAsPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000504 if (PT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000505 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
506 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000507
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000508 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 if (funcT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000510 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
511 SourceRange(Fn->getLocStart(), RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000512
513 // If a prototype isn't declared, the parser implicitly defines a func decl
514 QualType resultType = funcT->getResultType();
515
516 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
517 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
518 // assignment, to the types of the corresponding parameter, ...
519
520 unsigned NumArgsInProto = proto->getNumArgs();
521 unsigned NumArgsToCheck = NumArgsInCall;
522
523 if (NumArgsInCall < NumArgsInProto)
524 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
Chris Lattner74c469f2007-07-21 03:03:59 +0000525 Fn->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000526 else if (NumArgsInCall > NumArgsInProto) {
527 if (!proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +0000528 Diag(Args[NumArgsInProto]->getLocStart(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000529 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +0000530 SourceRange(Args[NumArgsInProto]->getLocStart(),
531 Args[NumArgsInCall-1]->getLocEnd()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000532 }
533 NumArgsToCheck = NumArgsInProto;
534 }
535 // Continue to check argument types (even if we have too few/many args).
536 for (unsigned i = 0; i < NumArgsToCheck; i++) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000537 Expr *argExpr = Args[i];
Reid Spencer5f016e22007-07-11 17:01:13 +0000538 assert(argExpr && "ParseCallExpr(): missing argument expression");
539
540 QualType lhsType = proto->getArgType(i);
541 QualType rhsType = argExpr->getType();
Steve Naroff700204c2007-07-24 21:46:40 +0000542
Steve Naroff82c7e6d2007-07-25 20:45:33 +0000543 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnerc8629632007-07-31 19:29:30 +0000544 if (const ArrayType *ary = lhsType->getAsArrayType())
Steve Naroff700204c2007-07-24 21:46:40 +0000545 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff82c7e6d2007-07-25 20:45:33 +0000546 else if (lhsType->isFunctionType())
Steve Naroff700204c2007-07-24 21:46:40 +0000547 lhsType = Context.getPointerType(lhsType);
548
Steve Naroff90045e82007-07-13 23:32:42 +0000549 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
550 argExpr);
Steve Narofff1120de2007-08-24 22:33:52 +0000551 if (Args[i] != argExpr) // The expression was converted.
552 Args[i] = argExpr; // Make sure we store the converted expression.
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 SourceLocation l = argExpr->getLocStart();
554
555 // decode the result (notice that AST's are still created for extensions).
556 switch (result) {
557 case Compatible:
558 break;
559 case PointerFromInt:
560 // check for null pointer constant (C99 6.3.2.3p3)
Chris Lattner590b6642007-07-15 23:26:56 +0000561 if (!argExpr->isNullPointerConstant(Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 Diag(l, diag::ext_typecheck_passing_pointer_int,
563 lhsType.getAsString(), rhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000564 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000565 }
566 break;
567 case IntFromPointer:
568 Diag(l, diag::ext_typecheck_passing_pointer_int,
569 lhsType.getAsString(), rhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000570 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000571 break;
572 case IncompatiblePointer:
573 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
574 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000575 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000576 break;
577 case CompatiblePointerDiscardsQualifiers:
578 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
579 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000580 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000581 break;
582 case Incompatible:
583 return Diag(l, diag::err_typecheck_passing_incompatible,
584 rhsType.getAsString(), lhsType.getAsString(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000585 Fn->getSourceRange(), argExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000586 }
587 }
Steve Naroffb291ab62007-08-28 23:30:39 +0000588 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
589 // Promote the arguments (C99 6.5.2.2p7).
590 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
591 Expr *argExpr = Args[i];
592 assert(argExpr && "ParseCallExpr(): missing argument expression");
593
594 DefaultArgumentPromotion(argExpr);
595 if (Args[i] != argExpr) // The expression was converted.
596 Args[i] = argExpr; // Make sure we store the converted expression.
597 }
598 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
599 // Even if the types checked, bail if the number of arguments don't match.
Reid Spencer5f016e22007-07-11 17:01:13 +0000600 return true;
Steve Naroffb291ab62007-08-28 23:30:39 +0000601 }
602 } else if (isa<FunctionTypeNoProto>(funcT)) {
603 // Promote the arguments (C99 6.5.2.2p6).
604 for (unsigned i = 0; i < NumArgsInCall; i++) {
605 Expr *argExpr = Args[i];
606 assert(argExpr && "ParseCallExpr(): missing argument expression");
607
608 DefaultArgumentPromotion(argExpr);
609 if (Args[i] != argExpr) // The expression was converted.
610 Args[i] = argExpr; // Make sure we store the converted expression.
611 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000612 }
Chris Lattner59907c42007-08-10 20:18:51 +0000613 // Do special checking on direct calls to functions.
614 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
615 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
616 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000617 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args, NumArgsInCall))
Anders Carlsson71993dd2007-08-17 05:31:46 +0000618 return true;
Chris Lattner59907c42007-08-10 20:18:51 +0000619
Chris Lattner74c469f2007-07-21 03:03:59 +0000620 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000621}
622
623Action::ExprResult Sema::
Steve Naroff4aa88f82007-07-19 01:06:55 +0000624ParseCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +0000625 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff4aa88f82007-07-19 01:06:55 +0000626 assert((Ty != 0) && "ParseCompoundLiteral(): missing type");
627 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +0000628 // FIXME: put back this assert when initializers are worked out.
629 //assert((InitExpr != 0) && "ParseCompoundLiteral(): missing expression");
630 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000631
632 // FIXME: add semantic analysis (C99 6.5.2.5).
Steve Naroffaff1edd2007-07-19 21:32:11 +0000633 return new CompoundLiteralExpr(literalType, literalExpr);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000634}
635
636Action::ExprResult Sema::
637ParseInitList(SourceLocation LParenLoc, ExprTy **InitList, unsigned NumInit,
638 SourceLocation RParenLoc) {
639 // FIXME: add semantic analysis (C99 6.7.8). This involves
640 // knowledge of the object being intialized. As a result, the code for
641 // doing the semantic analysis will likely be located elsewhere (i.e. in
642 // consumers of InitListExpr (e.g. ParseDeclarator, ParseCompoundLiteral).
643 return false; // FIXME instantiate an InitListExpr.
644}
645
646Action::ExprResult Sema::
Reid Spencer5f016e22007-07-11 17:01:13 +0000647ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
648 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff16beff82007-07-16 23:25:18 +0000649 assert((Ty != 0) && (Op != 0) && "ParseCastExpr(): missing type or expr");
650
651 Expr *castExpr = static_cast<Expr*>(Op);
652 QualType castType = QualType::getFromOpaquePtr(Ty);
653
Chris Lattner75af4802007-07-18 16:00:06 +0000654 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
655 // type needs to be scalar.
656 if (!castType->isScalarType() && !castType->isVoidType()) {
Steve Naroff16beff82007-07-16 23:25:18 +0000657 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
658 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
659 }
660 if (!castExpr->getType()->isScalarType()) {
661 return Diag(castExpr->getLocStart(),
662 diag::err_typecheck_expect_scalar_operand,
663 castExpr->getType().getAsString(), castExpr->getSourceRange());
664 }
665 return new CastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000666}
667
668inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +0000669 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000670 UsualUnaryConversions(cond);
671 UsualUnaryConversions(lex);
672 UsualUnaryConversions(rex);
673 QualType condT = cond->getType();
674 QualType lexT = lex->getType();
675 QualType rexT = rex->getType();
676
Reid Spencer5f016e22007-07-11 17:01:13 +0000677 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +0000678 if (!condT->isScalarType()) { // C99 6.5.15p2
679 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
680 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +0000681 return QualType();
682 }
683 // now check the two expressions.
Steve Naroffa4332e22007-07-17 00:58:39 +0000684 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
685 UsualArithmeticConversions(lex, rex);
686 return lex->getType();
687 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000688 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
689 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
690
691 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
692 return lexT;
693
Reid Spencer5f016e22007-07-11 17:01:13 +0000694 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000695 lexT.getAsString(), rexT.getAsString(),
696 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 return QualType();
698 }
699 }
Chris Lattner590b6642007-07-15 23:26:56 +0000700 // C99 6.5.15p3
701 if (lexT->isPointerType() && rex->isNullPointerConstant(Context))
Steve Naroff49b45262007-07-13 16:58:59 +0000702 return lexT;
Chris Lattner590b6642007-07-15 23:26:56 +0000703 if (rexT->isPointerType() && lex->isNullPointerConstant(Context))
Steve Naroff49b45262007-07-13 16:58:59 +0000704 return rexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000705
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000706 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
707 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
708 // get the "pointed to" types
709 QualType lhptee = LHSPT->getPointeeType();
710 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000711
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000712 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
713 if (lhptee->isVoidType() &&
714 (rhptee->isObjectType() || rhptee->isIncompleteType()))
715 return lexT;
716 if (rhptee->isVoidType() &&
717 (lhptee->isObjectType() || lhptee->isIncompleteType()))
718 return rexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000719
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000720 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
721 rhptee.getUnqualifiedType())) {
722 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
723 lexT.getAsString(), rexT.getAsString(),
724 lex->getSourceRange(), rex->getSourceRange());
725 return lexT; // FIXME: this is an _ext - is this return o.k?
726 }
727 // The pointer types are compatible.
728 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
729 // differently qualified versions of compatible types, the result type is a
730 // pointer to an appropriately qualified version of the *composite* type.
731 return lexT; // FIXME: Need to return the composite type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000732 }
733 }
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000734
Steve Naroff49b45262007-07-13 16:58:59 +0000735 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
736 return lexT;
Reid Spencer5f016e22007-07-11 17:01:13 +0000737
738 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +0000739 lexT.getAsString(), rexT.getAsString(),
740 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000741 return QualType();
742}
743
744/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
745/// in the case of a the GNU conditional expr extension.
746Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
747 SourceLocation ColonLoc,
748 ExprTy *Cond, ExprTy *LHS,
749 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +0000750 Expr *CondExpr = (Expr *) Cond;
751 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
752 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
753 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000754 if (result.isNull())
755 return true;
Chris Lattner26824902007-07-16 21:39:03 +0000756 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000757}
758
Steve Narofffa2eaab2007-07-15 02:02:06 +0000759// promoteExprToType - a helper function to ensure we create exactly one
760// ImplicitCastExpr. As a convenience (to the caller), we return the type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000761static void promoteExprToType(Expr *&expr, QualType type) {
Steve Narofffa2eaab2007-07-15 02:02:06 +0000762 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
763 impCast->setType(type);
764 else
765 expr = new ImplicitCastExpr(type, expr);
Steve Naroffa4332e22007-07-17 00:58:39 +0000766 return;
Steve Narofffa2eaab2007-07-15 02:02:06 +0000767}
768
Steve Naroffb291ab62007-08-28 23:30:39 +0000769/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
770/// do not have a prototype. Integer promotions are performed on each
771/// argument, and arguments that have type float are promoted to double.
772void Sema::DefaultArgumentPromotion(Expr *&expr) {
773 QualType t = expr->getType();
774 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
775
776 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
777 promoteExprToType(expr, Context.IntTy);
778 if (t == Context.FloatTy)
779 promoteExprToType(expr, Context.DoubleTy);
780}
781
Steve Narofffa2eaab2007-07-15 02:02:06 +0000782/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000783void Sema::DefaultFunctionArrayConversion(Expr *&e) {
Steve Narofffa2eaab2007-07-15 02:02:06 +0000784 QualType t = e->getType();
Steve Naroff90045e82007-07-13 23:32:42 +0000785 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
Bill Wendling08ad47c2007-07-17 03:52:31 +0000786
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000787 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000788 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
789 t = e->getType();
790 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000791 if (t->isFunctionType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000792 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnerc8629632007-07-31 19:29:30 +0000793 else if (const ArrayType *ary = t->getAsArrayType())
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000794 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000795}
796
797/// UsualUnaryConversion - Performs various conversions that are common to most
798/// operators (C99 6.3). The conversions of array and function types are
799/// sometimes surpressed. For example, the array->pointer conversion doesn't
800/// apply if the array is an argument to the sizeof or address (&) operators.
801/// In these instances, this routine should *not* be called.
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000802void Sema::UsualUnaryConversions(Expr *&expr) {
Steve Naroff49b45262007-07-13 16:58:59 +0000803 QualType t = expr->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000804 assert(!t.isNull() && "UsualUnaryConversions - missing type");
805
Chris Lattnera1d9fde2007-07-31 16:56:34 +0000806 if (const ReferenceType *ref = t->getAsReferenceType()) {
Bill Wendlingea5e79f2007-07-17 04:16:47 +0000807 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
808 t = expr->getType();
809 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000810 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000811 promoteExprToType(expr, Context.IntTy);
812 else
813 DefaultFunctionArrayConversion(expr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000814}
815
816/// UsualArithmeticConversions - Performs various conversions that are common to
817/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
818/// routine returns the first non-arithmetic type found. The client is
819/// responsible for emitting appropriate error diagnostics.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000820QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
821 bool isCompAssign) {
Steve Naroff8702a0f2007-08-25 19:54:59 +0000822 if (!isCompAssign) {
823 UsualUnaryConversions(lhsExpr);
824 UsualUnaryConversions(rhsExpr);
825 }
Steve Naroff3e5e5562007-07-16 22:23:01 +0000826 QualType lhs = lhsExpr->getType();
827 QualType rhs = rhsExpr->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000828
829 // If both types are identical, no conversion is needed.
830 if (lhs == rhs)
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000831 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000832
833 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
834 // The caller can deal with this (e.g. pointer + int).
Steve Naroffa4332e22007-07-17 00:58:39 +0000835 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000836 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000837
838 // At this point, we have two different arithmetic types.
839
840 // Handle complex types first (C99 6.3.1.8p1).
841 if (lhs->isComplexType() || rhs->isComplexType()) {
842 // if we have an integer operand, the result is the complex type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000843 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000844 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
845 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000846 }
847 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000848 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
849 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000850 }
Steve Narofff1448a02007-08-27 01:27:54 +0000851 // This handles complex/complex, complex/float, or float/complex.
852 // When both operands are complex, the shorter operand is converted to the
853 // type of the longer, and that is the type of the result. This corresponds
854 // to what is done when combining two real floating-point operands.
855 // The fun begins when size promotion occur across type domains.
856 // From H&S 6.3.4: When one operand is complex and the other is a real
857 // floating-point type, the less precise type is converted, within it's
858 // real or complex domain, to the precision of the other type. For example,
859 // when combining a "long double" with a "double _Complex", the
860 // "double _Complex" is promoted to "long double _Complex".
Steve Narofffb0d4962007-08-27 15:30:22 +0000861 int result = Context.compareFloatingType(lhs, rhs);
862
863 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff55fe4552007-08-27 21:32:55 +0000864 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
865 if (!isCompAssign)
866 promoteExprToType(rhsExpr, rhs);
867 } else if (result < 0) { // The right side is bigger, convert lhs.
868 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
869 if (!isCompAssign)
870 promoteExprToType(lhsExpr, lhs);
871 }
872 // At this point, lhs and rhs have the same rank/size. Now, make sure the
873 // domains match. This is a requirement for our implementation, C99
874 // does not require this promotion.
875 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
876 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff29960362007-08-27 21:43:43 +0000877 if (!isCompAssign)
878 promoteExprToType(lhsExpr, rhs);
879 return rhs;
Steve Naroff55fe4552007-08-27 21:32:55 +0000880 } else { // handle "_Complex double, double".
Steve Naroff29960362007-08-27 21:43:43 +0000881 if (!isCompAssign)
882 promoteExprToType(rhsExpr, lhs);
883 return lhs;
Steve Naroff55fe4552007-08-27 21:32:55 +0000884 }
Steve Naroffa4332e22007-07-17 00:58:39 +0000885 }
Steve Naroff29960362007-08-27 21:43:43 +0000886 return lhs; // The domain/size match exactly.
Reid Spencer5f016e22007-07-11 17:01:13 +0000887 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000888 // Now handle "real" floating types (i.e. float, double, long double).
889 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
890 // if we have an integer operand, the result is the real floating type.
Steve Naroffa4332e22007-07-17 00:58:39 +0000891 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000892 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
893 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000894 }
895 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000896 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
897 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000898 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000899 // We have two real floating types, float/complex combos were handled above.
900 // Convert the smaller operand to the bigger result.
Steve Narofffb0d4962007-08-27 15:30:22 +0000901 int result = Context.compareFloatingType(lhs, rhs);
902
903 if (result > 0) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000904 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
905 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000906 }
Steve Narofffb0d4962007-08-27 15:30:22 +0000907 if (result < 0) { // convert the lhs
908 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
909 return rhs;
910 }
911 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Reid Spencer5f016e22007-07-11 17:01:13 +0000912 }
Steve Narofffa2eaab2007-07-15 02:02:06 +0000913 // Finally, we have two differing integer types.
Steve Naroffa4332e22007-07-17 00:58:39 +0000914 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000915 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
916 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +0000917 }
Steve Naroff9f5fa9b2007-08-24 19:07:16 +0000918 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
919 return rhs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000920}
921
922// CheckPointerTypesForAssignment - This is a very tricky routine (despite
923// being closely modeled after the C99 spec:-). The odd characteristic of this
924// routine is it effectively iqnores the qualifiers on the top level pointee.
925// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
926// FIXME: add a couple examples in this comment.
927Sema::AssignmentCheckResult
928Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
929 QualType lhptee, rhptee;
930
931 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000932 lhptee = lhsType->getAsPointerType()->getPointeeType();
933 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000934
935 // make sure we operate on the canonical type
936 lhptee = lhptee.getCanonicalType();
937 rhptee = rhptee.getCanonicalType();
938
939 AssignmentCheckResult r = Compatible;
940
941 // C99 6.5.16.1p1: This following citation is common to constraints
942 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
943 // qualifiers of the type *pointed to* by the right;
944 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
945 rhptee.getQualifiers())
946 r = CompatiblePointerDiscardsQualifiers;
947
948 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
949 // incomplete type and the other is a pointer to a qualified or unqualified
950 // version of void...
951 if (lhptee.getUnqualifiedType()->isVoidType() &&
952 (rhptee->isObjectType() || rhptee->isIncompleteType()))
953 ;
954 else if (rhptee.getUnqualifiedType()->isVoidType() &&
955 (lhptee->isObjectType() || lhptee->isIncompleteType()))
956 ;
957 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
958 // unqualified versions of compatible types, ...
959 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
960 rhptee.getUnqualifiedType()))
961 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
962 return r;
963}
964
965/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
966/// has code to accommodate several GCC extensions when type checking
967/// pointers. Here are some objectionable examples that GCC considers warnings:
968///
969/// int a, *pint;
970/// short *pshort;
971/// struct foo *pfoo;
972///
973/// pint = pshort; // warning: assignment from incompatible pointer type
974/// a = pint; // warning: assignment makes integer from pointer without a cast
975/// pint = a; // warning: assignment makes pointer from integer without a cast
976/// pint = pfoo; // warning: assignment from incompatible pointer type
977///
978/// As a result, the code for dealing with pointers is more complex than the
979/// C99 spec dictates.
980/// Note: the warning above turn into errors when -pedantic-errors is enabled.
981///
982Sema::AssignmentCheckResult
983Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Steve Naroff700204c2007-07-24 21:46:40 +0000984 if (lhsType == rhsType) // common case, fast path...
985 return Compatible;
986
Reid Spencer5f016e22007-07-11 17:01:13 +0000987 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
988 if (lhsType->isVectorType() || rhsType->isVectorType()) {
989 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
990 return Incompatible;
991 }
992 return Compatible;
993 } else if (lhsType->isPointerType()) {
994 if (rhsType->isIntegerType())
995 return PointerFromInt;
996
997 if (rhsType->isPointerType())
998 return CheckPointerTypesForAssignment(lhsType, rhsType);
999 } else if (rhsType->isPointerType()) {
1000 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1001 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1002 return IntFromPointer;
1003
1004 if (lhsType->isPointerType())
1005 return CheckPointerTypesForAssignment(lhsType, rhsType);
1006 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
1007 if (Type::tagTypesAreCompatible(lhsType, rhsType))
1008 return Compatible;
1009 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
1010 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
1011 return Compatible;
1012 }
1013 return Incompatible;
1014}
1015
Steve Naroff90045e82007-07-13 23:32:42 +00001016Sema::AssignmentCheckResult
1017Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
1018 // This check seems unnatural, however it is necessary to insure the proper
1019 // conversion of functions/arrays. If the conversion were done for all
1020 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
1021 // expressions that surpress this implicit conversion (&, sizeof).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001022 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001023
1024 Sema::AssignmentCheckResult result;
Steve Naroff90045e82007-07-13 23:32:42 +00001025
Steve Narofff1120de2007-08-24 22:33:52 +00001026 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1027
1028 // C99 6.5.16.1p2: The value of the right operand is converted to the
1029 // type of the assignment expression.
1030 if (rExpr->getType() != lhsType)
1031 promoteExprToType(rExpr, lhsType);
1032 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001033}
1034
1035Sema::AssignmentCheckResult
1036Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1037 return CheckAssignmentConstraints(lhsType, rhsType);
1038}
1039
Steve Naroff49b45262007-07-13 16:58:59 +00001040inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001041 Diag(loc, diag::err_typecheck_invalid_operands,
1042 lex->getType().getAsString(), rex->getType().getAsString(),
1043 lex->getSourceRange(), rex->getSourceRange());
1044}
1045
Steve Naroff49b45262007-07-13 16:58:59 +00001046inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1047 Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001048 QualType lhsType = lex->getType(), rhsType = rex->getType();
1049
1050 // make sure the vector types are identical.
1051 if (lhsType == rhsType)
1052 return lhsType;
1053 // You cannot convert between vector values of different size.
1054 Diag(loc, diag::err_typecheck_vector_not_convertable,
1055 lex->getType().getAsString(), rex->getType().getAsString(),
1056 lex->getSourceRange(), rex->getSourceRange());
1057 return QualType();
1058}
1059
1060inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001061 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001062{
Steve Naroff90045e82007-07-13 23:32:42 +00001063 QualType lhsType = lex->getType(), rhsType = rex->getType();
1064
1065 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001066 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001067
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001068 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001069
Steve Naroffa4332e22007-07-17 00:58:39 +00001070 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001071 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001072 InvalidOperands(loc, lex, rex);
1073 return QualType();
1074}
1075
1076inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001077 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001078{
Steve Naroff90045e82007-07-13 23:32:42 +00001079 QualType lhsType = lex->getType(), rhsType = rex->getType();
1080
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001081 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001082
Steve Naroffa4332e22007-07-17 00:58:39 +00001083 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001084 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001085 InvalidOperands(loc, lex, rex);
1086 return QualType();
1087}
1088
1089inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001090 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001091{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001092 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001093 return CheckVectorOperands(loc, lex, rex);
1094
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001095 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Steve Naroff3e5e5562007-07-16 22:23:01 +00001096
Reid Spencer5f016e22007-07-11 17:01:13 +00001097 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001098 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001099 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001100
Steve Naroffa4332e22007-07-17 00:58:39 +00001101 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1102 return lex->getType();
1103 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1104 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001105 InvalidOperands(loc, lex, rex);
1106 return QualType();
1107}
1108
1109inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001110 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001111{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001112 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001113 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001114
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001115 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001116
1117 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001118 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001119 return compType;
Steve Naroff3e5e5562007-07-16 22:23:01 +00001120
1121 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001122 return compType;
Steve Naroff3e5e5562007-07-16 22:23:01 +00001123 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
Chris Lattner8b9023b2007-07-13 03:05:23 +00001124 return Context.getPointerDiffType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001125 InvalidOperands(loc, lex, rex);
1126 return QualType();
1127}
1128
1129inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001130 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001131{
1132 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1133 // for int << longlong -> the result type should be int, not long long.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001134 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001135
Steve Naroffa4332e22007-07-17 00:58:39 +00001136 // handle the common case first (both operands are arithmetic).
1137 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001138 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001139 InvalidOperands(loc, lex, rex);
1140 return QualType();
1141}
1142
Chris Lattnera5937dd2007-08-26 01:18:55 +00001143inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1144 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Reid Spencer5f016e22007-07-11 17:01:13 +00001145{
Chris Lattnera5937dd2007-08-26 01:18:55 +00001146 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00001147 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1148 UsualArithmeticConversions(lex, rex);
1149 else {
1150 UsualUnaryConversions(lex);
1151 UsualUnaryConversions(rex);
1152 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001153 QualType lType = lex->getType();
1154 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001155
Chris Lattnera5937dd2007-08-26 01:18:55 +00001156 if (isRelational) {
1157 if (lType->isRealType() && rType->isRealType())
1158 return Context.IntTy;
1159 } else {
1160 if (lType->isArithmeticType() && rType->isArithmeticType())
1161 return Context.IntTy;
1162 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001163
Chris Lattnerd28f8152007-08-26 01:10:14 +00001164 bool LHSIsNull = lex->isNullPointerConstant(Context);
1165 bool RHSIsNull = rex->isNullPointerConstant(Context);
1166
Chris Lattnera5937dd2007-08-26 01:18:55 +00001167 // All of the following pointer related warnings are GCC extensions, except
1168 // when handling null pointer constants. One day, we can consider making them
1169 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00001170 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerd28f8152007-08-26 01:10:14 +00001171 if (!LHSIsNull && !RHSIsNull &&
Steve Naroff77878cc2007-08-27 04:08:11 +00001172 !Type::pointerTypesAreCompatible(lType.getUnqualifiedType(),
1173 rType.getUnqualifiedType())) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001174 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1175 lType.getAsString(), rType.getAsString(),
1176 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001177 }
Chris Lattnerd28f8152007-08-26 01:10:14 +00001178 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001179 return Context.IntTy;
1180 }
1181 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001182 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001183 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1184 lType.getAsString(), rType.getAsString(),
1185 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001186 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001187 return Context.IntTy;
1188 }
1189 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001190 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001191 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1192 lType.getAsString(), rType.getAsString(),
1193 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerd28f8152007-08-26 01:10:14 +00001194 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001195 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001196 }
1197 InvalidOperands(loc, lex, rex);
1198 return QualType();
1199}
1200
Reid Spencer5f016e22007-07-11 17:01:13 +00001201inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001202 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001203{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001204 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001206
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001207 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001208
Steve Naroffa4332e22007-07-17 00:58:39 +00001209 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001210 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001211 InvalidOperands(loc, lex, rex);
1212 return QualType();
1213}
1214
1215inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00001216 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001217{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001218 UsualUnaryConversions(lex);
1219 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001220
Steve Naroffa4332e22007-07-17 00:58:39 +00001221 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001222 return Context.IntTy;
1223 InvalidOperands(loc, lex, rex);
1224 return QualType();
1225}
1226
1227inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00001228 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001229{
1230 QualType lhsType = lex->getType();
1231 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1232 bool hadError = false;
1233 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1234
1235 switch (mlval) { // C99 6.5.16p2
1236 case Expr::MLV_Valid:
1237 break;
1238 case Expr::MLV_ConstQualified:
1239 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1240 hadError = true;
1241 break;
1242 case Expr::MLV_ArrayType:
1243 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1244 lhsType.getAsString(), lex->getSourceRange());
1245 return QualType();
1246 case Expr::MLV_NotObjectType:
1247 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1248 lhsType.getAsString(), lex->getSourceRange());
1249 return QualType();
1250 case Expr::MLV_InvalidExpression:
1251 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1252 lex->getSourceRange());
1253 return QualType();
1254 case Expr::MLV_IncompleteType:
1255 case Expr::MLV_IncompleteVoidType:
1256 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1257 lhsType.getAsString(), lex->getSourceRange());
1258 return QualType();
Steve Narofffec0b492007-07-30 03:29:09 +00001259 case Expr::MLV_DuplicateVectorComponents:
1260 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1261 lex->getSourceRange());
1262 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 }
Steve Naroff90045e82007-07-13 23:32:42 +00001264 AssignmentCheckResult result;
1265
1266 if (compoundType.isNull())
1267 result = CheckSingleAssignmentConstraints(lhsType, rex);
1268 else
1269 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001270
Reid Spencer5f016e22007-07-11 17:01:13 +00001271 // decode the result (notice that extensions still return a type).
1272 switch (result) {
1273 case Compatible:
1274 break;
1275 case Incompatible:
1276 Diag(loc, diag::err_typecheck_assign_incompatible,
1277 lhsType.getAsString(), rhsType.getAsString(),
1278 lex->getSourceRange(), rex->getSourceRange());
1279 hadError = true;
1280 break;
1281 case PointerFromInt:
1282 // check for null pointer constant (C99 6.3.2.3p3)
Chris Lattner590b6642007-07-15 23:26:56 +00001283 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001284 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1285 lhsType.getAsString(), rhsType.getAsString(),
1286 lex->getSourceRange(), rex->getSourceRange());
1287 }
1288 break;
1289 case IntFromPointer:
1290 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1291 lhsType.getAsString(), rhsType.getAsString(),
1292 lex->getSourceRange(), rex->getSourceRange());
1293 break;
1294 case IncompatiblePointer:
1295 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1296 lhsType.getAsString(), rhsType.getAsString(),
1297 lex->getSourceRange(), rex->getSourceRange());
1298 break;
1299 case CompatiblePointerDiscardsQualifiers:
1300 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1301 lhsType.getAsString(), rhsType.getAsString(),
1302 lex->getSourceRange(), rex->getSourceRange());
1303 break;
1304 }
1305 // C99 6.5.16p3: The type of an assignment expression is the type of the
1306 // left operand unless the left operand has qualified type, in which case
1307 // it is the unqualified version of the type of the left operand.
1308 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1309 // is converted to the type of the assignment expression (above).
1310 // C++ 5.17p1: the type of the assignment expression is that of its left oprdu.
1311 return hadError ? QualType() : lhsType.getUnqualifiedType();
1312}
1313
1314inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00001315 Expr *&lex, Expr *&rex, SourceLocation loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001316 UsualUnaryConversions(rex);
1317 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001318}
1319
Steve Naroff49b45262007-07-13 16:58:59 +00001320/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1321/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00001322QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00001323 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001324 assert(!resType.isNull() && "no type for increment/decrement expression");
1325
Steve Naroff084f9ed2007-08-24 17:20:07 +00001326 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Reid Spencer5f016e22007-07-11 17:01:13 +00001327 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1328 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1329 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1330 resType.getAsString(), op->getSourceRange());
1331 return QualType();
1332 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00001333 } else if (!resType->isRealType()) {
1334 if (resType->isComplexType())
1335 // C99 does not support ++/-- on complex types.
1336 Diag(OpLoc, diag::ext_integer_increment_complex,
1337 resType.getAsString(), op->getSourceRange());
1338 else {
1339 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1340 resType.getAsString(), op->getSourceRange());
1341 return QualType();
1342 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001343 }
Steve Naroffdd10e022007-08-23 21:37:33 +00001344 // At this point, we know we have a real, complex or pointer type.
1345 // Now make sure the operand is a modifiable lvalue.
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1347 if (mlval != Expr::MLV_Valid) {
1348 // FIXME: emit a more precise diagnostic...
1349 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1350 op->getSourceRange());
1351 return QualType();
1352 }
1353 return resType;
1354}
1355
1356/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1357/// This routine allows us to typecheck complex/recursive expressions
1358/// where the declaration is needed for type checking. Here are some
1359/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1360static Decl *getPrimaryDeclaration(Expr *e) {
1361 switch (e->getStmtClass()) {
1362 case Stmt::DeclRefExprClass:
1363 return cast<DeclRefExpr>(e)->getDecl();
1364 case Stmt::MemberExprClass:
1365 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1366 case Stmt::ArraySubscriptExprClass:
1367 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1368 case Stmt::CallExprClass:
1369 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1370 case Stmt::UnaryOperatorClass:
1371 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1372 case Stmt::ParenExprClass:
1373 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1374 default:
1375 return 0;
1376 }
1377}
1378
1379/// CheckAddressOfOperand - The operand of & must be either a function
1380/// designator or an lvalue designating an object. If it is an lvalue, the
1381/// object cannot be declared with storage class register or be a bit field.
1382/// Note: The usual conversions are *not* applied to the operand of the &
1383/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1384QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1385 Decl *dcl = getPrimaryDeclaration(op);
1386 Expr::isLvalueResult lval = op->isLvalue();
1387
1388 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1389 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1390 ;
1391 else { // FIXME: emit more specific diag...
1392 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1393 op->getSourceRange());
1394 return QualType();
1395 }
1396 } else if (dcl) {
1397 // We have an lvalue with a decl. Make sure the decl is not declared
1398 // with the register storage-class specifier.
1399 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1400 if (vd->getStorageClass() == VarDecl::Register) {
1401 Diag(OpLoc, diag::err_typecheck_address_of_register,
1402 op->getSourceRange());
1403 return QualType();
1404 }
1405 } else
1406 assert(0 && "Unknown/unexpected decl type");
1407
1408 // FIXME: add check for bitfields!
1409 }
1410 // If the operand has type "type", the result has type "pointer to type".
1411 return Context.getPointerType(op->getType());
1412}
1413
1414QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001415 UsualUnaryConversions(op);
1416 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001417
Chris Lattnerbefee482007-07-31 16:53:04 +00001418 if (const PointerType *PT = qType->getAsPointerType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001419 QualType ptype = PT->getPointeeType();
1420 // C99 6.5.3.2p4. "if it points to an object,...".
1421 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1422 // GCC compat: special case 'void *' (treat as warning).
1423 if (ptype->isVoidType()) {
1424 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1425 qType.getAsString(), op->getSourceRange());
1426 } else {
1427 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1428 ptype.getAsString(), op->getSourceRange());
1429 return QualType();
1430 }
1431 }
1432 return ptype;
1433 }
1434 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1435 qType.getAsString(), op->getSourceRange());
1436 return QualType();
1437}
1438
1439static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1440 tok::TokenKind Kind) {
1441 BinaryOperator::Opcode Opc;
1442 switch (Kind) {
1443 default: assert(0 && "Unknown binop!");
1444 case tok::star: Opc = BinaryOperator::Mul; break;
1445 case tok::slash: Opc = BinaryOperator::Div; break;
1446 case tok::percent: Opc = BinaryOperator::Rem; break;
1447 case tok::plus: Opc = BinaryOperator::Add; break;
1448 case tok::minus: Opc = BinaryOperator::Sub; break;
1449 case tok::lessless: Opc = BinaryOperator::Shl; break;
1450 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1451 case tok::lessequal: Opc = BinaryOperator::LE; break;
1452 case tok::less: Opc = BinaryOperator::LT; break;
1453 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1454 case tok::greater: Opc = BinaryOperator::GT; break;
1455 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1456 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1457 case tok::amp: Opc = BinaryOperator::And; break;
1458 case tok::caret: Opc = BinaryOperator::Xor; break;
1459 case tok::pipe: Opc = BinaryOperator::Or; break;
1460 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1461 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1462 case tok::equal: Opc = BinaryOperator::Assign; break;
1463 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1464 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1465 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1466 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1467 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1468 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1469 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1470 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1471 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1472 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1473 case tok::comma: Opc = BinaryOperator::Comma; break;
1474 }
1475 return Opc;
1476}
1477
1478static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1479 tok::TokenKind Kind) {
1480 UnaryOperator::Opcode Opc;
1481 switch (Kind) {
1482 default: assert(0 && "Unknown unary op!");
1483 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1484 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1485 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1486 case tok::star: Opc = UnaryOperator::Deref; break;
1487 case tok::plus: Opc = UnaryOperator::Plus; break;
1488 case tok::minus: Opc = UnaryOperator::Minus; break;
1489 case tok::tilde: Opc = UnaryOperator::Not; break;
1490 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1491 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1492 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1493 case tok::kw___real: Opc = UnaryOperator::Real; break;
1494 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1495 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1496 }
1497 return Opc;
1498}
1499
1500// Binary Operators. 'Tok' is the token for the operator.
1501Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1502 ExprTy *LHS, ExprTy *RHS) {
1503 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1504 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1505
1506 assert((lhs != 0) && "ParseBinOp(): missing left expression");
1507 assert((rhs != 0) && "ParseBinOp(): missing right expression");
1508
1509 QualType ResultTy; // Result type of the binary operator.
1510 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1511
1512 switch (Opc) {
1513 default:
1514 assert(0 && "Unknown binary expr!");
1515 case BinaryOperator::Assign:
1516 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1517 break;
1518 case BinaryOperator::Mul:
1519 case BinaryOperator::Div:
1520 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1521 break;
1522 case BinaryOperator::Rem:
1523 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1524 break;
1525 case BinaryOperator::Add:
1526 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1527 break;
1528 case BinaryOperator::Sub:
1529 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1530 break;
1531 case BinaryOperator::Shl:
1532 case BinaryOperator::Shr:
1533 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1534 break;
1535 case BinaryOperator::LE:
1536 case BinaryOperator::LT:
1537 case BinaryOperator::GE:
1538 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001539 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 break;
1541 case BinaryOperator::EQ:
1542 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00001543 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001544 break;
1545 case BinaryOperator::And:
1546 case BinaryOperator::Xor:
1547 case BinaryOperator::Or:
1548 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1549 break;
1550 case BinaryOperator::LAnd:
1551 case BinaryOperator::LOr:
1552 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1553 break;
1554 case BinaryOperator::MulAssign:
1555 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001556 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 if (!CompTy.isNull())
1558 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1559 break;
1560 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001561 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001562 if (!CompTy.isNull())
1563 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1564 break;
1565 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001566 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 if (!CompTy.isNull())
1568 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1569 break;
1570 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001571 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 if (!CompTy.isNull())
1573 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1574 break;
1575 case BinaryOperator::ShlAssign:
1576 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001577 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 if (!CompTy.isNull())
1579 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1580 break;
1581 case BinaryOperator::AndAssign:
1582 case BinaryOperator::XorAssign:
1583 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001584 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 if (!CompTy.isNull())
1586 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1587 break;
1588 case BinaryOperator::Comma:
1589 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1590 break;
1591 }
1592 if (ResultTy.isNull())
1593 return true;
1594 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001595 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00001597 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001598}
1599
1600// Unary Operators. 'Tok' is the token for the operator.
1601Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1602 ExprTy *input) {
1603 Expr *Input = (Expr*)input;
1604 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1605 QualType resultType;
1606 switch (Opc) {
1607 default:
1608 assert(0 && "Unimplemented unary expr!");
1609 case UnaryOperator::PreInc:
1610 case UnaryOperator::PreDec:
1611 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1612 break;
1613 case UnaryOperator::AddrOf:
1614 resultType = CheckAddressOfOperand(Input, OpLoc);
1615 break;
1616 case UnaryOperator::Deref:
1617 resultType = CheckIndirectionOperand(Input, OpLoc);
1618 break;
1619 case UnaryOperator::Plus:
1620 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001621 UsualUnaryConversions(Input);
1622 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001623 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1624 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1625 resultType.getAsString());
1626 break;
1627 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001628 UsualUnaryConversions(Input);
1629 resultType = Input->getType();
Steve Naroff084f9ed2007-08-24 17:20:07 +00001630 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1631 if (!resultType->isIntegerType()) {
1632 if (resultType->isComplexType())
1633 // C99 does not support '~' for complex conjugation.
1634 Diag(OpLoc, diag::ext_integer_complement_complex,
1635 resultType.getAsString());
1636 else
1637 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1638 resultType.getAsString());
1639 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 break;
1641 case UnaryOperator::LNot: // logical negation
1642 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001643 DefaultFunctionArrayConversion(Input);
1644 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1646 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1647 resultType.getAsString());
1648 // LNot always has type int. C99 6.5.3.3p5.
1649 resultType = Context.IntTy;
1650 break;
1651 case UnaryOperator::SizeOf:
1652 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1653 break;
1654 case UnaryOperator::AlignOf:
1655 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1656 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00001657 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00001658 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00001659 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00001660 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001661 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00001662 resultType = Input->getType();
1663 break;
1664 }
1665 if (resultType.isNull())
1666 return true;
1667 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1668}
1669
1670/// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
1671Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
1672 SourceLocation LabLoc,
1673 IdentifierInfo *LabelII) {
1674 // Look up the record for this label identifier.
1675 LabelStmt *&LabelDecl = LabelMap[LabelII];
1676
1677 // If we haven't seen this label yet, create a forward reference.
1678 if (LabelDecl == 0)
1679 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1680
1681 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00001682 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1683 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001684}
1685
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001686Sema::ExprResult Sema::ParseStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
1687 SourceLocation RPLoc) { // "({..})"
1688 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1689 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1690 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1691
1692 // FIXME: there are a variety of strange constraints to enforce here, for
1693 // example, it is not possible to goto into a stmt expression apparently.
1694 // More semantic analysis is needed.
1695
1696 // FIXME: the last statement in the compount stmt has its value used. We
1697 // should not warn about it being unused.
1698
1699 // If there are sub stmts in the compound stmt, take the type of the last one
1700 // as the type of the stmtexpr.
1701 QualType Ty = Context.VoidTy;
1702
1703 if (!Compound->body_empty())
1704 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1705 Ty = LastExpr->getType();
1706
1707 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1708}
Steve Naroffd34e9152007-08-01 22:05:33 +00001709
Steve Naroff363bcff2007-08-01 23:45:51 +00001710Sema::ExprResult Sema::ParseTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00001711 TypeTy *arg1, TypeTy *arg2,
1712 SourceLocation RPLoc) {
1713 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1714 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1715
1716 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1717
Steve Naroff363bcff2007-08-01 23:45:51 +00001718 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2, RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00001719}
1720
Steve Naroffd04fdd52007-08-03 21:21:27 +00001721Sema::ExprResult Sema::ParseChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
1722 ExprTy *expr1, ExprTy *expr2,
1723 SourceLocation RPLoc) {
1724 Expr *CondExpr = static_cast<Expr*>(cond);
1725 Expr *LHSExpr = static_cast<Expr*>(expr1);
1726 Expr *RHSExpr = static_cast<Expr*>(expr2);
1727
1728 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1729
1730 // The conditional expression is required to be a constant expression.
1731 llvm::APSInt condEval(32);
1732 SourceLocation ExpLoc;
1733 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1734 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1735 CondExpr->getSourceRange());
1736
1737 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1738 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1739 RHSExpr->getType();
1740 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1741}
1742
Anders Carlsson55085182007-08-21 17:43:55 +00001743// TODO: Move this to SemaObjC.cpp
Anders Carlssonf9bcf012007-08-22 15:14:15 +00001744Sema::ExprResult Sema::ParseObjCStringLiteral(ExprTy *string) {
Anders Carlsson55085182007-08-21 17:43:55 +00001745 StringLiteral* S = static_cast<StringLiteral *>(string);
1746
1747 if (CheckBuiltinCFStringArgument(S))
1748 return true;
1749
1750 QualType t = Context.getCFConstantStringType();
1751 t = t.getQualifiedType(QualType::Const);
1752 t = Context.getPointerType(t);
1753
1754 return new ObjCStringLiteral(S, t);
1755}
Anders Carlssonf9bcf012007-08-22 15:14:15 +00001756
1757Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1758 SourceLocation LParenLoc,
1759 TypeTy *Ty,
1760 SourceLocation RParenLoc) {
1761 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
1762
1763 QualType t = Context.getPointerType(Context.CharTy);
1764 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
1765}