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