blob: 9efd229cc0bba230374652d3e771f2e20fbdeff6 [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"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Lex/LiteralSupport.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/LangOptions.h"
23#include "clang/Basic/TargetInfo.h"
24#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000025#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026using namespace clang;
27
28/// ParseStringLiteral - The specified tokens were lexed as pasted string
29/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
30/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
31/// multiple tokens. However, the common case is that StringToks points to one
32/// string.
33///
34Action::ExprResult
35Sema::ParseStringLiteral(const Token *StringToks, unsigned NumStringToks) {
36 assert(NumStringToks && "Must have at least one string!");
37
38 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
39 if (Literal.hadError)
40 return ExprResult(true);
41
42 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
43 for (unsigned i = 0; i != NumStringToks; ++i)
44 StringTokLocs.push_back(StringToks[i].getLocation());
45
46 // FIXME: handle wchar_t
47 QualType t = Context.getPointerType(Context.CharTy);
48
49 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
50 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
51 Literal.AnyWide, t, StringToks[0].getLocation(),
52 StringToks[NumStringToks-1].getLocation());
53}
54
55
56/// ParseIdentifierExpr - The parser read an identifier in expression context,
57/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
58/// identifier is used in an function call context.
59Sema::ExprResult Sema::ParseIdentifierExpr(Scope *S, SourceLocation Loc,
60 IdentifierInfo &II,
61 bool HasTrailingLParen) {
62 // Could be enum-constant or decl.
63 Decl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
64 if (D == 0) {
65 // Otherwise, this could be an implicitly declared function reference (legal
66 // in C90, extension in C99).
67 if (HasTrailingLParen &&
68 // Not in C++.
69 !getLangOptions().CPlusPlus)
70 D = ImplicitlyDefineFunction(Loc, II, S);
71 else {
72 // If this name wasn't predeclared and if this is not a function call,
73 // diagnose the problem.
74 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
75 }
76 }
Chris Lattner4b009652007-07-25 00:24:17 +000077 if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
78 return new DeclRefExpr(VD, VD->getType(), Loc);
79 if (isa<TypedefDecl>(D))
80 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
81
82 assert(0 && "Invalid decl");
83 abort();
84}
85
86Sema::ExprResult Sema::ParsePreDefinedExpr(SourceLocation Loc,
87 tok::TokenKind Kind) {
88 PreDefinedExpr::IdentType IT;
89
90 switch (Kind) {
91 default:
92 assert(0 && "Unknown simple primary expr!");
93 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
94 IT = PreDefinedExpr::Func;
95 break;
96 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
97 IT = PreDefinedExpr::Function;
98 break;
99 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
100 IT = PreDefinedExpr::PrettyFunction;
101 break;
102 }
103
104 // Pre-defined identifiers are always of type char *.
105 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
106}
107
108Sema::ExprResult Sema::ParseCharacterConstant(const Token &Tok) {
109 llvm::SmallString<16> CharBuffer;
110 CharBuffer.resize(Tok.getLength());
111 const char *ThisTokBegin = &CharBuffer[0];
112 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
113
114 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
115 Tok.getLocation(), PP);
116 if (Literal.hadError())
117 return ExprResult(true);
118 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
119 Tok.getLocation());
120}
121
122Action::ExprResult Sema::ParseNumericConstant(const Token &Tok) {
123 // fast path for a single digit (which is quite common). A single digit
124 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
125 if (Tok.getLength() == 1) {
126 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
127
128 unsigned IntSize = Context.getTypeSize(Context.IntTy, Tok.getLocation());
129 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
130 Context.IntTy,
131 Tok.getLocation()));
132 }
133 llvm::SmallString<512> IntegerBuffer;
134 IntegerBuffer.resize(Tok.getLength());
135 const char *ThisTokBegin = &IntegerBuffer[0];
136
137 // Get the spelling of the token, which eliminates trigraphs, etc.
138 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
139 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
140 Tok.getLocation(), PP);
141 if (Literal.hadError)
142 return ExprResult(true);
143
144 if (Literal.isIntegerLiteral()) {
145 QualType t;
146
147 // Get the value in the widest-possible width.
148 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
149
150 if (Literal.GetIntegerValue(ResultVal)) {
151 // If this value didn't fit into uintmax_t, warn and force to ull.
152 Diag(Tok.getLocation(), diag::warn_integer_too_large);
153 t = Context.UnsignedLongLongTy;
154 assert(Context.getTypeSize(t, Tok.getLocation()) ==
155 ResultVal.getBitWidth() && "long long is not intmax_t?");
156 } else {
157 // If this value fits into a ULL, try to figure out what else it fits into
158 // according to the rules of C99 6.4.4.1p5.
159
160 // Octal, Hexadecimal, and integers with a U suffix are allowed to
161 // be an unsigned int.
162 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
163
164 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000165 if (!Literal.isLong && !Literal.isLongLong) {
166 // Are int/unsigned possibilities?
Chris Lattner4b009652007-07-25 00:24:17 +0000167 unsigned IntSize = Context.getTypeSize(Context.IntTy,Tok.getLocation());
168 // Does it fit in a unsigned int?
169 if (ResultVal.isIntN(IntSize)) {
170 // Does it fit in a signed int?
171 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
172 t = Context.IntTy;
173 else if (AllowUnsigned)
174 t = Context.UnsignedIntTy;
175 }
176
177 if (!t.isNull())
178 ResultVal.trunc(IntSize);
179 }
180
181 // Are long/unsigned long possibilities?
182 if (t.isNull() && !Literal.isLongLong) {
183 unsigned LongSize = Context.getTypeSize(Context.LongTy,
184 Tok.getLocation());
185
186 // Does it fit in a unsigned long?
187 if (ResultVal.isIntN(LongSize)) {
188 // Does it fit in a signed long?
189 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
190 t = Context.LongTy;
191 else if (AllowUnsigned)
192 t = Context.UnsignedLongTy;
193 }
194 if (!t.isNull())
195 ResultVal.trunc(LongSize);
196 }
197
198 // Finally, check long long if needed.
199 if (t.isNull()) {
200 unsigned LongLongSize =
201 Context.getTypeSize(Context.LongLongTy, Tok.getLocation());
202
203 // Does it fit in a unsigned long long?
204 if (ResultVal.isIntN(LongLongSize)) {
205 // Does it fit in a signed long long?
206 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
207 t = Context.LongLongTy;
208 else if (AllowUnsigned)
209 t = Context.UnsignedLongLongTy;
210 }
211 }
212
213 // If we still couldn't decide a type, we probably have something that
214 // does not fit in a signed long long, but has no U suffix.
215 if (t.isNull()) {
216 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
217 t = Context.UnsignedLongLongTy;
218 }
219 }
220
221 return new IntegerLiteral(ResultVal, t, Tok.getLocation());
222 } else if (Literal.isFloatingLiteral()) {
223 // FIXME: handle float values > 32 (including compute the real type...).
224 return new FloatingLiteral(Literal.GetFloatValue(), Context.FloatTy,
225 Tok.getLocation());
226 }
227 return ExprResult(true);
228}
229
230Action::ExprResult Sema::ParseParenExpr(SourceLocation L, SourceLocation R,
231 ExprTy *Val) {
232 Expr *e = (Expr *)Val;
233 assert((e != 0) && "ParseParenExpr() missing expr");
234 return new ParenExpr(L, R, e);
235}
236
237/// The UsualUnaryConversions() function is *not* called by this routine.
238/// See C99 6.3.2.1p[2-4] for more details.
239QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
240 SourceLocation OpLoc, bool isSizeof) {
241 // C99 6.5.3.4p1:
242 if (isa<FunctionType>(exprType) && isSizeof)
243 // alignof(function) is allowed.
244 Diag(OpLoc, diag::ext_sizeof_function_type);
245 else if (exprType->isVoidType())
246 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
247 else if (exprType->isIncompleteType()) {
248 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
249 diag::err_alignof_incomplete_type,
250 exprType.getAsString());
251 return QualType(); // error
252 }
253 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
254 return Context.getSizeType();
255}
256
257Action::ExprResult Sema::
258ParseSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
259 SourceLocation LPLoc, TypeTy *Ty,
260 SourceLocation RPLoc) {
261 // If error parsing type, ignore.
262 if (Ty == 0) return true;
263
264 // Verify that this is a valid expression.
265 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
266
267 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
268
269 if (resultType.isNull())
270 return true;
271 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
272}
273
274
275Action::ExprResult Sema::ParsePostfixUnaryOp(SourceLocation OpLoc,
276 tok::TokenKind Kind,
277 ExprTy *Input) {
278 UnaryOperator::Opcode Opc;
279 switch (Kind) {
280 default: assert(0 && "Unknown unary op!");
281 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
282 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
283 }
284 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
285 if (result.isNull())
286 return true;
287 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
288}
289
290Action::ExprResult Sema::
291ParseArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
292 ExprTy *Idx, SourceLocation RLoc) {
293 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
294
295 // Perform default conversions.
296 DefaultFunctionArrayConversion(LHSExp);
297 DefaultFunctionArrayConversion(RHSExp);
298
299 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
300
301 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
302 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
303 // in the subscript position. As a result, we need to derive the array base
304 // and index from the expression types.
305 Expr *BaseExpr, *IndexExpr;
306 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000307 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000308 BaseExpr = LHSExp;
309 IndexExpr = RHSExp;
310 // FIXME: need to deal with const...
311 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000312 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000313 // Handle the uncommon case of "123[Ptr]".
314 BaseExpr = RHSExp;
315 IndexExpr = LHSExp;
316 // FIXME: need to deal with const...
317 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000318 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
319 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000320 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000321
322 // Component access limited to variables (reject vec4.rg[1]).
323 if (!isa<DeclRefExpr>(BaseExpr))
324 return Diag(LLoc, diag::err_ocuvector_component_access,
325 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000326 // FIXME: need to deal with const...
327 ResultType = VTy->getElementType();
328 } else {
329 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
330 RHSExp->getSourceRange());
331 }
332 // C99 6.5.2.1p1
333 if (!IndexExpr->getType()->isIntegerType())
334 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
335 IndexExpr->getSourceRange());
336
337 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
338 // the following check catches trying to index a pointer to a function (e.g.
339 // void (*)(int)). Functions are not objects in C99.
340 if (!ResultType->isObjectType())
341 return Diag(BaseExpr->getLocStart(),
342 diag::err_typecheck_subscript_not_object,
343 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
344
345 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
346}
347
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000348QualType Sema::
349CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
350 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000351 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000352
353 // The vector accessor can't exceed the number of elements.
354 const char *compStr = CompName.getName();
355 if (strlen(compStr) > vecType->getNumElements()) {
356 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
357 baseType.getAsString(), SourceRange(CompLoc));
358 return QualType();
359 }
360 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000361 if (vecType->getPointAccessorIdx(*compStr) != -1) {
362 do
363 compStr++;
364 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
365 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
366 do
367 compStr++;
368 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
369 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
370 do
371 compStr++;
372 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
373 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000374
375 if (*compStr) {
376 // We didn't get to the end of the string. This means the component names
377 // didn't come from the same set *or* we encountered an illegal name.
378 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
379 std::string(compStr,compStr+1), SourceRange(CompLoc));
380 return QualType();
381 }
382 // Each component accessor can't exceed the vector type.
383 compStr = CompName.getName();
384 while (*compStr) {
385 if (vecType->isAccessorWithinNumElements(*compStr))
386 compStr++;
387 else
388 break;
389 }
390 if (*compStr) {
391 // We didn't get to the end of the string. This means a component accessor
392 // exceeds the number of elements in the vector.
393 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
394 baseType.getAsString(), SourceRange(CompLoc));
395 return QualType();
396 }
397 // The component accessor looks fine - now we need to compute the actual type.
398 // The vector type is implied by the component accessor. For example,
399 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
400 unsigned CompSize = strlen(CompName.getName());
401 if (CompSize == 1)
402 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000403
404 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
405 // Now look up the TypeDefDecl from the vector type. Without this,
406 // diagostics look bad. We want OCU vector types to appear built-in.
407 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
408 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
409 return Context.getTypedefType(OCUVectorDecls[i]);
410 }
411 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000412}
413
Chris Lattner4b009652007-07-25 00:24:17 +0000414Action::ExprResult Sema::
415ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
416 tok::TokenKind OpKind, SourceLocation MemberLoc,
417 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000418 Expr *BaseExpr = static_cast<Expr *>(Base);
419 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000420
Steve Naroff2cb66382007-07-26 03:11:44 +0000421 QualType BaseType = BaseExpr->getType();
422 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000423
Chris Lattner4b009652007-07-25 00:24:17 +0000424 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000425 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000426 BaseType = PT->getPointeeType();
427 else
428 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
429 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000430 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000431 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000432 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000433 RecordDecl *RDecl = RTy->getDecl();
434 if (RTy->isIncompleteType())
435 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
436 BaseExpr->getSourceRange());
437 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000438 FieldDecl *MemberDecl = RDecl->getMember(&Member);
439 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000440 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
441 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000442 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
443 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000444 // Component access limited to variables (reject vec4.rg.g).
445 if (!isa<DeclRefExpr>(BaseExpr))
446 return Diag(OpLoc, diag::err_ocuvector_component_access,
447 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000448 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
449 if (ret.isNull())
450 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000451 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Steve Naroff2cb66382007-07-26 03:11:44 +0000452 } else
453 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
454 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000455}
456
457/// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
458/// This provides the location of the left/right parens and a list of comma
459/// locations.
460Action::ExprResult Sema::
461ParseCallExpr(ExprTy *fn, SourceLocation LParenLoc,
462 ExprTy **args, unsigned NumArgsInCall,
463 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
464 Expr *Fn = static_cast<Expr *>(fn);
465 Expr **Args = reinterpret_cast<Expr**>(args);
466 assert(Fn && "no function call expression");
467
468 UsualUnaryConversions(Fn);
469 QualType funcType = Fn->getType();
470
471 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
472 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000473 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000474 if (PT == 0)
475 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
476 SourceRange(Fn->getLocStart(), RParenLoc));
477
Chris Lattner71225142007-07-31 21:27:01 +0000478 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000479 if (funcT == 0)
480 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
481 SourceRange(Fn->getLocStart(), RParenLoc));
482
483 // If a prototype isn't declared, the parser implicitly defines a func decl
484 QualType resultType = funcT->getResultType();
485
486 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
487 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
488 // assignment, to the types of the corresponding parameter, ...
489
490 unsigned NumArgsInProto = proto->getNumArgs();
491 unsigned NumArgsToCheck = NumArgsInCall;
492
493 if (NumArgsInCall < NumArgsInProto)
494 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
495 Fn->getSourceRange());
496 else if (NumArgsInCall > NumArgsInProto) {
497 if (!proto->isVariadic()) {
498 Diag(Args[NumArgsInProto]->getLocStart(),
499 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
500 SourceRange(Args[NumArgsInProto]->getLocStart(),
501 Args[NumArgsInCall-1]->getLocEnd()));
502 }
503 NumArgsToCheck = NumArgsInProto;
504 }
505 // Continue to check argument types (even if we have too few/many args).
506 for (unsigned i = 0; i < NumArgsToCheck; i++) {
507 Expr *argExpr = Args[i];
508 assert(argExpr && "ParseCallExpr(): missing argument expression");
509
510 QualType lhsType = proto->getArgType(i);
511 QualType rhsType = argExpr->getType();
512
Steve Naroff75644062007-07-25 20:45:33 +0000513 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000514 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000515 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000516 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000517 lhsType = Context.getPointerType(lhsType);
518
519 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
520 argExpr);
521 SourceLocation l = argExpr->getLocStart();
522
523 // decode the result (notice that AST's are still created for extensions).
524 switch (result) {
525 case Compatible:
526 break;
527 case PointerFromInt:
528 // check for null pointer constant (C99 6.3.2.3p3)
529 if (!argExpr->isNullPointerConstant(Context)) {
530 Diag(l, diag::ext_typecheck_passing_pointer_int,
531 lhsType.getAsString(), rhsType.getAsString(),
532 Fn->getSourceRange(), argExpr->getSourceRange());
533 }
534 break;
535 case IntFromPointer:
536 Diag(l, diag::ext_typecheck_passing_pointer_int,
537 lhsType.getAsString(), rhsType.getAsString(),
538 Fn->getSourceRange(), argExpr->getSourceRange());
539 break;
540 case IncompatiblePointer:
541 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
542 rhsType.getAsString(), lhsType.getAsString(),
543 Fn->getSourceRange(), argExpr->getSourceRange());
544 break;
545 case CompatiblePointerDiscardsQualifiers:
546 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
547 rhsType.getAsString(), lhsType.getAsString(),
548 Fn->getSourceRange(), argExpr->getSourceRange());
549 break;
550 case Incompatible:
551 return Diag(l, diag::err_typecheck_passing_incompatible,
552 rhsType.getAsString(), lhsType.getAsString(),
553 Fn->getSourceRange(), argExpr->getSourceRange());
554 }
555 }
556 // Even if the types checked, bail if we had the wrong number of arguments.
557 if (NumArgsInCall != NumArgsInProto && !proto->isVariadic())
558 return true;
559 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000560
561 // Do special checking on direct calls to functions.
562 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
563 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
564 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000565 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args, NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000566 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000567
Chris Lattner4b009652007-07-25 00:24:17 +0000568 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
569}
570
571Action::ExprResult Sema::
572ParseCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
573 SourceLocation RParenLoc, ExprTy *InitExpr) {
574 assert((Ty != 0) && "ParseCompoundLiteral(): missing type");
575 QualType literalType = QualType::getFromOpaquePtr(Ty);
576 // FIXME: put back this assert when initializers are worked out.
577 //assert((InitExpr != 0) && "ParseCompoundLiteral(): missing expression");
578 Expr *literalExpr = static_cast<Expr*>(InitExpr);
579
580 // FIXME: add semantic analysis (C99 6.5.2.5).
581 return new CompoundLiteralExpr(literalType, literalExpr);
582}
583
584Action::ExprResult Sema::
585ParseInitList(SourceLocation LParenLoc, ExprTy **InitList, unsigned NumInit,
586 SourceLocation RParenLoc) {
587 // FIXME: add semantic analysis (C99 6.7.8). This involves
588 // knowledge of the object being intialized. As a result, the code for
589 // doing the semantic analysis will likely be located elsewhere (i.e. in
590 // consumers of InitListExpr (e.g. ParseDeclarator, ParseCompoundLiteral).
591 return false; // FIXME instantiate an InitListExpr.
592}
593
594Action::ExprResult Sema::
595ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
596 SourceLocation RParenLoc, ExprTy *Op) {
597 assert((Ty != 0) && (Op != 0) && "ParseCastExpr(): missing type or expr");
598
599 Expr *castExpr = static_cast<Expr*>(Op);
600 QualType castType = QualType::getFromOpaquePtr(Ty);
601
602 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
603 // type needs to be scalar.
604 if (!castType->isScalarType() && !castType->isVoidType()) {
605 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
606 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
607 }
608 if (!castExpr->getType()->isScalarType()) {
609 return Diag(castExpr->getLocStart(),
610 diag::err_typecheck_expect_scalar_operand,
611 castExpr->getType().getAsString(), castExpr->getSourceRange());
612 }
613 return new CastExpr(castType, castExpr, LParenLoc);
614}
615
616inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
617 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
618 UsualUnaryConversions(cond);
619 UsualUnaryConversions(lex);
620 UsualUnaryConversions(rex);
621 QualType condT = cond->getType();
622 QualType lexT = lex->getType();
623 QualType rexT = rex->getType();
624
625 // first, check the condition.
626 if (!condT->isScalarType()) { // C99 6.5.15p2
627 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
628 condT.getAsString());
629 return QualType();
630 }
631 // now check the two expressions.
632 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
633 UsualArithmeticConversions(lex, rex);
634 return lex->getType();
635 }
Chris Lattner71225142007-07-31 21:27:01 +0000636 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
637 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
638
639 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
640 return lexT;
641
Chris Lattner4b009652007-07-25 00:24:17 +0000642 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
643 lexT.getAsString(), rexT.getAsString(),
644 lex->getSourceRange(), rex->getSourceRange());
645 return QualType();
646 }
647 }
648 // C99 6.5.15p3
649 if (lexT->isPointerType() && rex->isNullPointerConstant(Context))
650 return lexT;
651 if (rexT->isPointerType() && lex->isNullPointerConstant(Context))
652 return rexT;
653
Chris Lattner71225142007-07-31 21:27:01 +0000654 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
655 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
656 // get the "pointed to" types
657 QualType lhptee = LHSPT->getPointeeType();
658 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000659
Chris Lattner71225142007-07-31 21:27:01 +0000660 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
661 if (lhptee->isVoidType() &&
662 (rhptee->isObjectType() || rhptee->isIncompleteType()))
663 return lexT;
664 if (rhptee->isVoidType() &&
665 (lhptee->isObjectType() || lhptee->isIncompleteType()))
666 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000667
Chris Lattner71225142007-07-31 21:27:01 +0000668 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
669 rhptee.getUnqualifiedType())) {
670 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
671 lexT.getAsString(), rexT.getAsString(),
672 lex->getSourceRange(), rex->getSourceRange());
673 return lexT; // FIXME: this is an _ext - is this return o.k?
674 }
675 // The pointer types are compatible.
676 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
677 // differently qualified versions of compatible types, the result type is a
678 // pointer to an appropriately qualified version of the *composite* type.
679 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000680 }
Chris Lattner4b009652007-07-25 00:24:17 +0000681 }
Chris Lattner71225142007-07-31 21:27:01 +0000682
Chris Lattner4b009652007-07-25 00:24:17 +0000683 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
684 return lexT;
685
686 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
687 lexT.getAsString(), rexT.getAsString(),
688 lex->getSourceRange(), rex->getSourceRange());
689 return QualType();
690}
691
692/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
693/// in the case of a the GNU conditional expr extension.
694Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
695 SourceLocation ColonLoc,
696 ExprTy *Cond, ExprTy *LHS,
697 ExprTy *RHS) {
698 Expr *CondExpr = (Expr *) Cond;
699 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
700 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
701 RHSExpr, QuestionLoc);
702 if (result.isNull())
703 return true;
704 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
705}
706
707// promoteExprToType - a helper function to ensure we create exactly one
708// ImplicitCastExpr. As a convenience (to the caller), we return the type.
709static void promoteExprToType(Expr *&expr, QualType type) {
710 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
711 impCast->setType(type);
712 else
713 expr = new ImplicitCastExpr(type, expr);
714 return;
715}
716
717/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
718void Sema::DefaultFunctionArrayConversion(Expr *&e) {
719 QualType t = e->getType();
720 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
721
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000722 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000723 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
724 t = e->getType();
725 }
726 if (t->isFunctionType())
727 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000728 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000729 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
730}
731
732/// UsualUnaryConversion - Performs various conversions that are common to most
733/// operators (C99 6.3). The conversions of array and function types are
734/// sometimes surpressed. For example, the array->pointer conversion doesn't
735/// apply if the array is an argument to the sizeof or address (&) operators.
736/// In these instances, this routine should *not* be called.
737void Sema::UsualUnaryConversions(Expr *&expr) {
738 QualType t = expr->getType();
739 assert(!t.isNull() && "UsualUnaryConversions - missing type");
740
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000741 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000742 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
743 t = expr->getType();
744 }
745 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
746 promoteExprToType(expr, Context.IntTy);
747 else
748 DefaultFunctionArrayConversion(expr);
749}
750
751/// UsualArithmeticConversions - Performs various conversions that are common to
752/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
753/// routine returns the first non-arithmetic type found. The client is
754/// responsible for emitting appropriate error diagnostics.
755void Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr) {
756 UsualUnaryConversions(lhsExpr);
757 UsualUnaryConversions(rhsExpr);
758
759 QualType lhs = lhsExpr->getType();
760 QualType rhs = rhsExpr->getType();
761
762 // If both types are identical, no conversion is needed.
763 if (lhs == rhs)
764 return;
765
766 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
767 // The caller can deal with this (e.g. pointer + int).
768 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
769 return;
770
771 // At this point, we have two different arithmetic types.
772
773 // Handle complex types first (C99 6.3.1.8p1).
774 if (lhs->isComplexType() || rhs->isComplexType()) {
775 // if we have an integer operand, the result is the complex type.
776 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
777 promoteExprToType(rhsExpr, lhs);
778 return;
779 }
780 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
781 promoteExprToType(lhsExpr, rhs);
782 return;
783 }
784 // Two complex types. Convert the smaller operand to the bigger result.
785 if (Context.maxComplexType(lhs, rhs) == lhs) { // convert the rhs
786 promoteExprToType(rhsExpr, lhs);
787 return;
788 }
789 promoteExprToType(lhsExpr, rhs); // convert the lhs
790 return;
791 }
792 // Now handle "real" floating types (i.e. float, double, long double).
793 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
794 // if we have an integer operand, the result is the real floating type.
795 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
796 promoteExprToType(rhsExpr, lhs);
797 return;
798 }
799 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
800 promoteExprToType(lhsExpr, rhs);
801 return;
802 }
803 // We have two real floating types, float/complex combos were handled above.
804 // Convert the smaller operand to the bigger result.
805 if (Context.maxFloatingType(lhs, rhs) == lhs) { // convert the rhs
806 promoteExprToType(rhsExpr, lhs);
807 return;
808 }
809 promoteExprToType(lhsExpr, rhs); // convert the lhs
810 return;
811 }
812 // Finally, we have two differing integer types.
813 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
814 promoteExprToType(rhsExpr, lhs);
815 return;
816 }
817 promoteExprToType(lhsExpr, rhs); // convert the lhs
818 return;
819}
820
821// CheckPointerTypesForAssignment - This is a very tricky routine (despite
822// being closely modeled after the C99 spec:-). The odd characteristic of this
823// routine is it effectively iqnores the qualifiers on the top level pointee.
824// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
825// FIXME: add a couple examples in this comment.
826Sema::AssignmentCheckResult
827Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
828 QualType lhptee, rhptee;
829
830 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +0000831 lhptee = lhsType->getAsPointerType()->getPointeeType();
832 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000833
834 // make sure we operate on the canonical type
835 lhptee = lhptee.getCanonicalType();
836 rhptee = rhptee.getCanonicalType();
837
838 AssignmentCheckResult r = Compatible;
839
840 // C99 6.5.16.1p1: This following citation is common to constraints
841 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
842 // qualifiers of the type *pointed to* by the right;
843 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
844 rhptee.getQualifiers())
845 r = CompatiblePointerDiscardsQualifiers;
846
847 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
848 // incomplete type and the other is a pointer to a qualified or unqualified
849 // version of void...
850 if (lhptee.getUnqualifiedType()->isVoidType() &&
851 (rhptee->isObjectType() || rhptee->isIncompleteType()))
852 ;
853 else if (rhptee.getUnqualifiedType()->isVoidType() &&
854 (lhptee->isObjectType() || lhptee->isIncompleteType()))
855 ;
856 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
857 // unqualified versions of compatible types, ...
858 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
859 rhptee.getUnqualifiedType()))
860 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
861 return r;
862}
863
864/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
865/// has code to accommodate several GCC extensions when type checking
866/// pointers. Here are some objectionable examples that GCC considers warnings:
867///
868/// int a, *pint;
869/// short *pshort;
870/// struct foo *pfoo;
871///
872/// pint = pshort; // warning: assignment from incompatible pointer type
873/// a = pint; // warning: assignment makes integer from pointer without a cast
874/// pint = a; // warning: assignment makes pointer from integer without a cast
875/// pint = pfoo; // warning: assignment from incompatible pointer type
876///
877/// As a result, the code for dealing with pointers is more complex than the
878/// C99 spec dictates.
879/// Note: the warning above turn into errors when -pedantic-errors is enabled.
880///
881Sema::AssignmentCheckResult
882Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
883 if (lhsType == rhsType) // common case, fast path...
884 return Compatible;
885
886 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
887 if (lhsType->isVectorType() || rhsType->isVectorType()) {
888 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
889 return Incompatible;
890 }
891 return Compatible;
892 } else if (lhsType->isPointerType()) {
893 if (rhsType->isIntegerType())
894 return PointerFromInt;
895
896 if (rhsType->isPointerType())
897 return CheckPointerTypesForAssignment(lhsType, rhsType);
898 } else if (rhsType->isPointerType()) {
899 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
900 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
901 return IntFromPointer;
902
903 if (lhsType->isPointerType())
904 return CheckPointerTypesForAssignment(lhsType, rhsType);
905 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
906 if (Type::tagTypesAreCompatible(lhsType, rhsType))
907 return Compatible;
908 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
909 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
910 return Compatible;
911 }
912 return Incompatible;
913}
914
915Sema::AssignmentCheckResult
916Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
917 // This check seems unnatural, however it is necessary to insure the proper
918 // conversion of functions/arrays. If the conversion were done for all
919 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
920 // expressions that surpress this implicit conversion (&, sizeof).
921 DefaultFunctionArrayConversion(rExpr);
922
923 return CheckAssignmentConstraints(lhsType, rExpr->getType());
924}
925
926Sema::AssignmentCheckResult
927Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
928 return CheckAssignmentConstraints(lhsType, rhsType);
929}
930
931inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
932 Diag(loc, diag::err_typecheck_invalid_operands,
933 lex->getType().getAsString(), rex->getType().getAsString(),
934 lex->getSourceRange(), rex->getSourceRange());
935}
936
937inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
938 Expr *&rex) {
939 QualType lhsType = lex->getType(), rhsType = rex->getType();
940
941 // make sure the vector types are identical.
942 if (lhsType == rhsType)
943 return lhsType;
944 // You cannot convert between vector values of different size.
945 Diag(loc, diag::err_typecheck_vector_not_convertable,
946 lex->getType().getAsString(), rex->getType().getAsString(),
947 lex->getSourceRange(), rex->getSourceRange());
948 return QualType();
949}
950
951inline QualType Sema::CheckMultiplyDivideOperands(
952 Expr *&lex, Expr *&rex, SourceLocation loc)
953{
954 QualType lhsType = lex->getType(), rhsType = rex->getType();
955
956 if (lhsType->isVectorType() || rhsType->isVectorType())
957 return CheckVectorOperands(loc, lex, rex);
958
959 UsualArithmeticConversions(lex, rex);
960
961 // handle the common case first (both operands are arithmetic).
962 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
963 return lex->getType();
964 InvalidOperands(loc, lex, rex);
965 return QualType();
966}
967
968inline QualType Sema::CheckRemainderOperands(
969 Expr *&lex, Expr *&rex, SourceLocation loc)
970{
971 QualType lhsType = lex->getType(), rhsType = rex->getType();
972
973 UsualArithmeticConversions(lex, rex);
974
975 // handle the common case first (both operands are arithmetic).
976 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
977 return lex->getType();
978 InvalidOperands(loc, lex, rex);
979 return QualType();
980}
981
982inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
983 Expr *&lex, Expr *&rex, SourceLocation loc)
984{
985 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
986 return CheckVectorOperands(loc, lex, rex);
987
988 UsualArithmeticConversions(lex, rex);
989
990 // handle the common case first (both operands are arithmetic).
991 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
992 return lex->getType();
993
994 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
995 return lex->getType();
996 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
997 return rex->getType();
998 InvalidOperands(loc, lex, rex);
999 return QualType();
1000}
1001
1002inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
1003 Expr *&lex, Expr *&rex, SourceLocation loc)
1004{
1005 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1006 return CheckVectorOperands(loc, lex, rex);
1007
1008 UsualArithmeticConversions(lex, rex);
1009
1010 // handle the common case first (both operands are arithmetic).
1011 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1012 return lex->getType();
1013
1014 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1015 return lex->getType();
1016 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1017 return Context.getPointerDiffType();
1018 InvalidOperands(loc, lex, rex);
1019 return QualType();
1020}
1021
1022inline QualType Sema::CheckShiftOperands( // C99 6.5.7
1023 Expr *&lex, Expr *&rex, SourceLocation loc)
1024{
1025 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1026 // for int << longlong -> the result type should be int, not long long.
1027 UsualArithmeticConversions(lex, rex);
1028
1029 // handle the common case first (both operands are arithmetic).
1030 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1031 return lex->getType();
1032 InvalidOperands(loc, lex, rex);
1033 return QualType();
1034}
1035
1036inline QualType Sema::CheckRelationalOperands( // C99 6.5.8
1037 Expr *&lex, Expr *&rex, SourceLocation loc)
1038{
Steve Naroffecc4fa12007-08-10 18:26:40 +00001039 // C99 6.5.8p3
1040 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1041 UsualArithmeticConversions(lex, rex);
1042 else {
1043 UsualUnaryConversions(lex);
1044 UsualUnaryConversions(rex);
1045 }
Chris Lattner4b009652007-07-25 00:24:17 +00001046 QualType lType = lex->getType();
1047 QualType rType = rex->getType();
1048
1049 if (lType->isRealType() && rType->isRealType())
1050 return Context.IntTy;
1051
Steve Naroff4462cb02007-08-16 21:48:38 +00001052 // All of the following pointer related warnings are GCC extensions. One
1053 // day, we can consider making them errors (when -pedantic-errors is enabled).
1054 if (lType->isPointerType() && rType->isPointerType()) {
1055 if (!Type::pointerTypesAreCompatible(lType, rType)) {
1056 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1057 lType.getAsString(), rType.getAsString(),
1058 lex->getSourceRange(), rex->getSourceRange());
1059 promoteExprToType(rex, lType); // promote the pointer to pointer
Chris Lattner4b009652007-07-25 00:24:17 +00001060 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001061 return Context.IntTy;
1062 }
1063 if (lType->isPointerType() && rType->isIntegerType()) {
1064 if (!rex->isNullPointerConstant(Context)) {
1065 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1066 lType.getAsString(), rType.getAsString(),
1067 lex->getSourceRange(), rex->getSourceRange());
1068 promoteExprToType(rex, lType); // promote the integer to pointer
Chris Lattner4b009652007-07-25 00:24:17 +00001069 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001070 return Context.IntTy;
1071 }
1072 if (lType->isIntegerType() && rType->isPointerType()) {
1073 if (!lex->isNullPointerConstant(Context)) {
1074 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1075 lType.getAsString(), rType.getAsString(),
1076 lex->getSourceRange(), rex->getSourceRange());
1077 promoteExprToType(lex, rType); // promote the integer to pointer
1078 }
1079 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001080 }
1081 InvalidOperands(loc, lex, rex);
1082 return QualType();
1083}
1084
1085inline QualType Sema::CheckEqualityOperands( // C99 6.5.9
1086 Expr *&lex, Expr *&rex, SourceLocation loc)
1087{
Steve Naroffecc4fa12007-08-10 18:26:40 +00001088 // C99 6.5.9p4
1089 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1090 UsualArithmeticConversions(lex, rex);
1091 else {
1092 UsualUnaryConversions(lex);
1093 UsualUnaryConversions(rex);
1094 }
Chris Lattner4b009652007-07-25 00:24:17 +00001095 QualType lType = lex->getType();
1096 QualType rType = rex->getType();
1097
1098 if (lType->isArithmeticType() && rType->isArithmeticType())
1099 return Context.IntTy;
1100
Steve Naroff4462cb02007-08-16 21:48:38 +00001101 // All of the following pointer related warnings are GCC extensions. One
1102 // day, we can consider making them errors (when -pedantic-errors is enabled).
1103 if (lType->isPointerType() && rType->isPointerType()) {
1104 if (!Type::pointerTypesAreCompatible(lType, rType)) {
1105 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1106 lType.getAsString(), rType.getAsString(),
1107 lex->getSourceRange(), rex->getSourceRange());
1108 promoteExprToType(rex, lType); // promote the pointer to pointer
Chris Lattner4b009652007-07-25 00:24:17 +00001109 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001110 return Context.IntTy;
1111 }
1112 if (lType->isPointerType() && rType->isIntegerType()) {
1113 if (!rex->isNullPointerConstant(Context)) {
1114 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1115 lType.getAsString(), rType.getAsString(),
1116 lex->getSourceRange(), rex->getSourceRange());
1117 promoteExprToType(rex, lType); // promote the integer to pointer
Chris Lattner4b009652007-07-25 00:24:17 +00001118 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001119 return Context.IntTy;
1120 }
1121 if (lType->isIntegerType() && rType->isPointerType()) {
1122 if (!lex->isNullPointerConstant(Context)) {
1123 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1124 lType.getAsString(), rType.getAsString(),
1125 lex->getSourceRange(), rex->getSourceRange());
1126 promoteExprToType(lex, rType); // promote the integer to pointer
1127 }
1128 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001129 }
1130 InvalidOperands(loc, lex, rex);
1131 return QualType();
1132}
1133
1134inline QualType Sema::CheckBitwiseOperands(
1135 Expr *&lex, Expr *&rex, SourceLocation loc)
1136{
1137 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1138 return CheckVectorOperands(loc, lex, rex);
1139
1140 UsualArithmeticConversions(lex, rex);
1141
1142 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1143 return lex->getType();
1144 InvalidOperands(loc, lex, rex);
1145 return QualType();
1146}
1147
1148inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1149 Expr *&lex, Expr *&rex, SourceLocation loc)
1150{
1151 UsualUnaryConversions(lex);
1152 UsualUnaryConversions(rex);
1153
1154 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1155 return Context.IntTy;
1156 InvalidOperands(loc, lex, rex);
1157 return QualType();
1158}
1159
1160inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
1161 Expr *lex, Expr *rex, SourceLocation loc, QualType compoundType)
1162{
1163 QualType lhsType = lex->getType();
1164 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1165 bool hadError = false;
1166 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1167
1168 switch (mlval) { // C99 6.5.16p2
1169 case Expr::MLV_Valid:
1170 break;
1171 case Expr::MLV_ConstQualified:
1172 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1173 hadError = true;
1174 break;
1175 case Expr::MLV_ArrayType:
1176 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1177 lhsType.getAsString(), lex->getSourceRange());
1178 return QualType();
1179 case Expr::MLV_NotObjectType:
1180 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1181 lhsType.getAsString(), lex->getSourceRange());
1182 return QualType();
1183 case Expr::MLV_InvalidExpression:
1184 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1185 lex->getSourceRange());
1186 return QualType();
1187 case Expr::MLV_IncompleteType:
1188 case Expr::MLV_IncompleteVoidType:
1189 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1190 lhsType.getAsString(), lex->getSourceRange());
1191 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001192 case Expr::MLV_DuplicateVectorComponents:
1193 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1194 lex->getSourceRange());
1195 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001196 }
1197 AssignmentCheckResult result;
1198
1199 if (compoundType.isNull())
1200 result = CheckSingleAssignmentConstraints(lhsType, rex);
1201 else
1202 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001203
Chris Lattner4b009652007-07-25 00:24:17 +00001204 // decode the result (notice that extensions still return a type).
1205 switch (result) {
1206 case Compatible:
1207 break;
1208 case Incompatible:
1209 Diag(loc, diag::err_typecheck_assign_incompatible,
1210 lhsType.getAsString(), rhsType.getAsString(),
1211 lex->getSourceRange(), rex->getSourceRange());
1212 hadError = true;
1213 break;
1214 case PointerFromInt:
1215 // check for null pointer constant (C99 6.3.2.3p3)
1216 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1217 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1218 lhsType.getAsString(), rhsType.getAsString(),
1219 lex->getSourceRange(), rex->getSourceRange());
1220 }
1221 break;
1222 case IntFromPointer:
1223 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1224 lhsType.getAsString(), rhsType.getAsString(),
1225 lex->getSourceRange(), rex->getSourceRange());
1226 break;
1227 case IncompatiblePointer:
1228 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1229 lhsType.getAsString(), rhsType.getAsString(),
1230 lex->getSourceRange(), rex->getSourceRange());
1231 break;
1232 case CompatiblePointerDiscardsQualifiers:
1233 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1234 lhsType.getAsString(), rhsType.getAsString(),
1235 lex->getSourceRange(), rex->getSourceRange());
1236 break;
1237 }
1238 // C99 6.5.16p3: The type of an assignment expression is the type of the
1239 // left operand unless the left operand has qualified type, in which case
1240 // it is the unqualified version of the type of the left operand.
1241 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1242 // is converted to the type of the assignment expression (above).
1243 // C++ 5.17p1: the type of the assignment expression is that of its left oprdu.
1244 return hadError ? QualType() : lhsType.getUnqualifiedType();
1245}
1246
1247inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1248 Expr *&lex, Expr *&rex, SourceLocation loc) {
1249 UsualUnaryConversions(rex);
1250 return rex->getType();
1251}
1252
1253/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1254/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1255QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1256 QualType resType = op->getType();
1257 assert(!resType.isNull() && "no type for increment/decrement expression");
1258
Steve Naroffd30e1932007-08-24 17:20:07 +00001259 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattner4b009652007-07-25 00:24:17 +00001260 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1261 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1262 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1263 resType.getAsString(), op->getSourceRange());
1264 return QualType();
1265 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001266 } else if (!resType->isRealType()) {
1267 if (resType->isComplexType())
1268 // C99 does not support ++/-- on complex types.
1269 Diag(OpLoc, diag::ext_integer_increment_complex,
1270 resType.getAsString(), op->getSourceRange());
1271 else {
1272 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1273 resType.getAsString(), op->getSourceRange());
1274 return QualType();
1275 }
Chris Lattner4b009652007-07-25 00:24:17 +00001276 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001277 // At this point, we know we have a real, complex or pointer type.
1278 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001279 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1280 if (mlval != Expr::MLV_Valid) {
1281 // FIXME: emit a more precise diagnostic...
1282 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1283 op->getSourceRange());
1284 return QualType();
1285 }
1286 return resType;
1287}
1288
1289/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1290/// This routine allows us to typecheck complex/recursive expressions
1291/// where the declaration is needed for type checking. Here are some
1292/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1293static Decl *getPrimaryDeclaration(Expr *e) {
1294 switch (e->getStmtClass()) {
1295 case Stmt::DeclRefExprClass:
1296 return cast<DeclRefExpr>(e)->getDecl();
1297 case Stmt::MemberExprClass:
1298 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1299 case Stmt::ArraySubscriptExprClass:
1300 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1301 case Stmt::CallExprClass:
1302 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1303 case Stmt::UnaryOperatorClass:
1304 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1305 case Stmt::ParenExprClass:
1306 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1307 default:
1308 return 0;
1309 }
1310}
1311
1312/// CheckAddressOfOperand - The operand of & must be either a function
1313/// designator or an lvalue designating an object. If it is an lvalue, the
1314/// object cannot be declared with storage class register or be a bit field.
1315/// Note: The usual conversions are *not* applied to the operand of the &
1316/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1317QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1318 Decl *dcl = getPrimaryDeclaration(op);
1319 Expr::isLvalueResult lval = op->isLvalue();
1320
1321 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1322 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1323 ;
1324 else { // FIXME: emit more specific diag...
1325 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1326 op->getSourceRange());
1327 return QualType();
1328 }
1329 } else if (dcl) {
1330 // We have an lvalue with a decl. Make sure the decl is not declared
1331 // with the register storage-class specifier.
1332 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1333 if (vd->getStorageClass() == VarDecl::Register) {
1334 Diag(OpLoc, diag::err_typecheck_address_of_register,
1335 op->getSourceRange());
1336 return QualType();
1337 }
1338 } else
1339 assert(0 && "Unknown/unexpected decl type");
1340
1341 // FIXME: add check for bitfields!
1342 }
1343 // If the operand has type "type", the result has type "pointer to type".
1344 return Context.getPointerType(op->getType());
1345}
1346
1347QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1348 UsualUnaryConversions(op);
1349 QualType qType = op->getType();
1350
Chris Lattner7931f4a2007-07-31 16:53:04 +00001351 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001352 QualType ptype = PT->getPointeeType();
1353 // C99 6.5.3.2p4. "if it points to an object,...".
1354 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1355 // GCC compat: special case 'void *' (treat as warning).
1356 if (ptype->isVoidType()) {
1357 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1358 qType.getAsString(), op->getSourceRange());
1359 } else {
1360 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1361 ptype.getAsString(), op->getSourceRange());
1362 return QualType();
1363 }
1364 }
1365 return ptype;
1366 }
1367 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1368 qType.getAsString(), op->getSourceRange());
1369 return QualType();
1370}
1371
1372static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1373 tok::TokenKind Kind) {
1374 BinaryOperator::Opcode Opc;
1375 switch (Kind) {
1376 default: assert(0 && "Unknown binop!");
1377 case tok::star: Opc = BinaryOperator::Mul; break;
1378 case tok::slash: Opc = BinaryOperator::Div; break;
1379 case tok::percent: Opc = BinaryOperator::Rem; break;
1380 case tok::plus: Opc = BinaryOperator::Add; break;
1381 case tok::minus: Opc = BinaryOperator::Sub; break;
1382 case tok::lessless: Opc = BinaryOperator::Shl; break;
1383 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1384 case tok::lessequal: Opc = BinaryOperator::LE; break;
1385 case tok::less: Opc = BinaryOperator::LT; break;
1386 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1387 case tok::greater: Opc = BinaryOperator::GT; break;
1388 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1389 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1390 case tok::amp: Opc = BinaryOperator::And; break;
1391 case tok::caret: Opc = BinaryOperator::Xor; break;
1392 case tok::pipe: Opc = BinaryOperator::Or; break;
1393 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1394 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1395 case tok::equal: Opc = BinaryOperator::Assign; break;
1396 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1397 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1398 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1399 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1400 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1401 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1402 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1403 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1404 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1405 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1406 case tok::comma: Opc = BinaryOperator::Comma; break;
1407 }
1408 return Opc;
1409}
1410
1411static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1412 tok::TokenKind Kind) {
1413 UnaryOperator::Opcode Opc;
1414 switch (Kind) {
1415 default: assert(0 && "Unknown unary op!");
1416 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1417 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1418 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1419 case tok::star: Opc = UnaryOperator::Deref; break;
1420 case tok::plus: Opc = UnaryOperator::Plus; break;
1421 case tok::minus: Opc = UnaryOperator::Minus; break;
1422 case tok::tilde: Opc = UnaryOperator::Not; break;
1423 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1424 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1425 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1426 case tok::kw___real: Opc = UnaryOperator::Real; break;
1427 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1428 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1429 }
1430 return Opc;
1431}
1432
1433// Binary Operators. 'Tok' is the token for the operator.
1434Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1435 ExprTy *LHS, ExprTy *RHS) {
1436 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1437 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1438
1439 assert((lhs != 0) && "ParseBinOp(): missing left expression");
1440 assert((rhs != 0) && "ParseBinOp(): missing right expression");
1441
1442 QualType ResultTy; // Result type of the binary operator.
1443 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1444
1445 switch (Opc) {
1446 default:
1447 assert(0 && "Unknown binary expr!");
1448 case BinaryOperator::Assign:
1449 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1450 break;
1451 case BinaryOperator::Mul:
1452 case BinaryOperator::Div:
1453 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1454 break;
1455 case BinaryOperator::Rem:
1456 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1457 break;
1458 case BinaryOperator::Add:
1459 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1460 break;
1461 case BinaryOperator::Sub:
1462 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1463 break;
1464 case BinaryOperator::Shl:
1465 case BinaryOperator::Shr:
1466 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1467 break;
1468 case BinaryOperator::LE:
1469 case BinaryOperator::LT:
1470 case BinaryOperator::GE:
1471 case BinaryOperator::GT:
1472 ResultTy = CheckRelationalOperands(lhs, rhs, TokLoc);
1473 break;
1474 case BinaryOperator::EQ:
1475 case BinaryOperator::NE:
1476 ResultTy = CheckEqualityOperands(lhs, rhs, TokLoc);
1477 break;
1478 case BinaryOperator::And:
1479 case BinaryOperator::Xor:
1480 case BinaryOperator::Or:
1481 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1482 break;
1483 case BinaryOperator::LAnd:
1484 case BinaryOperator::LOr:
1485 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1486 break;
1487 case BinaryOperator::MulAssign:
1488 case BinaryOperator::DivAssign:
1489 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1490 if (!CompTy.isNull())
1491 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1492 break;
1493 case BinaryOperator::RemAssign:
1494 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1495 if (!CompTy.isNull())
1496 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1497 break;
1498 case BinaryOperator::AddAssign:
1499 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1500 if (!CompTy.isNull())
1501 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1502 break;
1503 case BinaryOperator::SubAssign:
1504 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1505 if (!CompTy.isNull())
1506 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1507 break;
1508 case BinaryOperator::ShlAssign:
1509 case BinaryOperator::ShrAssign:
1510 CompTy = CheckShiftOperands(lhs, rhs, TokLoc);
1511 if (!CompTy.isNull())
1512 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1513 break;
1514 case BinaryOperator::AndAssign:
1515 case BinaryOperator::XorAssign:
1516 case BinaryOperator::OrAssign:
1517 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1518 if (!CompTy.isNull())
1519 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1520 break;
1521 case BinaryOperator::Comma:
1522 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1523 break;
1524 }
1525 if (ResultTy.isNull())
1526 return true;
1527 if (CompTy.isNull())
1528 return new BinaryOperator(lhs, rhs, Opc, ResultTy);
1529 else
1530 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy);
1531}
1532
1533// Unary Operators. 'Tok' is the token for the operator.
1534Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1535 ExprTy *input) {
1536 Expr *Input = (Expr*)input;
1537 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1538 QualType resultType;
1539 switch (Opc) {
1540 default:
1541 assert(0 && "Unimplemented unary expr!");
1542 case UnaryOperator::PreInc:
1543 case UnaryOperator::PreDec:
1544 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1545 break;
1546 case UnaryOperator::AddrOf:
1547 resultType = CheckAddressOfOperand(Input, OpLoc);
1548 break;
1549 case UnaryOperator::Deref:
1550 resultType = CheckIndirectionOperand(Input, OpLoc);
1551 break;
1552 case UnaryOperator::Plus:
1553 case UnaryOperator::Minus:
1554 UsualUnaryConversions(Input);
1555 resultType = Input->getType();
1556 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1557 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1558 resultType.getAsString());
1559 break;
1560 case UnaryOperator::Not: // bitwise complement
1561 UsualUnaryConversions(Input);
1562 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001563 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1564 if (!resultType->isIntegerType()) {
1565 if (resultType->isComplexType())
1566 // C99 does not support '~' for complex conjugation.
1567 Diag(OpLoc, diag::ext_integer_complement_complex,
1568 resultType.getAsString());
1569 else
1570 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1571 resultType.getAsString());
1572 }
Chris Lattner4b009652007-07-25 00:24:17 +00001573 break;
1574 case UnaryOperator::LNot: // logical negation
1575 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1576 DefaultFunctionArrayConversion(Input);
1577 resultType = Input->getType();
1578 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1579 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1580 resultType.getAsString());
1581 // LNot always has type int. C99 6.5.3.3p5.
1582 resultType = Context.IntTy;
1583 break;
1584 case UnaryOperator::SizeOf:
1585 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1586 break;
1587 case UnaryOperator::AlignOf:
1588 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1589 break;
1590 case UnaryOperator::Extension:
1591 // FIXME: does __extension__ cause any promotions? I would think not.
1592 resultType = Input->getType();
1593 break;
1594 }
1595 if (resultType.isNull())
1596 return true;
1597 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1598}
1599
1600/// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
1601Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
1602 SourceLocation LabLoc,
1603 IdentifierInfo *LabelII) {
1604 // Look up the record for this label identifier.
1605 LabelStmt *&LabelDecl = LabelMap[LabelII];
1606
1607 // If we haven't seen this label yet, create a forward reference.
1608 if (LabelDecl == 0)
1609 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1610
1611 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001612 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1613 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001614}
1615
1616Sema::ExprResult Sema::ParseStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
1617 SourceLocation RPLoc) { // "({..})"
1618 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1619 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1620 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1621
1622 // FIXME: there are a variety of strange constraints to enforce here, for
1623 // example, it is not possible to goto into a stmt expression apparently.
1624 // More semantic analysis is needed.
1625
1626 // FIXME: the last statement in the compount stmt has its value used. We
1627 // should not warn about it being unused.
1628
1629 // If there are sub stmts in the compound stmt, take the type of the last one
1630 // as the type of the stmtexpr.
1631 QualType Ty = Context.VoidTy;
1632
1633 if (!Compound->body_empty())
1634 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1635 Ty = LastExpr->getType();
1636
1637 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1638}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001639
Steve Naroff5b528922007-08-01 23:45:51 +00001640Sema::ExprResult Sema::ParseTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001641 TypeTy *arg1, TypeTy *arg2,
1642 SourceLocation RPLoc) {
1643 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1644 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1645
1646 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1647
Steve Naroff5b528922007-08-01 23:45:51 +00001648 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001649}
1650
Steve Naroff93c53012007-08-03 21:21:27 +00001651Sema::ExprResult Sema::ParseChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
1652 ExprTy *expr1, ExprTy *expr2,
1653 SourceLocation RPLoc) {
1654 Expr *CondExpr = static_cast<Expr*>(cond);
1655 Expr *LHSExpr = static_cast<Expr*>(expr1);
1656 Expr *RHSExpr = static_cast<Expr*>(expr2);
1657
1658 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1659
1660 // The conditional expression is required to be a constant expression.
1661 llvm::APSInt condEval(32);
1662 SourceLocation ExpLoc;
1663 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1664 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1665 CondExpr->getSourceRange());
1666
1667 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1668 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1669 RHSExpr->getType();
1670 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1671}
1672
Anders Carlssona66cad42007-08-21 17:43:55 +00001673// TODO: Move this to SemaObjC.cpp
Anders Carlsson8be1d402007-08-22 15:14:15 +00001674Sema::ExprResult Sema::ParseObjCStringLiteral(ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00001675 StringLiteral* S = static_cast<StringLiteral *>(string);
1676
1677 if (CheckBuiltinCFStringArgument(S))
1678 return true;
1679
1680 QualType t = Context.getCFConstantStringType();
1681 t = t.getQualifiedType(QualType::Const);
1682 t = Context.getPointerType(t);
1683
1684 return new ObjCStringLiteral(S, t);
1685}
Anders Carlsson8be1d402007-08-22 15:14:15 +00001686
1687Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1688 SourceLocation LParenLoc,
1689 TypeTy *Ty,
1690 SourceLocation RParenLoc) {
1691 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
1692
1693 QualType t = Context.getPointerType(Context.CharTy);
1694 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
1695}