blob: 11c3eccb36a7b3662db3d64cc47d3b1e0fafeaee [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()) {
153 // FIXME: handle float values > 32 (including compute the real type...).
154 QualType Ty = Literal.isFloat ? Context.FloatTy : Context.DoubleTy;
155 Res = new FloatingLiteral(Literal.GetFloatValue(), Ty, Tok.getLocation());
156 } else if (!Literal.isIntegerLiteral()) {
157 return ExprResult(true);
158 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000159 QualType t;
160
Neil Booth7421e9c2007-08-29 22:00:19 +0000161 // long long is a C99 feature.
162 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000163 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000164 Diag(Tok.getLocation(), diag::ext_longlong);
165
Chris Lattner4b009652007-07-25 00:24:17 +0000166 // Get the value in the widest-possible width.
167 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
168
169 if (Literal.GetIntegerValue(ResultVal)) {
170 // If this value didn't fit into uintmax_t, warn and force to ull.
171 Diag(Tok.getLocation(), diag::warn_integer_too_large);
172 t = Context.UnsignedLongLongTy;
173 assert(Context.getTypeSize(t, Tok.getLocation()) ==
174 ResultVal.getBitWidth() && "long long is not intmax_t?");
175 } else {
176 // If this value fits into a ULL, try to figure out what else it fits into
177 // according to the rules of C99 6.4.4.1p5.
178
179 // Octal, Hexadecimal, and integers with a U suffix are allowed to
180 // be an unsigned int.
181 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
182
183 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000184 if (!Literal.isLong && !Literal.isLongLong) {
185 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000186 unsigned IntSize = static_cast<unsigned>(
187 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000188 // Does it fit in a unsigned int?
189 if (ResultVal.isIntN(IntSize)) {
190 // Does it fit in a signed int?
191 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
192 t = Context.IntTy;
193 else if (AllowUnsigned)
194 t = Context.UnsignedIntTy;
195 }
196
197 if (!t.isNull())
198 ResultVal.trunc(IntSize);
199 }
200
201 // Are long/unsigned long possibilities?
202 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000203 unsigned LongSize = static_cast<unsigned>(
204 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000205
206 // Does it fit in a unsigned long?
207 if (ResultVal.isIntN(LongSize)) {
208 // Does it fit in a signed long?
209 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
210 t = Context.LongTy;
211 else if (AllowUnsigned)
212 t = Context.UnsignedLongTy;
213 }
214 if (!t.isNull())
215 ResultVal.trunc(LongSize);
216 }
217
218 // Finally, check long long if needed.
219 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000220 unsigned LongLongSize = static_cast<unsigned>(
221 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000222
223 // Does it fit in a unsigned long long?
224 if (ResultVal.isIntN(LongLongSize)) {
225 // Does it fit in a signed long long?
226 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
227 t = Context.LongLongTy;
228 else if (AllowUnsigned)
229 t = Context.UnsignedLongLongTy;
230 }
231 }
232
233 // If we still couldn't decide a type, we probably have something that
234 // does not fit in a signed long long, but has no U suffix.
235 if (t.isNull()) {
236 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
237 t = Context.UnsignedLongLongTy;
238 }
239 }
240
Chris Lattner1de66eb2007-08-26 03:42:43 +0000241 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000242 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000243
244 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
245 if (Literal.isImaginary)
246 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
247
248 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000249}
250
Steve Naroff87d58b42007-09-16 03:34:24 +0000251Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000252 ExprTy *Val) {
253 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000254 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000255 return new ParenExpr(L, R, e);
256}
257
258/// The UsualUnaryConversions() function is *not* called by this routine.
259/// See C99 6.3.2.1p[2-4] for more details.
260QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
261 SourceLocation OpLoc, bool isSizeof) {
262 // C99 6.5.3.4p1:
263 if (isa<FunctionType>(exprType) && isSizeof)
264 // alignof(function) is allowed.
265 Diag(OpLoc, diag::ext_sizeof_function_type);
266 else if (exprType->isVoidType())
267 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
268 else if (exprType->isIncompleteType()) {
269 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
270 diag::err_alignof_incomplete_type,
271 exprType.getAsString());
272 return QualType(); // error
273 }
274 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
275 return Context.getSizeType();
276}
277
278Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000279ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000280 SourceLocation LPLoc, TypeTy *Ty,
281 SourceLocation RPLoc) {
282 // If error parsing type, ignore.
283 if (Ty == 0) return true;
284
285 // Verify that this is a valid expression.
286 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
287
288 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
289
290 if (resultType.isNull())
291 return true;
292 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
293}
294
Chris Lattner5110ad52007-08-24 21:41:10 +0000295QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000296 DefaultFunctionArrayConversion(V);
297
Chris Lattnera16e42d2007-08-26 05:39:26 +0000298 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000299 if (const ComplexType *CT = V->getType()->getAsComplexType())
300 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000301
302 // Otherwise they pass through real integer and floating point types here.
303 if (V->getType()->isArithmeticType())
304 return V->getType();
305
306 // Reject anything else.
307 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
308 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000309}
310
311
Chris Lattner4b009652007-07-25 00:24:17 +0000312
Steve Naroff87d58b42007-09-16 03:34:24 +0000313Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000314 tok::TokenKind Kind,
315 ExprTy *Input) {
316 UnaryOperator::Opcode Opc;
317 switch (Kind) {
318 default: assert(0 && "Unknown unary op!");
319 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
320 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
321 }
322 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
323 if (result.isNull())
324 return true;
325 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
326}
327
328Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000329ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000330 ExprTy *Idx, SourceLocation RLoc) {
331 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
332
333 // Perform default conversions.
334 DefaultFunctionArrayConversion(LHSExp);
335 DefaultFunctionArrayConversion(RHSExp);
336
337 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
338
339 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000340 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000341 // in the subscript position. As a result, we need to derive the array base
342 // and index from the expression types.
343 Expr *BaseExpr, *IndexExpr;
344 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000345 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000346 BaseExpr = LHSExp;
347 IndexExpr = RHSExp;
348 // FIXME: need to deal with const...
349 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000350 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000351 // Handle the uncommon case of "123[Ptr]".
352 BaseExpr = RHSExp;
353 IndexExpr = LHSExp;
354 // FIXME: need to deal with const...
355 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000356 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
357 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000358 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000359
360 // Component access limited to variables (reject vec4.rg[1]).
361 if (!isa<DeclRefExpr>(BaseExpr))
362 return Diag(LLoc, diag::err_ocuvector_component_access,
363 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000364 // FIXME: need to deal with const...
365 ResultType = VTy->getElementType();
366 } else {
367 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
368 RHSExp->getSourceRange());
369 }
370 // C99 6.5.2.1p1
371 if (!IndexExpr->getType()->isIntegerType())
372 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
373 IndexExpr->getSourceRange());
374
375 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
376 // the following check catches trying to index a pointer to a function (e.g.
377 // void (*)(int)). Functions are not objects in C99.
378 if (!ResultType->isObjectType())
379 return Diag(BaseExpr->getLocStart(),
380 diag::err_typecheck_subscript_not_object,
381 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
382
383 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
384}
385
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000386QualType Sema::
387CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
388 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000389 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000390
391 // The vector accessor can't exceed the number of elements.
392 const char *compStr = CompName.getName();
393 if (strlen(compStr) > vecType->getNumElements()) {
394 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
395 baseType.getAsString(), SourceRange(CompLoc));
396 return QualType();
397 }
398 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000399 if (vecType->getPointAccessorIdx(*compStr) != -1) {
400 do
401 compStr++;
402 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
403 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
404 do
405 compStr++;
406 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
407 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
408 do
409 compStr++;
410 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
411 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000412
413 if (*compStr) {
414 // We didn't get to the end of the string. This means the component names
415 // didn't come from the same set *or* we encountered an illegal name.
416 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
417 std::string(compStr,compStr+1), SourceRange(CompLoc));
418 return QualType();
419 }
420 // Each component accessor can't exceed the vector type.
421 compStr = CompName.getName();
422 while (*compStr) {
423 if (vecType->isAccessorWithinNumElements(*compStr))
424 compStr++;
425 else
426 break;
427 }
428 if (*compStr) {
429 // We didn't get to the end of the string. This means a component accessor
430 // exceeds the number of elements in the vector.
431 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
432 baseType.getAsString(), SourceRange(CompLoc));
433 return QualType();
434 }
435 // The component accessor looks fine - now we need to compute the actual type.
436 // The vector type is implied by the component accessor. For example,
437 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
438 unsigned CompSize = strlen(CompName.getName());
439 if (CompSize == 1)
440 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000441
442 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
443 // Now look up the TypeDefDecl from the vector type. Without this,
444 // diagostics look bad. We want OCU vector types to appear built-in.
445 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
446 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
447 return Context.getTypedefType(OCUVectorDecls[i]);
448 }
449 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000450}
451
Chris Lattner4b009652007-07-25 00:24:17 +0000452Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000453ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000454 tok::TokenKind OpKind, SourceLocation MemberLoc,
455 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000456 Expr *BaseExpr = static_cast<Expr *>(Base);
457 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000458
Steve Naroff2cb66382007-07-26 03:11:44 +0000459 QualType BaseType = BaseExpr->getType();
460 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000461
Chris Lattner4b009652007-07-25 00:24:17 +0000462 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000463 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000464 BaseType = PT->getPointeeType();
465 else
466 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
467 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000468 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000469 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000470 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000471 RecordDecl *RDecl = RTy->getDecl();
472 if (RTy->isIncompleteType())
473 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
474 BaseExpr->getSourceRange());
475 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000476 FieldDecl *MemberDecl = RDecl->getMember(&Member);
477 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000478 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
479 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000480 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
481 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000482 // Component access limited to variables (reject vec4.rg.g).
483 if (!isa<DeclRefExpr>(BaseExpr))
484 return Diag(OpLoc, diag::err_ocuvector_component_access,
485 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000486 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
487 if (ret.isNull())
488 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000489 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Steve Naroff2cb66382007-07-26 03:11:44 +0000490 } else
491 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
492 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000493}
494
Steve Naroff87d58b42007-09-16 03:34:24 +0000495/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000496/// This provides the location of the left/right parens and a list of comma
497/// locations.
498Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000499ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000500 ExprTy **args, unsigned NumArgsInCall,
501 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
502 Expr *Fn = static_cast<Expr *>(fn);
503 Expr **Args = reinterpret_cast<Expr**>(args);
504 assert(Fn && "no function call expression");
505
506 UsualUnaryConversions(Fn);
507 QualType funcType = Fn->getType();
508
509 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
510 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000511 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000512 if (PT == 0)
513 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
514 SourceRange(Fn->getLocStart(), RParenLoc));
515
Chris Lattner71225142007-07-31 21:27:01 +0000516 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000517 if (funcT == 0)
518 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
519 SourceRange(Fn->getLocStart(), RParenLoc));
520
521 // If a prototype isn't declared, the parser implicitly defines a func decl
522 QualType resultType = funcT->getResultType();
523
524 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
525 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
526 // assignment, to the types of the corresponding parameter, ...
527
528 unsigned NumArgsInProto = proto->getNumArgs();
529 unsigned NumArgsToCheck = NumArgsInCall;
530
531 if (NumArgsInCall < NumArgsInProto)
532 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
533 Fn->getSourceRange());
534 else if (NumArgsInCall > NumArgsInProto) {
535 if (!proto->isVariadic()) {
536 Diag(Args[NumArgsInProto]->getLocStart(),
537 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
538 SourceRange(Args[NumArgsInProto]->getLocStart(),
539 Args[NumArgsInCall-1]->getLocEnd()));
540 }
541 NumArgsToCheck = NumArgsInProto;
542 }
543 // Continue to check argument types (even if we have too few/many args).
544 for (unsigned i = 0; i < NumArgsToCheck; i++) {
545 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000546 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000547
548 QualType lhsType = proto->getArgType(i);
549 QualType rhsType = argExpr->getType();
550
Steve Naroff75644062007-07-25 20:45:33 +0000551 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000552 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000553 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000554 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000555 lhsType = Context.getPointerType(lhsType);
556
557 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
558 argExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000559 if (Args[i] != argExpr) // The expression was converted.
560 Args[i] = argExpr; // Make sure we store the converted expression.
Chris Lattner4b009652007-07-25 00:24:17 +0000561 SourceLocation l = argExpr->getLocStart();
562
563 // decode the result (notice that AST's are still created for extensions).
564 switch (result) {
565 case Compatible:
566 break;
567 case PointerFromInt:
568 // check for null pointer constant (C99 6.3.2.3p3)
569 if (!argExpr->isNullPointerConstant(Context)) {
570 Diag(l, diag::ext_typecheck_passing_pointer_int,
571 lhsType.getAsString(), rhsType.getAsString(),
572 Fn->getSourceRange(), argExpr->getSourceRange());
573 }
574 break;
575 case IntFromPointer:
576 Diag(l, diag::ext_typecheck_passing_pointer_int,
577 lhsType.getAsString(), rhsType.getAsString(),
578 Fn->getSourceRange(), argExpr->getSourceRange());
579 break;
580 case IncompatiblePointer:
581 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
582 rhsType.getAsString(), lhsType.getAsString(),
583 Fn->getSourceRange(), argExpr->getSourceRange());
584 break;
585 case CompatiblePointerDiscardsQualifiers:
586 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
587 rhsType.getAsString(), lhsType.getAsString(),
588 Fn->getSourceRange(), argExpr->getSourceRange());
589 break;
590 case Incompatible:
591 return Diag(l, diag::err_typecheck_passing_incompatible,
592 rhsType.getAsString(), lhsType.getAsString(),
593 Fn->getSourceRange(), argExpr->getSourceRange());
594 }
595 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000596 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
597 // Promote the arguments (C99 6.5.2.2p7).
598 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
599 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000600 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000601
602 DefaultArgumentPromotion(argExpr);
603 if (Args[i] != argExpr) // The expression was converted.
604 Args[i] = argExpr; // Make sure we store the converted expression.
605 }
606 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
607 // Even if the types checked, bail if the number of arguments don't match.
Chris Lattner4b009652007-07-25 00:24:17 +0000608 return true;
Steve Naroffdb65e052007-08-28 23:30:39 +0000609 }
610 } else if (isa<FunctionTypeNoProto>(funcT)) {
611 // Promote the arguments (C99 6.5.2.2p6).
612 for (unsigned i = 0; 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 }
Chris Lattner4b009652007-07-25 00:24:17 +0000620 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000621 // Do special checking on direct calls to functions.
622 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
623 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
624 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000625 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
626 NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000627 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000628
Chris Lattner4b009652007-07-25 00:24:17 +0000629 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
630}
631
632Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000633ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000634 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000635 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000636 QualType literalType = QualType::getFromOpaquePtr(Ty);
637 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000638 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000639 Expr *literalExpr = static_cast<Expr*>(InitExpr);
640
641 // FIXME: add semantic analysis (C99 6.5.2.5).
642 return new CompoundLiteralExpr(literalType, literalExpr);
643}
644
645Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000646ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000647 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000648 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000649
Steve Naroff0acc9c92007-09-15 18:49:24 +0000650 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000651 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000652
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000653 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
654 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
655 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000656}
657
658Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000659ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000660 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000661 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000662
663 Expr *castExpr = static_cast<Expr*>(Op);
664 QualType castType = QualType::getFromOpaquePtr(Ty);
665
Steve Naroff68adb482007-08-31 00:32:44 +0000666 UsualUnaryConversions(castExpr);
667
Chris Lattner4b009652007-07-25 00:24:17 +0000668 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
669 // type needs to be scalar.
670 if (!castType->isScalarType() && !castType->isVoidType()) {
671 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
672 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
673 }
674 if (!castExpr->getType()->isScalarType()) {
675 return Diag(castExpr->getLocStart(),
676 diag::err_typecheck_expect_scalar_operand,
677 castExpr->getType().getAsString(), castExpr->getSourceRange());
678 }
679 return new CastExpr(castType, castExpr, LParenLoc);
680}
681
682inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
683 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
684 UsualUnaryConversions(cond);
685 UsualUnaryConversions(lex);
686 UsualUnaryConversions(rex);
687 QualType condT = cond->getType();
688 QualType lexT = lex->getType();
689 QualType rexT = rex->getType();
690
691 // first, check the condition.
692 if (!condT->isScalarType()) { // C99 6.5.15p2
693 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
694 condT.getAsString());
695 return QualType();
696 }
697 // now check the two expressions.
698 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
699 UsualArithmeticConversions(lex, rex);
700 return lex->getType();
701 }
Chris Lattner71225142007-07-31 21:27:01 +0000702 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
703 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
704
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000705 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
Chris Lattner71225142007-07-31 21:27:01 +0000706 return lexT;
707
Chris Lattner4b009652007-07-25 00:24:17 +0000708 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
709 lexT.getAsString(), rexT.getAsString(),
710 lex->getSourceRange(), rex->getSourceRange());
711 return QualType();
712 }
713 }
714 // C99 6.5.15p3
715 if (lexT->isPointerType() && rex->isNullPointerConstant(Context))
716 return lexT;
717 if (rexT->isPointerType() && lex->isNullPointerConstant(Context))
718 return rexT;
719
Chris Lattner71225142007-07-31 21:27:01 +0000720 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
721 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
722 // get the "pointed to" types
723 QualType lhptee = LHSPT->getPointeeType();
724 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000725
Chris Lattner71225142007-07-31 21:27:01 +0000726 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
727 if (lhptee->isVoidType() &&
728 (rhptee->isObjectType() || rhptee->isIncompleteType()))
729 return lexT;
730 if (rhptee->isVoidType() &&
731 (lhptee->isObjectType() || lhptee->isIncompleteType()))
732 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000733
Chris Lattner71225142007-07-31 21:27:01 +0000734 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
735 rhptee.getUnqualifiedType())) {
736 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
737 lexT.getAsString(), rexT.getAsString(),
738 lex->getSourceRange(), rex->getSourceRange());
739 return lexT; // FIXME: this is an _ext - is this return o.k?
740 }
741 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000742 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
743 // differently qualified versions of compatible types, the result type is
744 // a pointer to an appropriately qualified version of the *composite*
745 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000746 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000747 }
Chris Lattner4b009652007-07-25 00:24:17 +0000748 }
Chris Lattner71225142007-07-31 21:27:01 +0000749
Chris Lattner4b009652007-07-25 00:24:17 +0000750 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
751 return lexT;
752
753 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
754 lexT.getAsString(), rexT.getAsString(),
755 lex->getSourceRange(), rex->getSourceRange());
756 return QualType();
757}
758
Steve Naroff87d58b42007-09-16 03:34:24 +0000759/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000760/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000761Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000762 SourceLocation ColonLoc,
763 ExprTy *Cond, ExprTy *LHS,
764 ExprTy *RHS) {
765 Expr *CondExpr = (Expr *) Cond;
766 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
767 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
768 RHSExpr, QuestionLoc);
769 if (result.isNull())
770 return true;
771 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
772}
773
774// promoteExprToType - a helper function to ensure we create exactly one
775// ImplicitCastExpr. As a convenience (to the caller), we return the type.
776static void promoteExprToType(Expr *&expr, QualType type) {
777 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
778 impCast->setType(type);
779 else
780 expr = new ImplicitCastExpr(type, expr);
781 return;
782}
783
Steve Naroffdb65e052007-08-28 23:30:39 +0000784/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
785/// do not have a prototype. Integer promotions are performed on each
786/// argument, and arguments that have type float are promoted to double.
787void Sema::DefaultArgumentPromotion(Expr *&expr) {
788 QualType t = expr->getType();
789 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
790
791 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
792 promoteExprToType(expr, Context.IntTy);
793 if (t == Context.FloatTy)
794 promoteExprToType(expr, Context.DoubleTy);
795}
796
Chris Lattner4b009652007-07-25 00:24:17 +0000797/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
798void Sema::DefaultFunctionArrayConversion(Expr *&e) {
799 QualType t = e->getType();
800 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
801
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000802 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000803 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
804 t = e->getType();
805 }
806 if (t->isFunctionType())
807 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000808 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000809 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
810}
811
812/// UsualUnaryConversion - Performs various conversions that are common to most
813/// operators (C99 6.3). The conversions of array and function types are
814/// sometimes surpressed. For example, the array->pointer conversion doesn't
815/// apply if the array is an argument to the sizeof or address (&) operators.
816/// In these instances, this routine should *not* be called.
817void Sema::UsualUnaryConversions(Expr *&expr) {
818 QualType t = expr->getType();
819 assert(!t.isNull() && "UsualUnaryConversions - missing type");
820
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000821 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000822 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
823 t = expr->getType();
824 }
825 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
826 promoteExprToType(expr, Context.IntTy);
827 else
828 DefaultFunctionArrayConversion(expr);
829}
830
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000831/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000832/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
833/// routine returns the first non-arithmetic type found. The client is
834/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000835QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
836 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000837 if (!isCompAssign) {
838 UsualUnaryConversions(lhsExpr);
839 UsualUnaryConversions(rhsExpr);
840 }
Chris Lattner4b009652007-07-25 00:24:17 +0000841 QualType lhs = lhsExpr->getType();
842 QualType rhs = rhsExpr->getType();
843
844 // If both types are identical, no conversion is needed.
845 if (lhs == rhs)
Steve Naroff8f708362007-08-24 19:07:16 +0000846 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000847
848 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
849 // The caller can deal with this (e.g. pointer + int).
850 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000851 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000852
853 // At this point, we have two different arithmetic types.
854
855 // Handle complex types first (C99 6.3.1.8p1).
856 if (lhs->isComplexType() || rhs->isComplexType()) {
857 // if we have an integer operand, the result is the complex type.
858 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000859 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
860 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000861 }
862 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000863 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
864 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000865 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000866 // This handles complex/complex, complex/float, or float/complex.
867 // When both operands are complex, the shorter operand is converted to the
868 // type of the longer, and that is the type of the result. This corresponds
869 // to what is done when combining two real floating-point operands.
870 // The fun begins when size promotion occur across type domains.
871 // From H&S 6.3.4: When one operand is complex and the other is a real
872 // floating-point type, the less precise type is converted, within it's
873 // real or complex domain, to the precision of the other type. For example,
874 // when combining a "long double" with a "double _Complex", the
875 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000876 int result = Context.compareFloatingType(lhs, rhs);
877
878 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000879 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
880 if (!isCompAssign)
881 promoteExprToType(rhsExpr, rhs);
882 } else if (result < 0) { // The right side is bigger, convert lhs.
883 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
884 if (!isCompAssign)
885 promoteExprToType(lhsExpr, lhs);
886 }
887 // At this point, lhs and rhs have the same rank/size. Now, make sure the
888 // domains match. This is a requirement for our implementation, C99
889 // does not require this promotion.
890 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
891 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000892 if (!isCompAssign)
893 promoteExprToType(lhsExpr, rhs);
894 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000895 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000896 if (!isCompAssign)
897 promoteExprToType(rhsExpr, lhs);
898 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000899 }
Chris Lattner4b009652007-07-25 00:24:17 +0000900 }
Steve Naroff3b6157f2007-08-27 21:43:43 +0000901 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +0000902 }
903 // Now handle "real" floating types (i.e. float, double, long double).
904 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
905 // if we have an integer operand, the result is the real floating type.
906 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000907 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
908 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000909 }
910 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000911 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
912 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000913 }
914 // We have two real floating types, float/complex combos were handled above.
915 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +0000916 int result = Context.compareFloatingType(lhs, rhs);
917
918 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000919 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
920 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000921 }
Steve Naroff45fc9822007-08-27 15:30:22 +0000922 if (result < 0) { // convert the lhs
923 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
924 return rhs;
925 }
926 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +0000927 }
928 // Finally, we have two differing integer types.
929 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000930 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
931 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000932 }
Steve Naroff8f708362007-08-24 19:07:16 +0000933 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
934 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000935}
936
937// CheckPointerTypesForAssignment - This is a very tricky routine (despite
938// being closely modeled after the C99 spec:-). The odd characteristic of this
939// routine is it effectively iqnores the qualifiers on the top level pointee.
940// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
941// FIXME: add a couple examples in this comment.
942Sema::AssignmentCheckResult
943Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
944 QualType lhptee, rhptee;
945
946 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +0000947 lhptee = lhsType->getAsPointerType()->getPointeeType();
948 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000949
950 // make sure we operate on the canonical type
951 lhptee = lhptee.getCanonicalType();
952 rhptee = rhptee.getCanonicalType();
953
954 AssignmentCheckResult r = Compatible;
955
956 // C99 6.5.16.1p1: This following citation is common to constraints
957 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
958 // qualifiers of the type *pointed to* by the right;
959 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
960 rhptee.getQualifiers())
961 r = CompatiblePointerDiscardsQualifiers;
962
963 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
964 // incomplete type and the other is a pointer to a qualified or unqualified
965 // version of void...
966 if (lhptee.getUnqualifiedType()->isVoidType() &&
967 (rhptee->isObjectType() || rhptee->isIncompleteType()))
968 ;
969 else if (rhptee.getUnqualifiedType()->isVoidType() &&
970 (lhptee->isObjectType() || lhptee->isIncompleteType()))
971 ;
972 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
973 // unqualified versions of compatible types, ...
974 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
975 rhptee.getUnqualifiedType()))
976 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
977 return r;
978}
979
980/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
981/// has code to accommodate several GCC extensions when type checking
982/// pointers. Here are some objectionable examples that GCC considers warnings:
983///
984/// int a, *pint;
985/// short *pshort;
986/// struct foo *pfoo;
987///
988/// pint = pshort; // warning: assignment from incompatible pointer type
989/// a = pint; // warning: assignment makes integer from pointer without a cast
990/// pint = a; // warning: assignment makes pointer from integer without a cast
991/// pint = pfoo; // warning: assignment from incompatible pointer type
992///
993/// As a result, the code for dealing with pointers is more complex than the
994/// C99 spec dictates.
995/// Note: the warning above turn into errors when -pedantic-errors is enabled.
996///
997Sema::AssignmentCheckResult
998Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
999 if (lhsType == rhsType) // common case, fast path...
1000 return Compatible;
1001
1002 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
1003 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1004 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1005 return Incompatible;
1006 }
1007 return Compatible;
1008 } else if (lhsType->isPointerType()) {
1009 if (rhsType->isIntegerType())
1010 return PointerFromInt;
1011
1012 if (rhsType->isPointerType())
1013 return CheckPointerTypesForAssignment(lhsType, rhsType);
1014 } else if (rhsType->isPointerType()) {
1015 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1016 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1017 return IntFromPointer;
1018
1019 if (lhsType->isPointerType())
1020 return CheckPointerTypesForAssignment(lhsType, rhsType);
1021 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
1022 if (Type::tagTypesAreCompatible(lhsType, rhsType))
1023 return Compatible;
1024 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
1025 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
1026 return Compatible;
1027 }
1028 return Incompatible;
1029}
1030
1031Sema::AssignmentCheckResult
1032Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
1033 // This check seems unnatural, however it is necessary to insure the proper
1034 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001035 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001036 // expressions that surpress this implicit conversion (&, sizeof).
1037 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001038
1039 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +00001040
Steve Naroff0f32f432007-08-24 22:33:52 +00001041 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1042
1043 // C99 6.5.16.1p2: The value of the right operand is converted to the
1044 // type of the assignment expression.
1045 if (rExpr->getType() != lhsType)
1046 promoteExprToType(rExpr, lhsType);
1047 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001048}
1049
1050Sema::AssignmentCheckResult
1051Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1052 return CheckAssignmentConstraints(lhsType, rhsType);
1053}
1054
1055inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1056 Diag(loc, diag::err_typecheck_invalid_operands,
1057 lex->getType().getAsString(), rex->getType().getAsString(),
1058 lex->getSourceRange(), rex->getSourceRange());
1059}
1060
1061inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1062 Expr *&rex) {
1063 QualType lhsType = lex->getType(), rhsType = rex->getType();
1064
1065 // make sure the vector types are identical.
1066 if (lhsType == rhsType)
1067 return lhsType;
1068 // You cannot convert between vector values of different size.
1069 Diag(loc, diag::err_typecheck_vector_not_convertable,
1070 lex->getType().getAsString(), rex->getType().getAsString(),
1071 lex->getSourceRange(), rex->getSourceRange());
1072 return QualType();
1073}
1074
1075inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001076 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001077{
1078 QualType lhsType = lex->getType(), rhsType = rex->getType();
1079
1080 if (lhsType->isVectorType() || rhsType->isVectorType())
1081 return CheckVectorOperands(loc, lex, rex);
1082
Steve Naroff8f708362007-08-24 19:07:16 +00001083 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001084
Chris Lattner4b009652007-07-25 00:24:17 +00001085 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001086 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001087 InvalidOperands(loc, lex, rex);
1088 return QualType();
1089}
1090
1091inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001092 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001093{
1094 QualType lhsType = lex->getType(), rhsType = rex->getType();
1095
Steve Naroff8f708362007-08-24 19:07:16 +00001096 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001097
Chris Lattner4b009652007-07-25 00:24:17 +00001098 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001099 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001100 InvalidOperands(loc, lex, rex);
1101 return QualType();
1102}
1103
1104inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001105 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001106{
1107 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1108 return CheckVectorOperands(loc, lex, rex);
1109
Steve Naroff8f708362007-08-24 19:07:16 +00001110 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001111
1112 // handle the common case first (both operands are arithmetic).
1113 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001114 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001115
1116 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1117 return lex->getType();
1118 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1119 return rex->getType();
1120 InvalidOperands(loc, lex, rex);
1121 return QualType();
1122}
1123
1124inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001125 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001126{
1127 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1128 return CheckVectorOperands(loc, lex, rex);
1129
Steve Naroff8f708362007-08-24 19:07:16 +00001130 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001131
1132 // handle the common case first (both operands are arithmetic).
1133 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001134 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001135
1136 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001137 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001138 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1139 return Context.getPointerDiffType();
1140 InvalidOperands(loc, lex, rex);
1141 return QualType();
1142}
1143
1144inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001145 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001146{
1147 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1148 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001149 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001150
1151 // handle the common case first (both operands are arithmetic).
1152 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001153 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001154 InvalidOperands(loc, lex, rex);
1155 return QualType();
1156}
1157
Chris Lattner254f3bc2007-08-26 01:18:55 +00001158inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1159 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001160{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001161 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001162 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1163 UsualArithmeticConversions(lex, rex);
1164 else {
1165 UsualUnaryConversions(lex);
1166 UsualUnaryConversions(rex);
1167 }
Chris Lattner4b009652007-07-25 00:24:17 +00001168 QualType lType = lex->getType();
1169 QualType rType = rex->getType();
1170
Chris Lattner254f3bc2007-08-26 01:18:55 +00001171 if (isRelational) {
1172 if (lType->isRealType() && rType->isRealType())
1173 return Context.IntTy;
1174 } else {
Chris Lattnerbd3cc222007-08-30 06:10:41 +00001175 if (lType->isFloatingType() && rType->isFloatingType())
Ted Kremenekec761af2007-08-29 18:06:12 +00001176 Diag(loc, diag::warn_floatingpoint_eq);
1177
Chris Lattner254f3bc2007-08-26 01:18:55 +00001178 if (lType->isArithmeticType() && rType->isArithmeticType())
1179 return Context.IntTy;
1180 }
Chris Lattner4b009652007-07-25 00:24:17 +00001181
Chris Lattner22be8422007-08-26 01:10:14 +00001182 bool LHSIsNull = lex->isNullPointerConstant(Context);
1183 bool RHSIsNull = rex->isNullPointerConstant(Context);
1184
Chris Lattner254f3bc2007-08-26 01:18:55 +00001185 // All of the following pointer related warnings are GCC extensions, except
1186 // when handling null pointer constants. One day, we can consider making them
1187 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001188 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner22be8422007-08-26 01:10:14 +00001189 if (!LHSIsNull && !RHSIsNull &&
Steve Naroffc33c0602007-08-27 04:08:11 +00001190 !Type::pointerTypesAreCompatible(lType.getUnqualifiedType(),
1191 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001192 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1193 lType.getAsString(), rType.getAsString(),
1194 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001195 }
Chris Lattner22be8422007-08-26 01:10:14 +00001196 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001197 return Context.IntTy;
1198 }
1199 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001200 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001201 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1202 lType.getAsString(), rType.getAsString(),
1203 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001204 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001205 return Context.IntTy;
1206 }
1207 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001208 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001209 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1210 lType.getAsString(), rType.getAsString(),
1211 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001212 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001213 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001214 }
1215 InvalidOperands(loc, lex, rex);
1216 return QualType();
1217}
1218
Chris Lattner4b009652007-07-25 00:24:17 +00001219inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001220 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001221{
1222 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1223 return CheckVectorOperands(loc, lex, rex);
1224
Steve Naroff8f708362007-08-24 19:07:16 +00001225 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001226
1227 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001228 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001229 InvalidOperands(loc, lex, rex);
1230 return QualType();
1231}
1232
1233inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1234 Expr *&lex, Expr *&rex, SourceLocation loc)
1235{
1236 UsualUnaryConversions(lex);
1237 UsualUnaryConversions(rex);
1238
1239 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1240 return Context.IntTy;
1241 InvalidOperands(loc, lex, rex);
1242 return QualType();
1243}
1244
1245inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001246 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001247{
1248 QualType lhsType = lex->getType();
1249 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1250 bool hadError = false;
1251 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1252
1253 switch (mlval) { // C99 6.5.16p2
1254 case Expr::MLV_Valid:
1255 break;
1256 case Expr::MLV_ConstQualified:
1257 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1258 hadError = true;
1259 break;
1260 case Expr::MLV_ArrayType:
1261 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1262 lhsType.getAsString(), lex->getSourceRange());
1263 return QualType();
1264 case Expr::MLV_NotObjectType:
1265 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1266 lhsType.getAsString(), lex->getSourceRange());
1267 return QualType();
1268 case Expr::MLV_InvalidExpression:
1269 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1270 lex->getSourceRange());
1271 return QualType();
1272 case Expr::MLV_IncompleteType:
1273 case Expr::MLV_IncompleteVoidType:
1274 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1275 lhsType.getAsString(), lex->getSourceRange());
1276 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001277 case Expr::MLV_DuplicateVectorComponents:
1278 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1279 lex->getSourceRange());
1280 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001281 }
1282 AssignmentCheckResult result;
1283
1284 if (compoundType.isNull())
1285 result = CheckSingleAssignmentConstraints(lhsType, rex);
1286 else
1287 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001288
Chris Lattner4b009652007-07-25 00:24:17 +00001289 // decode the result (notice that extensions still return a type).
1290 switch (result) {
1291 case Compatible:
1292 break;
1293 case Incompatible:
1294 Diag(loc, diag::err_typecheck_assign_incompatible,
1295 lhsType.getAsString(), rhsType.getAsString(),
1296 lex->getSourceRange(), rex->getSourceRange());
1297 hadError = true;
1298 break;
1299 case PointerFromInt:
1300 // check for null pointer constant (C99 6.3.2.3p3)
1301 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1302 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1303 lhsType.getAsString(), rhsType.getAsString(),
1304 lex->getSourceRange(), rex->getSourceRange());
1305 }
1306 break;
1307 case IntFromPointer:
1308 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1309 lhsType.getAsString(), rhsType.getAsString(),
1310 lex->getSourceRange(), rex->getSourceRange());
1311 break;
1312 case IncompatiblePointer:
1313 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1314 lhsType.getAsString(), rhsType.getAsString(),
1315 lex->getSourceRange(), rex->getSourceRange());
1316 break;
1317 case CompatiblePointerDiscardsQualifiers:
1318 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1319 lhsType.getAsString(), rhsType.getAsString(),
1320 lex->getSourceRange(), rex->getSourceRange());
1321 break;
1322 }
1323 // C99 6.5.16p3: The type of an assignment expression is the type of the
1324 // left operand unless the left operand has qualified type, in which case
1325 // it is the unqualified version of the type of the left operand.
1326 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1327 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001328 // C++ 5.17p1: the type of the assignment expression is that of its left
1329 // oprdu.
Chris Lattner4b009652007-07-25 00:24:17 +00001330 return hadError ? QualType() : lhsType.getUnqualifiedType();
1331}
1332
1333inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1334 Expr *&lex, Expr *&rex, SourceLocation loc) {
1335 UsualUnaryConversions(rex);
1336 return rex->getType();
1337}
1338
1339/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1340/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1341QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1342 QualType resType = op->getType();
1343 assert(!resType.isNull() && "no type for increment/decrement expression");
1344
Steve Naroffd30e1932007-08-24 17:20:07 +00001345 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattner4b009652007-07-25 00:24:17 +00001346 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1347 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1348 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1349 resType.getAsString(), op->getSourceRange());
1350 return QualType();
1351 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001352 } else if (!resType->isRealType()) {
1353 if (resType->isComplexType())
1354 // C99 does not support ++/-- on complex types.
1355 Diag(OpLoc, diag::ext_integer_increment_complex,
1356 resType.getAsString(), op->getSourceRange());
1357 else {
1358 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1359 resType.getAsString(), op->getSourceRange());
1360 return QualType();
1361 }
Chris Lattner4b009652007-07-25 00:24:17 +00001362 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001363 // At this point, we know we have a real, complex or pointer type.
1364 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001365 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1366 if (mlval != Expr::MLV_Valid) {
1367 // FIXME: emit a more precise diagnostic...
1368 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1369 op->getSourceRange());
1370 return QualType();
1371 }
1372 return resType;
1373}
1374
1375/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1376/// This routine allows us to typecheck complex/recursive expressions
1377/// where the declaration is needed for type checking. Here are some
1378/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1379static Decl *getPrimaryDeclaration(Expr *e) {
1380 switch (e->getStmtClass()) {
1381 case Stmt::DeclRefExprClass:
1382 return cast<DeclRefExpr>(e)->getDecl();
1383 case Stmt::MemberExprClass:
1384 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1385 case Stmt::ArraySubscriptExprClass:
1386 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1387 case Stmt::CallExprClass:
1388 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1389 case Stmt::UnaryOperatorClass:
1390 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1391 case Stmt::ParenExprClass:
1392 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1393 default:
1394 return 0;
1395 }
1396}
1397
1398/// CheckAddressOfOperand - The operand of & must be either a function
1399/// designator or an lvalue designating an object. If it is an lvalue, the
1400/// object cannot be declared with storage class register or be a bit field.
1401/// Note: The usual conversions are *not* applied to the operand of the &
1402/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1403QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1404 Decl *dcl = getPrimaryDeclaration(op);
1405 Expr::isLvalueResult lval = op->isLvalue();
1406
1407 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1408 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1409 ;
1410 else { // FIXME: emit more specific diag...
1411 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1412 op->getSourceRange());
1413 return QualType();
1414 }
1415 } else if (dcl) {
1416 // We have an lvalue with a decl. Make sure the decl is not declared
1417 // with the register storage-class specifier.
1418 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1419 if (vd->getStorageClass() == VarDecl::Register) {
1420 Diag(OpLoc, diag::err_typecheck_address_of_register,
1421 op->getSourceRange());
1422 return QualType();
1423 }
1424 } else
1425 assert(0 && "Unknown/unexpected decl type");
1426
1427 // FIXME: add check for bitfields!
1428 }
1429 // If the operand has type "type", the result has type "pointer to type".
1430 return Context.getPointerType(op->getType());
1431}
1432
1433QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1434 UsualUnaryConversions(op);
1435 QualType qType = op->getType();
1436
Chris Lattner7931f4a2007-07-31 16:53:04 +00001437 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001438 QualType ptype = PT->getPointeeType();
1439 // C99 6.5.3.2p4. "if it points to an object,...".
1440 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1441 // GCC compat: special case 'void *' (treat as warning).
1442 if (ptype->isVoidType()) {
1443 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1444 qType.getAsString(), op->getSourceRange());
1445 } else {
1446 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1447 ptype.getAsString(), op->getSourceRange());
1448 return QualType();
1449 }
1450 }
1451 return ptype;
1452 }
1453 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1454 qType.getAsString(), op->getSourceRange());
1455 return QualType();
1456}
1457
1458static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1459 tok::TokenKind Kind) {
1460 BinaryOperator::Opcode Opc;
1461 switch (Kind) {
1462 default: assert(0 && "Unknown binop!");
1463 case tok::star: Opc = BinaryOperator::Mul; break;
1464 case tok::slash: Opc = BinaryOperator::Div; break;
1465 case tok::percent: Opc = BinaryOperator::Rem; break;
1466 case tok::plus: Opc = BinaryOperator::Add; break;
1467 case tok::minus: Opc = BinaryOperator::Sub; break;
1468 case tok::lessless: Opc = BinaryOperator::Shl; break;
1469 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1470 case tok::lessequal: Opc = BinaryOperator::LE; break;
1471 case tok::less: Opc = BinaryOperator::LT; break;
1472 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1473 case tok::greater: Opc = BinaryOperator::GT; break;
1474 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1475 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1476 case tok::amp: Opc = BinaryOperator::And; break;
1477 case tok::caret: Opc = BinaryOperator::Xor; break;
1478 case tok::pipe: Opc = BinaryOperator::Or; break;
1479 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1480 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1481 case tok::equal: Opc = BinaryOperator::Assign; break;
1482 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1483 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1484 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1485 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1486 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1487 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1488 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1489 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1490 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1491 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1492 case tok::comma: Opc = BinaryOperator::Comma; break;
1493 }
1494 return Opc;
1495}
1496
1497static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1498 tok::TokenKind Kind) {
1499 UnaryOperator::Opcode Opc;
1500 switch (Kind) {
1501 default: assert(0 && "Unknown unary op!");
1502 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1503 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1504 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1505 case tok::star: Opc = UnaryOperator::Deref; break;
1506 case tok::plus: Opc = UnaryOperator::Plus; break;
1507 case tok::minus: Opc = UnaryOperator::Minus; break;
1508 case tok::tilde: Opc = UnaryOperator::Not; break;
1509 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1510 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1511 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1512 case tok::kw___real: Opc = UnaryOperator::Real; break;
1513 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1514 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1515 }
1516 return Opc;
1517}
1518
1519// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001520Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001521 ExprTy *LHS, ExprTy *RHS) {
1522 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1523 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1524
Steve Naroff87d58b42007-09-16 03:34:24 +00001525 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1526 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001527
1528 QualType ResultTy; // Result type of the binary operator.
1529 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1530
1531 switch (Opc) {
1532 default:
1533 assert(0 && "Unknown binary expr!");
1534 case BinaryOperator::Assign:
1535 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1536 break;
1537 case BinaryOperator::Mul:
1538 case BinaryOperator::Div:
1539 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1540 break;
1541 case BinaryOperator::Rem:
1542 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1543 break;
1544 case BinaryOperator::Add:
1545 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1546 break;
1547 case BinaryOperator::Sub:
1548 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1549 break;
1550 case BinaryOperator::Shl:
1551 case BinaryOperator::Shr:
1552 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1553 break;
1554 case BinaryOperator::LE:
1555 case BinaryOperator::LT:
1556 case BinaryOperator::GE:
1557 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001558 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001559 break;
1560 case BinaryOperator::EQ:
1561 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001562 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001563 break;
1564 case BinaryOperator::And:
1565 case BinaryOperator::Xor:
1566 case BinaryOperator::Or:
1567 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1568 break;
1569 case BinaryOperator::LAnd:
1570 case BinaryOperator::LOr:
1571 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1572 break;
1573 case BinaryOperator::MulAssign:
1574 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001575 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001576 if (!CompTy.isNull())
1577 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1578 break;
1579 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001580 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001581 if (!CompTy.isNull())
1582 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1583 break;
1584 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001585 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001586 if (!CompTy.isNull())
1587 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1588 break;
1589 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001590 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001591 if (!CompTy.isNull())
1592 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1593 break;
1594 case BinaryOperator::ShlAssign:
1595 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001596 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001597 if (!CompTy.isNull())
1598 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1599 break;
1600 case BinaryOperator::AndAssign:
1601 case BinaryOperator::XorAssign:
1602 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001603 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001604 if (!CompTy.isNull())
1605 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1606 break;
1607 case BinaryOperator::Comma:
1608 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1609 break;
1610 }
1611 if (ResultTy.isNull())
1612 return true;
1613 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001614 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001615 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001616 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001617}
1618
1619// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001620Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001621 ExprTy *input) {
1622 Expr *Input = (Expr*)input;
1623 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1624 QualType resultType;
1625 switch (Opc) {
1626 default:
1627 assert(0 && "Unimplemented unary expr!");
1628 case UnaryOperator::PreInc:
1629 case UnaryOperator::PreDec:
1630 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1631 break;
1632 case UnaryOperator::AddrOf:
1633 resultType = CheckAddressOfOperand(Input, OpLoc);
1634 break;
1635 case UnaryOperator::Deref:
1636 resultType = CheckIndirectionOperand(Input, OpLoc);
1637 break;
1638 case UnaryOperator::Plus:
1639 case UnaryOperator::Minus:
1640 UsualUnaryConversions(Input);
1641 resultType = Input->getType();
1642 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1643 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1644 resultType.getAsString());
1645 break;
1646 case UnaryOperator::Not: // bitwise complement
1647 UsualUnaryConversions(Input);
1648 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001649 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1650 if (!resultType->isIntegerType()) {
1651 if (resultType->isComplexType())
1652 // C99 does not support '~' for complex conjugation.
1653 Diag(OpLoc, diag::ext_integer_complement_complex,
1654 resultType.getAsString());
1655 else
1656 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1657 resultType.getAsString());
1658 }
Chris Lattner4b009652007-07-25 00:24:17 +00001659 break;
1660 case UnaryOperator::LNot: // logical negation
1661 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1662 DefaultFunctionArrayConversion(Input);
1663 resultType = Input->getType();
1664 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1665 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1666 resultType.getAsString());
1667 // LNot always has type int. C99 6.5.3.3p5.
1668 resultType = Context.IntTy;
1669 break;
1670 case UnaryOperator::SizeOf:
1671 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1672 break;
1673 case UnaryOperator::AlignOf:
1674 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1675 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001676 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001677 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001678 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001679 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001680 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001681 resultType = Input->getType();
1682 break;
1683 }
1684 if (resultType.isNull())
1685 return true;
1686 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1687}
1688
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001689/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1690Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001691 SourceLocation LabLoc,
1692 IdentifierInfo *LabelII) {
1693 // Look up the record for this label identifier.
1694 LabelStmt *&LabelDecl = LabelMap[LabelII];
1695
1696 // If we haven't seen this label yet, create a forward reference.
1697 if (LabelDecl == 0)
1698 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1699
1700 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001701 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1702 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001703}
1704
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001705Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00001706 SourceLocation RPLoc) { // "({..})"
1707 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1708 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1709 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1710
1711 // FIXME: there are a variety of strange constraints to enforce here, for
1712 // example, it is not possible to goto into a stmt expression apparently.
1713 // More semantic analysis is needed.
1714
1715 // FIXME: the last statement in the compount stmt has its value used. We
1716 // should not warn about it being unused.
1717
1718 // If there are sub stmts in the compound stmt, take the type of the last one
1719 // as the type of the stmtexpr.
1720 QualType Ty = Context.VoidTy;
1721
1722 if (!Compound->body_empty())
1723 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1724 Ty = LastExpr->getType();
1725
1726 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1727}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001728
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001729Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001730 SourceLocation TypeLoc,
1731 TypeTy *argty,
1732 OffsetOfComponent *CompPtr,
1733 unsigned NumComponents,
1734 SourceLocation RPLoc) {
1735 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1736 assert(!ArgTy.isNull() && "Missing type argument!");
1737
1738 // We must have at least one component that refers to the type, and the first
1739 // one is known to be a field designator. Verify that the ArgTy represents
1740 // a struct/union/class.
1741 if (!ArgTy->isRecordType())
1742 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1743
1744 // Otherwise, create a compound literal expression as the base, and
1745 // iteratively process the offsetof designators.
1746 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1747
Chris Lattnerb37522e2007-08-31 21:49:13 +00001748 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1749 // GCC extension, diagnose them.
1750 if (NumComponents != 1)
1751 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1752 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1753
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001754 for (unsigned i = 0; i != NumComponents; ++i) {
1755 const OffsetOfComponent &OC = CompPtr[i];
1756 if (OC.isBrackets) {
1757 // Offset of an array sub-field. TODO: Should we allow vector elements?
1758 const ArrayType *AT = Res->getType()->getAsArrayType();
1759 if (!AT) {
1760 delete Res;
1761 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1762 Res->getType().getAsString());
1763 }
1764
Chris Lattner2af6a802007-08-30 17:59:59 +00001765 // FIXME: C++: Verify that operator[] isn't overloaded.
1766
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001767 // C99 6.5.2.1p1
1768 Expr *Idx = static_cast<Expr*>(OC.U.E);
1769 if (!Idx->getType()->isIntegerType())
1770 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1771 Idx->getSourceRange());
1772
1773 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1774 continue;
1775 }
1776
1777 const RecordType *RC = Res->getType()->getAsRecordType();
1778 if (!RC) {
1779 delete Res;
1780 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1781 Res->getType().getAsString());
1782 }
1783
1784 // Get the decl corresponding to this.
1785 RecordDecl *RD = RC->getDecl();
1786 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1787 if (!MemberDecl)
1788 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1789 OC.U.IdentInfo->getName(),
1790 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00001791
1792 // FIXME: C++: Verify that MemberDecl isn't a static field.
1793 // FIXME: Verify that MemberDecl isn't a bitfield.
1794
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001795 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1796 }
1797
1798 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1799 BuiltinLoc);
1800}
1801
1802
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001803Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001804 TypeTy *arg1, TypeTy *arg2,
1805 SourceLocation RPLoc) {
1806 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1807 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1808
1809 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1810
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001811 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001812}
1813
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001814Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00001815 ExprTy *expr1, ExprTy *expr2,
1816 SourceLocation RPLoc) {
1817 Expr *CondExpr = static_cast<Expr*>(cond);
1818 Expr *LHSExpr = static_cast<Expr*>(expr1);
1819 Expr *RHSExpr = static_cast<Expr*>(expr2);
1820
1821 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1822
1823 // The conditional expression is required to be a constant expression.
1824 llvm::APSInt condEval(32);
1825 SourceLocation ExpLoc;
1826 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1827 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1828 CondExpr->getSourceRange());
1829
1830 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1831 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1832 RHSExpr->getType();
1833 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1834}
1835
Anders Carlssona66cad42007-08-21 17:43:55 +00001836// TODO: Move this to SemaObjC.cpp
Anders Carlsson8be1d402007-08-22 15:14:15 +00001837Sema::ExprResult Sema::ParseObjCStringLiteral(ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00001838 StringLiteral* S = static_cast<StringLiteral *>(string);
1839
1840 if (CheckBuiltinCFStringArgument(S))
1841 return true;
1842
1843 QualType t = Context.getCFConstantStringType();
1844 t = t.getQualifiedType(QualType::Const);
1845 t = Context.getPointerType(t);
1846
1847 return new ObjCStringLiteral(S, t);
1848}
Anders Carlsson8be1d402007-08-22 15:14:15 +00001849
1850Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1851 SourceLocation LParenLoc,
1852 TypeTy *Ty,
1853 SourceLocation RParenLoc) {
1854 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
1855
1856 QualType t = Context.getPointerType(Context.CharTy);
1857 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
1858}
Steve Naroffd3f5ee42007-09-17 21:01:15 +00001859
Steve Naroff4bc52ce2007-09-19 16:18:46 +00001860static IdentifierInfo &DeriveSelector(ObjcKeywordMessage *Keywords,
Steve Naroffc39ca262007-09-18 23:55:05 +00001861 unsigned NumKeywords,
1862 ASTContext &Context) {
1863 // Derive the selector name from the keyword declarations.
1864 int len=0;
1865 for (unsigned int i = 0; i < NumKeywords; i++) {
1866 if (Keywords[i].SelectorName)
1867 len += strlen(Keywords[i].SelectorName->getName());
1868 len++;
1869 }
1870 llvm::SmallString<128> methodName;
1871 methodName[0] = '\0';
1872 for (unsigned int i = 0; i < NumKeywords; i++) {
1873 if (Keywords[i].SelectorName)
1874 methodName += Keywords[i].SelectorName->getName();
1875 methodName += ":";
1876 }
1877 methodName[len] = '\0';
Steve Naroff4bc52ce2007-09-19 16:18:46 +00001878 return Context.Idents.get(&methodName[0], &methodName[0]+len);
Steve Naroffc39ca262007-09-18 23:55:05 +00001879}
1880
Steve Naroffd3f5ee42007-09-17 21:01:15 +00001881// This actions handles keyword message to classes.
Steve Naroffc39ca262007-09-18 23:55:05 +00001882Sema::ExprResult Sema::ActOnKeywordMessage(
1883 IdentifierInfo *receivingClassName,
1884 ObjcKeywordMessage *Keywords, unsigned NumKeywords,
1885 SourceLocation lbrac, SourceLocation rbrac)
Steve Naroffd3f5ee42007-09-17 21:01:15 +00001886{
Steve Naroff4bc52ce2007-09-19 16:18:46 +00001887 IdentifierInfo &SelName = DeriveSelector(Keywords, NumKeywords, Context);
Steve Naroffc39ca262007-09-18 23:55:05 +00001888 assert(receivingClassName && "missing receiver class name");
1889
1890 return new ObjCMessageExpr(receivingClassName, SelName, Keywords, NumKeywords,
1891 Context.IntTy/*FIXME*/, lbrac, rbrac);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00001892}
1893
1894// This action handles keyword messages to instances.
Steve Naroffc39ca262007-09-18 23:55:05 +00001895Sema::ExprResult Sema::ActOnKeywordMessage(
1896 ExprTy *receiver, ObjcKeywordMessage *Keywords, unsigned NumKeywords,
1897 SourceLocation lbrac, SourceLocation rbrac) {
Steve Naroff4bc52ce2007-09-19 16:18:46 +00001898 IdentifierInfo &SelName = DeriveSelector(Keywords, NumKeywords, Context);
Steve Naroffc39ca262007-09-18 23:55:05 +00001899 assert(receiver && "missing receiver expression");
1900
1901 Expr *RExpr = static_cast<Expr *>(receiver);
1902 return new ObjCMessageExpr(RExpr, SelName, Keywords, NumKeywords,
1903 Context.IntTy/*FIXME*/, lbrac, rbrac);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00001904}
1905
Steve Naroffc39ca262007-09-18 23:55:05 +00001906// This actions handles unary message to classes.
1907Sema::ExprResult Sema::ActOnUnaryMessage(
1908 IdentifierInfo *receivingClassName, IdentifierInfo *selName,
1909 SourceLocation lbrac, SourceLocation rbrac) {
1910 assert(receivingClassName && "missing receiver class name");
1911
1912 // FIXME: this should be passed in...
Steve Naroff4bc52ce2007-09-19 16:18:46 +00001913 IdentifierInfo &SName = Context.Idents.get(
Steve Naroffc39ca262007-09-18 23:55:05 +00001914 selName->getName(), selName->getName()+strlen(selName->getName()));
1915 return new ObjCMessageExpr(receivingClassName, SName,
1916 Context.IntTy/*FIXME*/, lbrac, rbrac);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00001917}
1918
Steve Naroffc39ca262007-09-18 23:55:05 +00001919// This action handles unary messages to instances.
1920Sema::ExprResult Sema::ActOnUnaryMessage(
1921 ExprTy *receiver, IdentifierInfo *selName,
1922 SourceLocation lbrac, SourceLocation rbrac) {
1923 assert(receiver && "missing receiver expression");
1924
1925 Expr *RExpr = static_cast<Expr *>(receiver);
1926 // FIXME: this should be passed in...
Steve Naroff4bc52ce2007-09-19 16:18:46 +00001927 IdentifierInfo &SName = Context.Idents.get(
Steve Naroffc39ca262007-09-18 23:55:05 +00001928 selName->getName(), selName->getName()+strlen(selName->getName()));
1929 return new ObjCMessageExpr(RExpr, SName,
1930 Context.IntTy/*FIXME*/, lbrac, rbrac);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00001931}
1932