blob: 67aa04de99f3a475d14096ed46f74598c2947ed9 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +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"
Steve Naroffc39ca262007-09-18 23:55:05 +000018#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Basic/Diagnostic.h"
23#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
25#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000026#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Steve Naroff87d58b42007-09-16 03:34:24 +000029/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000030/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
31/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
32/// multiple tokens. However, the common case is that StringToks points to one
33/// string.
34///
35Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000036Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000037 assert(NumStringToks && "Must have at least one string!");
38
39 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
40 if (Literal.hadError)
41 return ExprResult(true);
42
43 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
44 for (unsigned i = 0; i != NumStringToks; ++i)
45 StringTokLocs.push_back(StringToks[i].getLocation());
46
47 // FIXME: handle wchar_t
48 QualType t = Context.getPointerType(Context.CharTy);
49
50 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
51 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
52 Literal.AnyWide, t, StringToks[0].getLocation(),
53 StringToks[NumStringToks-1].getLocation());
54}
55
56
Steve Naroff0acc9c92007-09-15 18:49:24 +000057/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000058/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
59/// identifier is used in an function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000060Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000061 IdentifierInfo &II,
62 bool HasTrailingLParen) {
63 // Could be enum-constant or decl.
Steve Narofff0c31dd2007-09-16 16:16:00 +000064 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Chris Lattner4b009652007-07-25 00:24:17 +000065 if (D == 0) {
66 // Otherwise, this could be an implicitly declared function reference (legal
67 // in C90, extension in C99).
68 if (HasTrailingLParen &&
69 // Not in C++.
70 !getLangOptions().CPlusPlus)
71 D = ImplicitlyDefineFunction(Loc, II, S);
72 else {
73 // If this name wasn't predeclared and if this is not a function call,
74 // diagnose the problem.
75 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
76 }
77 }
Steve Naroff91b03f72007-08-28 03:03:08 +000078 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroffcae537d2007-08-28 18:45:29 +000079 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +000080 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +000081 return true;
Chris Lattner4b009652007-07-25 00:24:17 +000082 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +000083 }
Chris Lattner4b009652007-07-25 00:24:17 +000084 if (isa<TypedefDecl>(D))
85 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
86
87 assert(0 && "Invalid decl");
88 abort();
89}
90
Steve Naroff87d58b42007-09-16 03:34:24 +000091Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000092 tok::TokenKind Kind) {
93 PreDefinedExpr::IdentType IT;
94
95 switch (Kind) {
96 default:
97 assert(0 && "Unknown simple primary expr!");
98 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
99 IT = PreDefinedExpr::Func;
100 break;
101 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
102 IT = PreDefinedExpr::Function;
103 break;
104 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
105 IT = PreDefinedExpr::PrettyFunction;
106 break;
107 }
108
109 // Pre-defined identifiers are always of type char *.
110 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
111}
112
Steve Naroff87d58b42007-09-16 03:34:24 +0000113Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000114 llvm::SmallString<16> CharBuffer;
115 CharBuffer.resize(Tok.getLength());
116 const char *ThisTokBegin = &CharBuffer[0];
117 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
118
119 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
120 Tok.getLocation(), PP);
121 if (Literal.hadError())
122 return ExprResult(true);
123 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
124 Tok.getLocation());
125}
126
Steve Naroff87d58b42007-09-16 03:34:24 +0000127Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000128 // fast path for a single digit (which is quite common). A single digit
129 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
130 if (Tok.getLength() == 1) {
131 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
132
Chris Lattner3496d522007-09-04 02:45:27 +0000133 unsigned IntSize = static_cast<unsigned>(
134 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000135 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
136 Context.IntTy,
137 Tok.getLocation()));
138 }
139 llvm::SmallString<512> IntegerBuffer;
140 IntegerBuffer.resize(Tok.getLength());
141 const char *ThisTokBegin = &IntegerBuffer[0];
142
143 // Get the spelling of the token, which eliminates trigraphs, etc.
144 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
145 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
146 Tok.getLocation(), PP);
147 if (Literal.hadError)
148 return ExprResult(true);
149
Chris Lattner1de66eb2007-08-26 03:42:43 +0000150 Expr *Res;
151
152 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000153 QualType Ty;
154 const llvm::fltSemantics *Format;
155 uint64_t Size; unsigned Align;
156
157 if (Literal.isFloat) {
158 Ty = Context.FloatTy;
159 Context.Target.getFloatInfo(Size, Align, Format, Tok.getLocation());
160 } else if (Literal.isLong) {
161 Ty = Context.LongDoubleTy;
162 Context.Target.getLongDoubleInfo(Size, Align, Format, Tok.getLocation());
163 } else {
164 Ty = Context.DoubleTy;
165 Context.Target.getDoubleInfo(Size, Align, Format, Tok.getLocation());
166 }
167
168 Res = new FloatingLiteral(Literal.GetFloatValue(*Format), Ty,
169 Tok.getLocation());
Chris Lattner1de66eb2007-08-26 03:42:43 +0000170 } else if (!Literal.isIntegerLiteral()) {
171 return ExprResult(true);
172 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000173 QualType t;
174
Neil Booth7421e9c2007-08-29 22:00:19 +0000175 // long long is a C99 feature.
176 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000177 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000178 Diag(Tok.getLocation(), diag::ext_longlong);
179
Chris Lattner4b009652007-07-25 00:24:17 +0000180 // Get the value in the widest-possible width.
181 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
182
183 if (Literal.GetIntegerValue(ResultVal)) {
184 // If this value didn't fit into uintmax_t, warn and force to ull.
185 Diag(Tok.getLocation(), diag::warn_integer_too_large);
186 t = Context.UnsignedLongLongTy;
187 assert(Context.getTypeSize(t, Tok.getLocation()) ==
188 ResultVal.getBitWidth() && "long long is not intmax_t?");
189 } else {
190 // If this value fits into a ULL, try to figure out what else it fits into
191 // according to the rules of C99 6.4.4.1p5.
192
193 // Octal, Hexadecimal, and integers with a U suffix are allowed to
194 // be an unsigned int.
195 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
196
197 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000198 if (!Literal.isLong && !Literal.isLongLong) {
199 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000200 unsigned IntSize = static_cast<unsigned>(
201 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000202 // Does it fit in a unsigned int?
203 if (ResultVal.isIntN(IntSize)) {
204 // Does it fit in a signed int?
205 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
206 t = Context.IntTy;
207 else if (AllowUnsigned)
208 t = Context.UnsignedIntTy;
209 }
210
211 if (!t.isNull())
212 ResultVal.trunc(IntSize);
213 }
214
215 // Are long/unsigned long possibilities?
216 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000217 unsigned LongSize = static_cast<unsigned>(
218 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000219
220 // Does it fit in a unsigned long?
221 if (ResultVal.isIntN(LongSize)) {
222 // Does it fit in a signed long?
223 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
224 t = Context.LongTy;
225 else if (AllowUnsigned)
226 t = Context.UnsignedLongTy;
227 }
228 if (!t.isNull())
229 ResultVal.trunc(LongSize);
230 }
231
232 // Finally, check long long if needed.
233 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000234 unsigned LongLongSize = static_cast<unsigned>(
235 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000236
237 // Does it fit in a unsigned long long?
238 if (ResultVal.isIntN(LongLongSize)) {
239 // Does it fit in a signed long long?
240 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
241 t = Context.LongLongTy;
242 else if (AllowUnsigned)
243 t = Context.UnsignedLongLongTy;
244 }
245 }
246
247 // If we still couldn't decide a type, we probably have something that
248 // does not fit in a signed long long, but has no U suffix.
249 if (t.isNull()) {
250 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
251 t = Context.UnsignedLongLongTy;
252 }
253 }
254
Chris Lattner1de66eb2007-08-26 03:42:43 +0000255 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000256 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000257
258 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
259 if (Literal.isImaginary)
260 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
261
262 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000263}
264
Steve Naroff87d58b42007-09-16 03:34:24 +0000265Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000266 ExprTy *Val) {
267 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000268 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000269 return new ParenExpr(L, R, e);
270}
271
272/// The UsualUnaryConversions() function is *not* called by this routine.
273/// See C99 6.3.2.1p[2-4] for more details.
274QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
275 SourceLocation OpLoc, bool isSizeof) {
276 // C99 6.5.3.4p1:
277 if (isa<FunctionType>(exprType) && isSizeof)
278 // alignof(function) is allowed.
279 Diag(OpLoc, diag::ext_sizeof_function_type);
280 else if (exprType->isVoidType())
281 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
282 else if (exprType->isIncompleteType()) {
283 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
284 diag::err_alignof_incomplete_type,
285 exprType.getAsString());
286 return QualType(); // error
287 }
288 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
289 return Context.getSizeType();
290}
291
292Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000293ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000294 SourceLocation LPLoc, TypeTy *Ty,
295 SourceLocation RPLoc) {
296 // If error parsing type, ignore.
297 if (Ty == 0) return true;
298
299 // Verify that this is a valid expression.
300 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
301
302 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
303
304 if (resultType.isNull())
305 return true;
306 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
307}
308
Chris Lattner5110ad52007-08-24 21:41:10 +0000309QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000310 DefaultFunctionArrayConversion(V);
311
Chris Lattnera16e42d2007-08-26 05:39:26 +0000312 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000313 if (const ComplexType *CT = V->getType()->getAsComplexType())
314 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000315
316 // Otherwise they pass through real integer and floating point types here.
317 if (V->getType()->isArithmeticType())
318 return V->getType();
319
320 // Reject anything else.
321 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
322 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000323}
324
325
Chris Lattner4b009652007-07-25 00:24:17 +0000326
Steve Naroff87d58b42007-09-16 03:34:24 +0000327Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000328 tok::TokenKind Kind,
329 ExprTy *Input) {
330 UnaryOperator::Opcode Opc;
331 switch (Kind) {
332 default: assert(0 && "Unknown unary op!");
333 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
334 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
335 }
336 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
337 if (result.isNull())
338 return true;
339 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
340}
341
342Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000343ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000344 ExprTy *Idx, SourceLocation RLoc) {
345 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
346
347 // Perform default conversions.
348 DefaultFunctionArrayConversion(LHSExp);
349 DefaultFunctionArrayConversion(RHSExp);
350
351 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
352
353 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000354 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000355 // in the subscript position. As a result, we need to derive the array base
356 // and index from the expression types.
357 Expr *BaseExpr, *IndexExpr;
358 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000359 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000360 BaseExpr = LHSExp;
361 IndexExpr = RHSExp;
362 // FIXME: need to deal with const...
363 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000364 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000365 // Handle the uncommon case of "123[Ptr]".
366 BaseExpr = RHSExp;
367 IndexExpr = LHSExp;
368 // FIXME: need to deal with const...
369 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000370 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
371 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000372 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000373
374 // Component access limited to variables (reject vec4.rg[1]).
375 if (!isa<DeclRefExpr>(BaseExpr))
376 return Diag(LLoc, diag::err_ocuvector_component_access,
377 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000378 // FIXME: need to deal with const...
379 ResultType = VTy->getElementType();
380 } else {
381 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
382 RHSExp->getSourceRange());
383 }
384 // C99 6.5.2.1p1
385 if (!IndexExpr->getType()->isIntegerType())
386 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
387 IndexExpr->getSourceRange());
388
389 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
390 // the following check catches trying to index a pointer to a function (e.g.
391 // void (*)(int)). Functions are not objects in C99.
392 if (!ResultType->isObjectType())
393 return Diag(BaseExpr->getLocStart(),
394 diag::err_typecheck_subscript_not_object,
395 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
396
397 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
398}
399
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000400QualType Sema::
401CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
402 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000403 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000404
405 // The vector accessor can't exceed the number of elements.
406 const char *compStr = CompName.getName();
407 if (strlen(compStr) > vecType->getNumElements()) {
408 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
409 baseType.getAsString(), SourceRange(CompLoc));
410 return QualType();
411 }
412 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000413 if (vecType->getPointAccessorIdx(*compStr) != -1) {
414 do
415 compStr++;
416 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
417 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
418 do
419 compStr++;
420 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
421 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
422 do
423 compStr++;
424 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
425 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000426
427 if (*compStr) {
428 // We didn't get to the end of the string. This means the component names
429 // didn't come from the same set *or* we encountered an illegal name.
430 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
431 std::string(compStr,compStr+1), SourceRange(CompLoc));
432 return QualType();
433 }
434 // Each component accessor can't exceed the vector type.
435 compStr = CompName.getName();
436 while (*compStr) {
437 if (vecType->isAccessorWithinNumElements(*compStr))
438 compStr++;
439 else
440 break;
441 }
442 if (*compStr) {
443 // We didn't get to the end of the string. This means a component accessor
444 // exceeds the number of elements in the vector.
445 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
446 baseType.getAsString(), SourceRange(CompLoc));
447 return QualType();
448 }
449 // The component accessor looks fine - now we need to compute the actual type.
450 // The vector type is implied by the component accessor. For example,
451 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
452 unsigned CompSize = strlen(CompName.getName());
453 if (CompSize == 1)
454 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000455
456 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
457 // Now look up the TypeDefDecl from the vector type. Without this,
458 // diagostics look bad. We want OCU vector types to appear built-in.
459 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
460 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
461 return Context.getTypedefType(OCUVectorDecls[i]);
462 }
463 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000464}
465
Chris Lattner4b009652007-07-25 00:24:17 +0000466Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000467ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000468 tok::TokenKind OpKind, SourceLocation MemberLoc,
469 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000470 Expr *BaseExpr = static_cast<Expr *>(Base);
471 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000472
Steve Naroff2cb66382007-07-26 03:11:44 +0000473 QualType BaseType = BaseExpr->getType();
474 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000475
Chris Lattner4b009652007-07-25 00:24:17 +0000476 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000477 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000478 BaseType = PT->getPointeeType();
479 else
480 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
481 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000482 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000483 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000484 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000485 RecordDecl *RDecl = RTy->getDecl();
486 if (RTy->isIncompleteType())
487 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
488 BaseExpr->getSourceRange());
489 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000490 FieldDecl *MemberDecl = RDecl->getMember(&Member);
491 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000492 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
493 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000494 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
495 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000496 // Component access limited to variables (reject vec4.rg.g).
497 if (!isa<DeclRefExpr>(BaseExpr))
498 return Diag(OpLoc, diag::err_ocuvector_component_access,
499 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000500 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
501 if (ret.isNull())
502 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000503 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Steve Naroff2cb66382007-07-26 03:11:44 +0000504 } else
505 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
506 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000507}
508
Steve Naroff87d58b42007-09-16 03:34:24 +0000509/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000510/// This provides the location of the left/right parens and a list of comma
511/// locations.
512Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000513ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000514 ExprTy **args, unsigned NumArgsInCall,
515 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
516 Expr *Fn = static_cast<Expr *>(fn);
517 Expr **Args = reinterpret_cast<Expr**>(args);
518 assert(Fn && "no function call expression");
519
520 UsualUnaryConversions(Fn);
521 QualType funcType = Fn->getType();
522
523 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
524 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000525 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000526 if (PT == 0)
527 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
528 SourceRange(Fn->getLocStart(), RParenLoc));
529
Chris Lattner71225142007-07-31 21:27:01 +0000530 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000531 if (funcT == 0)
532 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
533 SourceRange(Fn->getLocStart(), RParenLoc));
534
535 // If a prototype isn't declared, the parser implicitly defines a func decl
536 QualType resultType = funcT->getResultType();
537
538 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
539 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
540 // assignment, to the types of the corresponding parameter, ...
541
542 unsigned NumArgsInProto = proto->getNumArgs();
543 unsigned NumArgsToCheck = NumArgsInCall;
544
545 if (NumArgsInCall < NumArgsInProto)
546 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
547 Fn->getSourceRange());
548 else if (NumArgsInCall > NumArgsInProto) {
549 if (!proto->isVariadic()) {
550 Diag(Args[NumArgsInProto]->getLocStart(),
551 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
552 SourceRange(Args[NumArgsInProto]->getLocStart(),
553 Args[NumArgsInCall-1]->getLocEnd()));
554 }
555 NumArgsToCheck = NumArgsInProto;
556 }
557 // Continue to check argument types (even if we have too few/many args).
558 for (unsigned i = 0; i < NumArgsToCheck; i++) {
559 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000560 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000561
562 QualType lhsType = proto->getArgType(i);
563 QualType rhsType = argExpr->getType();
564
Steve Naroff75644062007-07-25 20:45:33 +0000565 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000566 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000567 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000568 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000569 lhsType = Context.getPointerType(lhsType);
570
571 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
572 argExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000573 if (Args[i] != argExpr) // The expression was converted.
574 Args[i] = argExpr; // Make sure we store the converted expression.
Chris Lattner4b009652007-07-25 00:24:17 +0000575 SourceLocation l = argExpr->getLocStart();
576
577 // decode the result (notice that AST's are still created for extensions).
578 switch (result) {
579 case Compatible:
580 break;
581 case PointerFromInt:
582 // check for null pointer constant (C99 6.3.2.3p3)
583 if (!argExpr->isNullPointerConstant(Context)) {
584 Diag(l, diag::ext_typecheck_passing_pointer_int,
585 lhsType.getAsString(), rhsType.getAsString(),
586 Fn->getSourceRange(), argExpr->getSourceRange());
587 }
588 break;
589 case IntFromPointer:
590 Diag(l, diag::ext_typecheck_passing_pointer_int,
591 lhsType.getAsString(), rhsType.getAsString(),
592 Fn->getSourceRange(), argExpr->getSourceRange());
593 break;
594 case IncompatiblePointer:
595 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
596 rhsType.getAsString(), lhsType.getAsString(),
597 Fn->getSourceRange(), argExpr->getSourceRange());
598 break;
599 case CompatiblePointerDiscardsQualifiers:
600 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
601 rhsType.getAsString(), lhsType.getAsString(),
602 Fn->getSourceRange(), argExpr->getSourceRange());
603 break;
604 case Incompatible:
605 return Diag(l, diag::err_typecheck_passing_incompatible,
606 rhsType.getAsString(), lhsType.getAsString(),
607 Fn->getSourceRange(), argExpr->getSourceRange());
608 }
609 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000610 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
611 // Promote the arguments (C99 6.5.2.2p7).
612 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
613 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000614 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000615
616 DefaultArgumentPromotion(argExpr);
617 if (Args[i] != argExpr) // The expression was converted.
618 Args[i] = argExpr; // Make sure we store the converted expression.
619 }
620 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
621 // Even if the types checked, bail if the number of arguments don't match.
Chris Lattner4b009652007-07-25 00:24:17 +0000622 return true;
Steve Naroffdb65e052007-08-28 23:30:39 +0000623 }
624 } else if (isa<FunctionTypeNoProto>(funcT)) {
625 // Promote the arguments (C99 6.5.2.2p6).
626 for (unsigned i = 0; i < NumArgsInCall; i++) {
627 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000628 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000629
630 DefaultArgumentPromotion(argExpr);
631 if (Args[i] != argExpr) // The expression was converted.
632 Args[i] = argExpr; // Make sure we store the converted expression.
633 }
Chris Lattner4b009652007-07-25 00:24:17 +0000634 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000635 // Do special checking on direct calls to functions.
636 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
637 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
638 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000639 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
640 NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000641 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000642
Chris Lattner4b009652007-07-25 00:24:17 +0000643 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
644}
645
646Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000647ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000648 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000649 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000650 QualType literalType = QualType::getFromOpaquePtr(Ty);
651 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000652 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000653 Expr *literalExpr = static_cast<Expr*>(InitExpr);
654
655 // FIXME: add semantic analysis (C99 6.5.2.5).
656 return new CompoundLiteralExpr(literalType, literalExpr);
657}
658
659Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000660ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000661 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000662 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000663
Steve Naroff0acc9c92007-09-15 18:49:24 +0000664 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000665 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000666
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000667 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
668 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
669 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000670}
671
672Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000673ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000674 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000675 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000676
677 Expr *castExpr = static_cast<Expr*>(Op);
678 QualType castType = QualType::getFromOpaquePtr(Ty);
679
Steve Naroff68adb482007-08-31 00:32:44 +0000680 UsualUnaryConversions(castExpr);
681
Chris Lattner4b009652007-07-25 00:24:17 +0000682 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
683 // type needs to be scalar.
684 if (!castType->isScalarType() && !castType->isVoidType()) {
685 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
686 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
687 }
688 if (!castExpr->getType()->isScalarType()) {
689 return Diag(castExpr->getLocStart(),
690 diag::err_typecheck_expect_scalar_operand,
691 castExpr->getType().getAsString(), castExpr->getSourceRange());
692 }
693 return new CastExpr(castType, castExpr, LParenLoc);
694}
695
696inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
697 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
698 UsualUnaryConversions(cond);
699 UsualUnaryConversions(lex);
700 UsualUnaryConversions(rex);
701 QualType condT = cond->getType();
702 QualType lexT = lex->getType();
703 QualType rexT = rex->getType();
704
705 // first, check the condition.
706 if (!condT->isScalarType()) { // C99 6.5.15p2
707 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
708 condT.getAsString());
709 return QualType();
710 }
711 // now check the two expressions.
712 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
713 UsualArithmeticConversions(lex, rex);
714 return lex->getType();
715 }
Chris Lattner71225142007-07-31 21:27:01 +0000716 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
717 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
718
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000719 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
Chris Lattner71225142007-07-31 21:27:01 +0000720 return lexT;
721
Chris Lattner4b009652007-07-25 00:24:17 +0000722 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
723 lexT.getAsString(), rexT.getAsString(),
724 lex->getSourceRange(), rex->getSourceRange());
725 return QualType();
726 }
727 }
728 // C99 6.5.15p3
729 if (lexT->isPointerType() && rex->isNullPointerConstant(Context))
730 return lexT;
731 if (rexT->isPointerType() && lex->isNullPointerConstant(Context))
732 return rexT;
733
Chris Lattner71225142007-07-31 21:27:01 +0000734 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
735 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
736 // get the "pointed to" types
737 QualType lhptee = LHSPT->getPointeeType();
738 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000739
Chris Lattner71225142007-07-31 21:27:01 +0000740 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
741 if (lhptee->isVoidType() &&
742 (rhptee->isObjectType() || rhptee->isIncompleteType()))
743 return lexT;
744 if (rhptee->isVoidType() &&
745 (lhptee->isObjectType() || lhptee->isIncompleteType()))
746 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000747
Chris Lattner71225142007-07-31 21:27:01 +0000748 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
749 rhptee.getUnqualifiedType())) {
750 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
751 lexT.getAsString(), rexT.getAsString(),
752 lex->getSourceRange(), rex->getSourceRange());
753 return lexT; // FIXME: this is an _ext - is this return o.k?
754 }
755 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000756 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
757 // differently qualified versions of compatible types, the result type is
758 // a pointer to an appropriately qualified version of the *composite*
759 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000760 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000761 }
Chris Lattner4b009652007-07-25 00:24:17 +0000762 }
Chris Lattner71225142007-07-31 21:27:01 +0000763
Chris Lattner4b009652007-07-25 00:24:17 +0000764 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
765 return lexT;
766
767 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
768 lexT.getAsString(), rexT.getAsString(),
769 lex->getSourceRange(), rex->getSourceRange());
770 return QualType();
771}
772
Steve Naroff87d58b42007-09-16 03:34:24 +0000773/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000774/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000775Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000776 SourceLocation ColonLoc,
777 ExprTy *Cond, ExprTy *LHS,
778 ExprTy *RHS) {
779 Expr *CondExpr = (Expr *) Cond;
780 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
781 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
782 RHSExpr, QuestionLoc);
783 if (result.isNull())
784 return true;
785 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
786}
787
788// promoteExprToType - a helper function to ensure we create exactly one
789// ImplicitCastExpr. As a convenience (to the caller), we return the type.
790static void promoteExprToType(Expr *&expr, QualType type) {
791 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
792 impCast->setType(type);
793 else
794 expr = new ImplicitCastExpr(type, expr);
795 return;
796}
797
Steve Naroffdb65e052007-08-28 23:30:39 +0000798/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
799/// do not have a prototype. Integer promotions are performed on each
800/// argument, and arguments that have type float are promoted to double.
801void Sema::DefaultArgumentPromotion(Expr *&expr) {
802 QualType t = expr->getType();
803 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
804
805 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
806 promoteExprToType(expr, Context.IntTy);
807 if (t == Context.FloatTy)
808 promoteExprToType(expr, Context.DoubleTy);
809}
810
Chris Lattner4b009652007-07-25 00:24:17 +0000811/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
812void Sema::DefaultFunctionArrayConversion(Expr *&e) {
813 QualType t = e->getType();
814 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
815
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000816 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000817 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
818 t = e->getType();
819 }
820 if (t->isFunctionType())
821 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000822 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000823 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
824}
825
826/// UsualUnaryConversion - Performs various conversions that are common to most
827/// operators (C99 6.3). The conversions of array and function types are
828/// sometimes surpressed. For example, the array->pointer conversion doesn't
829/// apply if the array is an argument to the sizeof or address (&) operators.
830/// In these instances, this routine should *not* be called.
831void Sema::UsualUnaryConversions(Expr *&expr) {
832 QualType t = expr->getType();
833 assert(!t.isNull() && "UsualUnaryConversions - missing type");
834
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000835 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000836 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
837 t = expr->getType();
838 }
839 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
840 promoteExprToType(expr, Context.IntTy);
841 else
842 DefaultFunctionArrayConversion(expr);
843}
844
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000845/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000846/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
847/// routine returns the first non-arithmetic type found. The client is
848/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000849QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
850 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000851 if (!isCompAssign) {
852 UsualUnaryConversions(lhsExpr);
853 UsualUnaryConversions(rhsExpr);
854 }
Chris Lattner4b009652007-07-25 00:24:17 +0000855 QualType lhs = lhsExpr->getType();
856 QualType rhs = rhsExpr->getType();
857
858 // If both types are identical, no conversion is needed.
859 if (lhs == rhs)
Steve Naroff8f708362007-08-24 19:07:16 +0000860 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000861
862 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
863 // The caller can deal with this (e.g. pointer + int).
864 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000865 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000866
867 // At this point, we have two different arithmetic types.
868
869 // Handle complex types first (C99 6.3.1.8p1).
870 if (lhs->isComplexType() || rhs->isComplexType()) {
871 // if we have an integer operand, the result is the complex type.
872 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000873 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
874 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000875 }
876 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000877 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
878 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000879 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000880 // This handles complex/complex, complex/float, or float/complex.
881 // When both operands are complex, the shorter operand is converted to the
882 // type of the longer, and that is the type of the result. This corresponds
883 // to what is done when combining two real floating-point operands.
884 // The fun begins when size promotion occur across type domains.
885 // From H&S 6.3.4: When one operand is complex and the other is a real
886 // floating-point type, the less precise type is converted, within it's
887 // real or complex domain, to the precision of the other type. For example,
888 // when combining a "long double" with a "double _Complex", the
889 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000890 int result = Context.compareFloatingType(lhs, rhs);
891
892 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000893 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
894 if (!isCompAssign)
895 promoteExprToType(rhsExpr, rhs);
896 } else if (result < 0) { // The right side is bigger, convert lhs.
897 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
898 if (!isCompAssign)
899 promoteExprToType(lhsExpr, lhs);
900 }
901 // At this point, lhs and rhs have the same rank/size. Now, make sure the
902 // domains match. This is a requirement for our implementation, C99
903 // does not require this promotion.
904 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
905 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000906 if (!isCompAssign)
907 promoteExprToType(lhsExpr, rhs);
908 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000909 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000910 if (!isCompAssign)
911 promoteExprToType(rhsExpr, lhs);
912 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000913 }
Chris Lattner4b009652007-07-25 00:24:17 +0000914 }
Steve Naroff3b6157f2007-08-27 21:43:43 +0000915 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +0000916 }
917 // Now handle "real" floating types (i.e. float, double, long double).
918 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
919 // if we have an integer operand, the result is the real floating type.
920 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000921 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
922 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000923 }
924 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000925 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
926 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000927 }
928 // We have two real floating types, float/complex combos were handled above.
929 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +0000930 int result = Context.compareFloatingType(lhs, rhs);
931
932 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000933 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
934 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000935 }
Steve Naroff45fc9822007-08-27 15:30:22 +0000936 if (result < 0) { // convert the lhs
937 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
938 return rhs;
939 }
940 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +0000941 }
942 // Finally, we have two differing integer types.
943 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000944 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
945 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000946 }
Steve Naroff8f708362007-08-24 19:07:16 +0000947 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
948 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000949}
950
951// CheckPointerTypesForAssignment - This is a very tricky routine (despite
952// being closely modeled after the C99 spec:-). The odd characteristic of this
953// routine is it effectively iqnores the qualifiers on the top level pointee.
954// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
955// FIXME: add a couple examples in this comment.
956Sema::AssignmentCheckResult
957Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
958 QualType lhptee, rhptee;
959
960 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +0000961 lhptee = lhsType->getAsPointerType()->getPointeeType();
962 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000963
964 // make sure we operate on the canonical type
965 lhptee = lhptee.getCanonicalType();
966 rhptee = rhptee.getCanonicalType();
967
968 AssignmentCheckResult r = Compatible;
969
970 // C99 6.5.16.1p1: This following citation is common to constraints
971 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
972 // qualifiers of the type *pointed to* by the right;
973 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
974 rhptee.getQualifiers())
975 r = CompatiblePointerDiscardsQualifiers;
976
977 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
978 // incomplete type and the other is a pointer to a qualified or unqualified
979 // version of void...
980 if (lhptee.getUnqualifiedType()->isVoidType() &&
981 (rhptee->isObjectType() || rhptee->isIncompleteType()))
982 ;
983 else if (rhptee.getUnqualifiedType()->isVoidType() &&
984 (lhptee->isObjectType() || lhptee->isIncompleteType()))
985 ;
986 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
987 // unqualified versions of compatible types, ...
988 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
989 rhptee.getUnqualifiedType()))
990 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
991 return r;
992}
993
994/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
995/// has code to accommodate several GCC extensions when type checking
996/// pointers. Here are some objectionable examples that GCC considers warnings:
997///
998/// int a, *pint;
999/// short *pshort;
1000/// struct foo *pfoo;
1001///
1002/// pint = pshort; // warning: assignment from incompatible pointer type
1003/// a = pint; // warning: assignment makes integer from pointer without a cast
1004/// pint = a; // warning: assignment makes pointer from integer without a cast
1005/// pint = pfoo; // warning: assignment from incompatible pointer type
1006///
1007/// As a result, the code for dealing with pointers is more complex than the
1008/// C99 spec dictates.
1009/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1010///
1011Sema::AssignmentCheckResult
1012Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
1013 if (lhsType == rhsType) // common case, fast path...
1014 return Compatible;
1015
1016 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
1017 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1018 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1019 return Incompatible;
1020 }
1021 return Compatible;
1022 } else if (lhsType->isPointerType()) {
1023 if (rhsType->isIntegerType())
1024 return PointerFromInt;
1025
1026 if (rhsType->isPointerType())
1027 return CheckPointerTypesForAssignment(lhsType, rhsType);
1028 } else if (rhsType->isPointerType()) {
1029 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1030 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1031 return IntFromPointer;
1032
1033 if (lhsType->isPointerType())
1034 return CheckPointerTypesForAssignment(lhsType, rhsType);
1035 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
1036 if (Type::tagTypesAreCompatible(lhsType, rhsType))
1037 return Compatible;
1038 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
1039 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
1040 return Compatible;
1041 }
1042 return Incompatible;
1043}
1044
1045Sema::AssignmentCheckResult
1046Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
1047 // This check seems unnatural, however it is necessary to insure the proper
1048 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001049 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001050 // expressions that surpress this implicit conversion (&, sizeof).
1051 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001052
1053 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +00001054
Steve Naroff0f32f432007-08-24 22:33:52 +00001055 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1056
1057 // C99 6.5.16.1p2: The value of the right operand is converted to the
1058 // type of the assignment expression.
1059 if (rExpr->getType() != lhsType)
1060 promoteExprToType(rExpr, lhsType);
1061 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001062}
1063
1064Sema::AssignmentCheckResult
1065Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1066 return CheckAssignmentConstraints(lhsType, rhsType);
1067}
1068
1069inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1070 Diag(loc, diag::err_typecheck_invalid_operands,
1071 lex->getType().getAsString(), rex->getType().getAsString(),
1072 lex->getSourceRange(), rex->getSourceRange());
1073}
1074
1075inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1076 Expr *&rex) {
1077 QualType lhsType = lex->getType(), rhsType = rex->getType();
1078
1079 // make sure the vector types are identical.
1080 if (lhsType == rhsType)
1081 return lhsType;
1082 // You cannot convert between vector values of different size.
1083 Diag(loc, diag::err_typecheck_vector_not_convertable,
1084 lex->getType().getAsString(), rex->getType().getAsString(),
1085 lex->getSourceRange(), rex->getSourceRange());
1086 return QualType();
1087}
1088
1089inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001090 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001091{
1092 QualType lhsType = lex->getType(), rhsType = rex->getType();
1093
1094 if (lhsType->isVectorType() || rhsType->isVectorType())
1095 return CheckVectorOperands(loc, lex, rex);
1096
Steve Naroff8f708362007-08-24 19:07:16 +00001097 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001098
Chris Lattner4b009652007-07-25 00:24:17 +00001099 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001100 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001101 InvalidOperands(loc, lex, rex);
1102 return QualType();
1103}
1104
1105inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001106 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001107{
1108 QualType lhsType = lex->getType(), rhsType = rex->getType();
1109
Steve Naroff8f708362007-08-24 19:07:16 +00001110 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001111
Chris Lattner4b009652007-07-25 00:24:17 +00001112 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001113 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001114 InvalidOperands(loc, lex, rex);
1115 return QualType();
1116}
1117
1118inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001119 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001120{
1121 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1122 return CheckVectorOperands(loc, lex, rex);
1123
Steve Naroff8f708362007-08-24 19:07:16 +00001124 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001125
1126 // handle the common case first (both operands are arithmetic).
1127 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001128 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001129
1130 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1131 return lex->getType();
1132 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1133 return rex->getType();
1134 InvalidOperands(loc, lex, rex);
1135 return QualType();
1136}
1137
1138inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001139 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001140{
1141 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1142 return CheckVectorOperands(loc, lex, rex);
1143
Steve Naroff8f708362007-08-24 19:07:16 +00001144 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001145
1146 // handle the common case first (both operands are arithmetic).
1147 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001148 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001149
1150 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001151 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001152 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1153 return Context.getPointerDiffType();
1154 InvalidOperands(loc, lex, rex);
1155 return QualType();
1156}
1157
1158inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001159 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001160{
1161 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1162 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001163 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001164
1165 // handle the common case first (both operands are arithmetic).
1166 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001167 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001168 InvalidOperands(loc, lex, rex);
1169 return QualType();
1170}
1171
Chris Lattner254f3bc2007-08-26 01:18:55 +00001172inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1173 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001174{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001175 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001176 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1177 UsualArithmeticConversions(lex, rex);
1178 else {
1179 UsualUnaryConversions(lex);
1180 UsualUnaryConversions(rex);
1181 }
Chris Lattner4b009652007-07-25 00:24:17 +00001182 QualType lType = lex->getType();
1183 QualType rType = rex->getType();
1184
Chris Lattner254f3bc2007-08-26 01:18:55 +00001185 if (isRelational) {
1186 if (lType->isRealType() && rType->isRealType())
1187 return Context.IntTy;
1188 } else {
Chris Lattnerbd3cc222007-08-30 06:10:41 +00001189 if (lType->isFloatingType() && rType->isFloatingType())
Ted Kremenekec761af2007-08-29 18:06:12 +00001190 Diag(loc, diag::warn_floatingpoint_eq);
1191
Chris Lattner254f3bc2007-08-26 01:18:55 +00001192 if (lType->isArithmeticType() && rType->isArithmeticType())
1193 return Context.IntTy;
1194 }
Chris Lattner4b009652007-07-25 00:24:17 +00001195
Chris Lattner22be8422007-08-26 01:10:14 +00001196 bool LHSIsNull = lex->isNullPointerConstant(Context);
1197 bool RHSIsNull = rex->isNullPointerConstant(Context);
1198
Chris Lattner254f3bc2007-08-26 01:18:55 +00001199 // All of the following pointer related warnings are GCC extensions, except
1200 // when handling null pointer constants. One day, we can consider making them
1201 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001202 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner22be8422007-08-26 01:10:14 +00001203 if (!LHSIsNull && !RHSIsNull &&
Steve Naroffc33c0602007-08-27 04:08:11 +00001204 !Type::pointerTypesAreCompatible(lType.getUnqualifiedType(),
1205 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001206 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1207 lType.getAsString(), rType.getAsString(),
1208 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001209 }
Chris Lattner22be8422007-08-26 01:10:14 +00001210 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001211 return Context.IntTy;
1212 }
1213 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001214 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001215 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1216 lType.getAsString(), rType.getAsString(),
1217 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001218 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001219 return Context.IntTy;
1220 }
1221 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001222 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001223 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1224 lType.getAsString(), rType.getAsString(),
1225 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001226 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001227 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001228 }
1229 InvalidOperands(loc, lex, rex);
1230 return QualType();
1231}
1232
Chris Lattner4b009652007-07-25 00:24:17 +00001233inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001234 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001235{
1236 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1237 return CheckVectorOperands(loc, lex, rex);
1238
Steve Naroff8f708362007-08-24 19:07:16 +00001239 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001240
1241 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001242 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001243 InvalidOperands(loc, lex, rex);
1244 return QualType();
1245}
1246
1247inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1248 Expr *&lex, Expr *&rex, SourceLocation loc)
1249{
1250 UsualUnaryConversions(lex);
1251 UsualUnaryConversions(rex);
1252
1253 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1254 return Context.IntTy;
1255 InvalidOperands(loc, lex, rex);
1256 return QualType();
1257}
1258
1259inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001260 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001261{
1262 QualType lhsType = lex->getType();
1263 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1264 bool hadError = false;
1265 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1266
1267 switch (mlval) { // C99 6.5.16p2
1268 case Expr::MLV_Valid:
1269 break;
1270 case Expr::MLV_ConstQualified:
1271 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1272 hadError = true;
1273 break;
1274 case Expr::MLV_ArrayType:
1275 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1276 lhsType.getAsString(), lex->getSourceRange());
1277 return QualType();
1278 case Expr::MLV_NotObjectType:
1279 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1280 lhsType.getAsString(), lex->getSourceRange());
1281 return QualType();
1282 case Expr::MLV_InvalidExpression:
1283 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1284 lex->getSourceRange());
1285 return QualType();
1286 case Expr::MLV_IncompleteType:
1287 case Expr::MLV_IncompleteVoidType:
1288 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1289 lhsType.getAsString(), lex->getSourceRange());
1290 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001291 case Expr::MLV_DuplicateVectorComponents:
1292 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1293 lex->getSourceRange());
1294 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001295 }
1296 AssignmentCheckResult result;
1297
1298 if (compoundType.isNull())
1299 result = CheckSingleAssignmentConstraints(lhsType, rex);
1300 else
1301 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001302
Chris Lattner4b009652007-07-25 00:24:17 +00001303 // decode the result (notice that extensions still return a type).
1304 switch (result) {
1305 case Compatible:
1306 break;
1307 case Incompatible:
1308 Diag(loc, diag::err_typecheck_assign_incompatible,
1309 lhsType.getAsString(), rhsType.getAsString(),
1310 lex->getSourceRange(), rex->getSourceRange());
1311 hadError = true;
1312 break;
1313 case PointerFromInt:
1314 // check for null pointer constant (C99 6.3.2.3p3)
1315 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1316 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1317 lhsType.getAsString(), rhsType.getAsString(),
1318 lex->getSourceRange(), rex->getSourceRange());
1319 }
1320 break;
1321 case IntFromPointer:
1322 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1323 lhsType.getAsString(), rhsType.getAsString(),
1324 lex->getSourceRange(), rex->getSourceRange());
1325 break;
1326 case IncompatiblePointer:
1327 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1328 lhsType.getAsString(), rhsType.getAsString(),
1329 lex->getSourceRange(), rex->getSourceRange());
1330 break;
1331 case CompatiblePointerDiscardsQualifiers:
1332 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1333 lhsType.getAsString(), rhsType.getAsString(),
1334 lex->getSourceRange(), rex->getSourceRange());
1335 break;
1336 }
1337 // C99 6.5.16p3: The type of an assignment expression is the type of the
1338 // left operand unless the left operand has qualified type, in which case
1339 // it is the unqualified version of the type of the left operand.
1340 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1341 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001342 // C++ 5.17p1: the type of the assignment expression is that of its left
1343 // oprdu.
Chris Lattner4b009652007-07-25 00:24:17 +00001344 return hadError ? QualType() : lhsType.getUnqualifiedType();
1345}
1346
1347inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1348 Expr *&lex, Expr *&rex, SourceLocation loc) {
1349 UsualUnaryConversions(rex);
1350 return rex->getType();
1351}
1352
1353/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1354/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1355QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1356 QualType resType = op->getType();
1357 assert(!resType.isNull() && "no type for increment/decrement expression");
1358
Steve Naroffd30e1932007-08-24 17:20:07 +00001359 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattner4b009652007-07-25 00:24:17 +00001360 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1361 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1362 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1363 resType.getAsString(), op->getSourceRange());
1364 return QualType();
1365 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001366 } else if (!resType->isRealType()) {
1367 if (resType->isComplexType())
1368 // C99 does not support ++/-- on complex types.
1369 Diag(OpLoc, diag::ext_integer_increment_complex,
1370 resType.getAsString(), op->getSourceRange());
1371 else {
1372 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1373 resType.getAsString(), op->getSourceRange());
1374 return QualType();
1375 }
Chris Lattner4b009652007-07-25 00:24:17 +00001376 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001377 // At this point, we know we have a real, complex or pointer type.
1378 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001379 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1380 if (mlval != Expr::MLV_Valid) {
1381 // FIXME: emit a more precise diagnostic...
1382 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1383 op->getSourceRange());
1384 return QualType();
1385 }
1386 return resType;
1387}
1388
1389/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1390/// This routine allows us to typecheck complex/recursive expressions
1391/// where the declaration is needed for type checking. Here are some
1392/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1393static Decl *getPrimaryDeclaration(Expr *e) {
1394 switch (e->getStmtClass()) {
1395 case Stmt::DeclRefExprClass:
1396 return cast<DeclRefExpr>(e)->getDecl();
1397 case Stmt::MemberExprClass:
1398 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1399 case Stmt::ArraySubscriptExprClass:
1400 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1401 case Stmt::CallExprClass:
1402 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1403 case Stmt::UnaryOperatorClass:
1404 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1405 case Stmt::ParenExprClass:
1406 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1407 default:
1408 return 0;
1409 }
1410}
1411
1412/// CheckAddressOfOperand - The operand of & must be either a function
1413/// designator or an lvalue designating an object. If it is an lvalue, the
1414/// object cannot be declared with storage class register or be a bit field.
1415/// Note: The usual conversions are *not* applied to the operand of the &
1416/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1417QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1418 Decl *dcl = getPrimaryDeclaration(op);
1419 Expr::isLvalueResult lval = op->isLvalue();
1420
1421 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1422 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1423 ;
1424 else { // FIXME: emit more specific diag...
1425 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1426 op->getSourceRange());
1427 return QualType();
1428 }
1429 } else if (dcl) {
1430 // We have an lvalue with a decl. Make sure the decl is not declared
1431 // with the register storage-class specifier.
1432 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1433 if (vd->getStorageClass() == VarDecl::Register) {
1434 Diag(OpLoc, diag::err_typecheck_address_of_register,
1435 op->getSourceRange());
1436 return QualType();
1437 }
1438 } else
1439 assert(0 && "Unknown/unexpected decl type");
1440
1441 // FIXME: add check for bitfields!
1442 }
1443 // If the operand has type "type", the result has type "pointer to type".
1444 return Context.getPointerType(op->getType());
1445}
1446
1447QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1448 UsualUnaryConversions(op);
1449 QualType qType = op->getType();
1450
Chris Lattner7931f4a2007-07-31 16:53:04 +00001451 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001452 QualType ptype = PT->getPointeeType();
1453 // C99 6.5.3.2p4. "if it points to an object,...".
1454 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1455 // GCC compat: special case 'void *' (treat as warning).
1456 if (ptype->isVoidType()) {
1457 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1458 qType.getAsString(), op->getSourceRange());
1459 } else {
1460 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1461 ptype.getAsString(), op->getSourceRange());
1462 return QualType();
1463 }
1464 }
1465 return ptype;
1466 }
1467 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1468 qType.getAsString(), op->getSourceRange());
1469 return QualType();
1470}
1471
1472static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1473 tok::TokenKind Kind) {
1474 BinaryOperator::Opcode Opc;
1475 switch (Kind) {
1476 default: assert(0 && "Unknown binop!");
1477 case tok::star: Opc = BinaryOperator::Mul; break;
1478 case tok::slash: Opc = BinaryOperator::Div; break;
1479 case tok::percent: Opc = BinaryOperator::Rem; break;
1480 case tok::plus: Opc = BinaryOperator::Add; break;
1481 case tok::minus: Opc = BinaryOperator::Sub; break;
1482 case tok::lessless: Opc = BinaryOperator::Shl; break;
1483 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1484 case tok::lessequal: Opc = BinaryOperator::LE; break;
1485 case tok::less: Opc = BinaryOperator::LT; break;
1486 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1487 case tok::greater: Opc = BinaryOperator::GT; break;
1488 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1489 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1490 case tok::amp: Opc = BinaryOperator::And; break;
1491 case tok::caret: Opc = BinaryOperator::Xor; break;
1492 case tok::pipe: Opc = BinaryOperator::Or; break;
1493 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1494 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1495 case tok::equal: Opc = BinaryOperator::Assign; break;
1496 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1497 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1498 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1499 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1500 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1501 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1502 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1503 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1504 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1505 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1506 case tok::comma: Opc = BinaryOperator::Comma; break;
1507 }
1508 return Opc;
1509}
1510
1511static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1512 tok::TokenKind Kind) {
1513 UnaryOperator::Opcode Opc;
1514 switch (Kind) {
1515 default: assert(0 && "Unknown unary op!");
1516 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1517 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1518 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1519 case tok::star: Opc = UnaryOperator::Deref; break;
1520 case tok::plus: Opc = UnaryOperator::Plus; break;
1521 case tok::minus: Opc = UnaryOperator::Minus; break;
1522 case tok::tilde: Opc = UnaryOperator::Not; break;
1523 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1524 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1525 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1526 case tok::kw___real: Opc = UnaryOperator::Real; break;
1527 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1528 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1529 }
1530 return Opc;
1531}
1532
1533// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001534Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001535 ExprTy *LHS, ExprTy *RHS) {
1536 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1537 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1538
Steve Naroff87d58b42007-09-16 03:34:24 +00001539 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1540 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001541
1542 QualType ResultTy; // Result type of the binary operator.
1543 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1544
1545 switch (Opc) {
1546 default:
1547 assert(0 && "Unknown binary expr!");
1548 case BinaryOperator::Assign:
1549 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1550 break;
1551 case BinaryOperator::Mul:
1552 case BinaryOperator::Div:
1553 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1554 break;
1555 case BinaryOperator::Rem:
1556 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1557 break;
1558 case BinaryOperator::Add:
1559 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1560 break;
1561 case BinaryOperator::Sub:
1562 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1563 break;
1564 case BinaryOperator::Shl:
1565 case BinaryOperator::Shr:
1566 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1567 break;
1568 case BinaryOperator::LE:
1569 case BinaryOperator::LT:
1570 case BinaryOperator::GE:
1571 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001572 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001573 break;
1574 case BinaryOperator::EQ:
1575 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001576 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001577 break;
1578 case BinaryOperator::And:
1579 case BinaryOperator::Xor:
1580 case BinaryOperator::Or:
1581 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1582 break;
1583 case BinaryOperator::LAnd:
1584 case BinaryOperator::LOr:
1585 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1586 break;
1587 case BinaryOperator::MulAssign:
1588 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001589 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001590 if (!CompTy.isNull())
1591 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1592 break;
1593 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001594 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001595 if (!CompTy.isNull())
1596 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1597 break;
1598 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001599 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001600 if (!CompTy.isNull())
1601 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1602 break;
1603 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001604 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001605 if (!CompTy.isNull())
1606 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1607 break;
1608 case BinaryOperator::ShlAssign:
1609 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001610 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001611 if (!CompTy.isNull())
1612 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1613 break;
1614 case BinaryOperator::AndAssign:
1615 case BinaryOperator::XorAssign:
1616 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001617 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001618 if (!CompTy.isNull())
1619 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1620 break;
1621 case BinaryOperator::Comma:
1622 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1623 break;
1624 }
1625 if (ResultTy.isNull())
1626 return true;
1627 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001628 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001629 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001630 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001631}
1632
1633// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001634Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001635 ExprTy *input) {
1636 Expr *Input = (Expr*)input;
1637 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1638 QualType resultType;
1639 switch (Opc) {
1640 default:
1641 assert(0 && "Unimplemented unary expr!");
1642 case UnaryOperator::PreInc:
1643 case UnaryOperator::PreDec:
1644 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1645 break;
1646 case UnaryOperator::AddrOf:
1647 resultType = CheckAddressOfOperand(Input, OpLoc);
1648 break;
1649 case UnaryOperator::Deref:
1650 resultType = CheckIndirectionOperand(Input, OpLoc);
1651 break;
1652 case UnaryOperator::Plus:
1653 case UnaryOperator::Minus:
1654 UsualUnaryConversions(Input);
1655 resultType = Input->getType();
1656 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1657 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1658 resultType.getAsString());
1659 break;
1660 case UnaryOperator::Not: // bitwise complement
1661 UsualUnaryConversions(Input);
1662 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001663 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1664 if (!resultType->isIntegerType()) {
1665 if (resultType->isComplexType())
1666 // C99 does not support '~' for complex conjugation.
1667 Diag(OpLoc, diag::ext_integer_complement_complex,
1668 resultType.getAsString());
1669 else
1670 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1671 resultType.getAsString());
1672 }
Chris Lattner4b009652007-07-25 00:24:17 +00001673 break;
1674 case UnaryOperator::LNot: // logical negation
1675 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1676 DefaultFunctionArrayConversion(Input);
1677 resultType = Input->getType();
1678 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1679 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1680 resultType.getAsString());
1681 // LNot always has type int. C99 6.5.3.3p5.
1682 resultType = Context.IntTy;
1683 break;
1684 case UnaryOperator::SizeOf:
1685 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1686 break;
1687 case UnaryOperator::AlignOf:
1688 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1689 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001690 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001691 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001692 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001693 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001694 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001695 resultType = Input->getType();
1696 break;
1697 }
1698 if (resultType.isNull())
1699 return true;
1700 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1701}
1702
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001703/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1704Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001705 SourceLocation LabLoc,
1706 IdentifierInfo *LabelII) {
1707 // Look up the record for this label identifier.
1708 LabelStmt *&LabelDecl = LabelMap[LabelII];
1709
1710 // If we haven't seen this label yet, create a forward reference.
1711 if (LabelDecl == 0)
1712 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1713
1714 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001715 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1716 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001717}
1718
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001719Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00001720 SourceLocation RPLoc) { // "({..})"
1721 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1722 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1723 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1724
1725 // FIXME: there are a variety of strange constraints to enforce here, for
1726 // example, it is not possible to goto into a stmt expression apparently.
1727 // More semantic analysis is needed.
1728
1729 // FIXME: the last statement in the compount stmt has its value used. We
1730 // should not warn about it being unused.
1731
1732 // If there are sub stmts in the compound stmt, take the type of the last one
1733 // as the type of the stmtexpr.
1734 QualType Ty = Context.VoidTy;
1735
1736 if (!Compound->body_empty())
1737 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1738 Ty = LastExpr->getType();
1739
1740 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1741}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001742
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001743Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001744 SourceLocation TypeLoc,
1745 TypeTy *argty,
1746 OffsetOfComponent *CompPtr,
1747 unsigned NumComponents,
1748 SourceLocation RPLoc) {
1749 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1750 assert(!ArgTy.isNull() && "Missing type argument!");
1751
1752 // We must have at least one component that refers to the type, and the first
1753 // one is known to be a field designator. Verify that the ArgTy represents
1754 // a struct/union/class.
1755 if (!ArgTy->isRecordType())
1756 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1757
1758 // Otherwise, create a compound literal expression as the base, and
1759 // iteratively process the offsetof designators.
1760 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1761
Chris Lattnerb37522e2007-08-31 21:49:13 +00001762 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1763 // GCC extension, diagnose them.
1764 if (NumComponents != 1)
1765 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1766 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1767
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001768 for (unsigned i = 0; i != NumComponents; ++i) {
1769 const OffsetOfComponent &OC = CompPtr[i];
1770 if (OC.isBrackets) {
1771 // Offset of an array sub-field. TODO: Should we allow vector elements?
1772 const ArrayType *AT = Res->getType()->getAsArrayType();
1773 if (!AT) {
1774 delete Res;
1775 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1776 Res->getType().getAsString());
1777 }
1778
Chris Lattner2af6a802007-08-30 17:59:59 +00001779 // FIXME: C++: Verify that operator[] isn't overloaded.
1780
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001781 // C99 6.5.2.1p1
1782 Expr *Idx = static_cast<Expr*>(OC.U.E);
1783 if (!Idx->getType()->isIntegerType())
1784 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1785 Idx->getSourceRange());
1786
1787 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1788 continue;
1789 }
1790
1791 const RecordType *RC = Res->getType()->getAsRecordType();
1792 if (!RC) {
1793 delete Res;
1794 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1795 Res->getType().getAsString());
1796 }
1797
1798 // Get the decl corresponding to this.
1799 RecordDecl *RD = RC->getDecl();
1800 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1801 if (!MemberDecl)
1802 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1803 OC.U.IdentInfo->getName(),
1804 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00001805
1806 // FIXME: C++: Verify that MemberDecl isn't a static field.
1807 // FIXME: Verify that MemberDecl isn't a bitfield.
1808
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001809 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1810 }
1811
1812 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1813 BuiltinLoc);
1814}
1815
1816
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001817Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001818 TypeTy *arg1, TypeTy *arg2,
1819 SourceLocation RPLoc) {
1820 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1821 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1822
1823 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1824
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001825 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001826}
1827
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001828Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00001829 ExprTy *expr1, ExprTy *expr2,
1830 SourceLocation RPLoc) {
1831 Expr *CondExpr = static_cast<Expr*>(cond);
1832 Expr *LHSExpr = static_cast<Expr*>(expr1);
1833 Expr *RHSExpr = static_cast<Expr*>(expr2);
1834
1835 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1836
1837 // The conditional expression is required to be a constant expression.
1838 llvm::APSInt condEval(32);
1839 SourceLocation ExpLoc;
1840 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1841 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1842 CondExpr->getSourceRange());
1843
1844 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1845 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1846 RHSExpr->getType();
1847 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1848}
1849
Anders Carlssona66cad42007-08-21 17:43:55 +00001850// TODO: Move this to SemaObjC.cpp
Anders Carlsson8be1d402007-08-22 15:14:15 +00001851Sema::ExprResult Sema::ParseObjCStringLiteral(ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00001852 StringLiteral* S = static_cast<StringLiteral *>(string);
1853
1854 if (CheckBuiltinCFStringArgument(S))
1855 return true;
1856
1857 QualType t = Context.getCFConstantStringType();
1858 t = t.getQualifiedType(QualType::Const);
1859 t = Context.getPointerType(t);
1860
1861 return new ObjCStringLiteral(S, t);
1862}
Anders Carlsson8be1d402007-08-22 15:14:15 +00001863
1864Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1865 SourceLocation LParenLoc,
1866 TypeTy *Ty,
1867 SourceLocation RParenLoc) {
1868 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
1869
1870 QualType t = Context.getPointerType(Context.CharTy);
1871 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
1872}
Steve Naroffd3f5ee42007-09-17 21:01:15 +00001873
Steve Naroff4ed9d662007-09-27 14:38:14 +00001874// ActOnClassMessage - used for both unary and keyword messages.
1875// ArgExprs is optional - if it is present, the number of expressions
1876// is obtained from Sel.getNumArgs().
1877Sema::ExprResult Sema::ActOnClassMessage(
1878 IdentifierInfo *receivingClassName, SelectorInfo *Sel,
1879 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args)
Steve Naroffd3f5ee42007-09-17 21:01:15 +00001880{
Steve Naroffc39ca262007-09-18 23:55:05 +00001881 assert(receivingClassName && "missing receiver class name");
1882
Steve Naroff4ed9d662007-09-27 14:38:14 +00001883 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
1884 return new ObjCMessageExpr(receivingClassName, Sel,
1885 Context.IntTy/*FIXME*/, lbrac, rbrac, ArgExprs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00001886}
1887
Steve Naroff4ed9d662007-09-27 14:38:14 +00001888// ActOnInstanceMessage - used for both unary and keyword messages.
1889// ArgExprs is optional - if it is present, the number of expressions
1890// is obtained from Sel.getNumArgs().
1891Sema::ExprResult Sema::ActOnInstanceMessage(
1892 ExprTy *receiver, SelectorInfo *Sel,
1893 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args)
1894{
Steve Naroffc39ca262007-09-18 23:55:05 +00001895 assert(receiver && "missing receiver expression");
1896
1897 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Naroff4ed9d662007-09-27 14:38:14 +00001898 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
1899 return new ObjCMessageExpr(RExpr, Sel,
1900 Context.IntTy/*FIXME*/, lbrac, rbrac, ArgExprs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00001901}