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