blob: 91d6d8de9b19c5d6e6c4d68fddc5bd98ed6ed32d [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;
306 if (const PointerType *PTy = LHSTy->isPointerType()) {
307 BaseExpr = LHSExp;
308 IndexExpr = RHSExp;
309 // FIXME: need to deal with const...
310 ResultType = PTy->getPointeeType();
311 } else if (const PointerType *PTy = RHSTy->isPointerType()) {
312 // Handle the uncommon case of "123[Ptr]".
313 BaseExpr = RHSExp;
314 IndexExpr = LHSExp;
315 // FIXME: need to deal with const...
316 ResultType = PTy->getPointeeType();
317 } else if (const VectorType *VTy = LHSTy->isVectorType()) { // vectors: V[123]
318 BaseExpr = LHSExp;
319 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) {
345 const OCUVectorType *vecType = baseType->isOCUVectorType();
346
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();
390 return Context.getOCUVectorType(vecType->getElementType(), CompSize);
391}
392
Chris Lattner4b009652007-07-25 00:24:17 +0000393Action::ExprResult Sema::
394ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
395 tok::TokenKind OpKind, SourceLocation MemberLoc,
396 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000397 Expr *BaseExpr = static_cast<Expr *>(Base);
398 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000399
Steve Naroff2cb66382007-07-26 03:11:44 +0000400 QualType BaseType = BaseExpr->getType();
401 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000402
Chris Lattner4b009652007-07-25 00:24:17 +0000403 if (OpKind == tok::arrow) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000404 if (const PointerType *PT = BaseType->isPointerType())
405 BaseType = PT->getPointeeType();
406 else
407 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
408 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000409 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000410 // The base type is either a record or an OCUVectorType.
Steve Naroff2cb66382007-07-26 03:11:44 +0000411 if (const RecordType *RTy = BaseType->isRecordType()) {
412 RecordDecl *RDecl = RTy->getDecl();
413 if (RTy->isIncompleteType())
414 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
415 BaseExpr->getSourceRange());
416 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000417 FieldDecl *MemberDecl = RDecl->getMember(&Member);
418 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000419 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
420 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000421 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
422 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
423 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
424 if (ret.isNull())
425 return true;
426 // FIXME: instantiate a OCUVectorComponentExpr node...
427 return true;
Steve Naroff2cb66382007-07-26 03:11:44 +0000428 } else
429 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
430 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000431}
432
433/// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
434/// This provides the location of the left/right parens and a list of comma
435/// locations.
436Action::ExprResult Sema::
437ParseCallExpr(ExprTy *fn, SourceLocation LParenLoc,
438 ExprTy **args, unsigned NumArgsInCall,
439 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
440 Expr *Fn = static_cast<Expr *>(fn);
441 Expr **Args = reinterpret_cast<Expr**>(args);
442 assert(Fn && "no function call expression");
443
444 UsualUnaryConversions(Fn);
445 QualType funcType = Fn->getType();
446
447 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
448 // type pointer to function".
449 const PointerType *PT = dyn_cast<PointerType>(funcType);
450 if (PT == 0) PT = dyn_cast<PointerType>(funcType.getCanonicalType());
451
452 if (PT == 0)
453 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
454 SourceRange(Fn->getLocStart(), RParenLoc));
455
456 const FunctionType *funcT = dyn_cast<FunctionType>(PT->getPointeeType());
457 if (funcT == 0)
458 funcT = dyn_cast<FunctionType>(PT->getPointeeType().getCanonicalType());
459
460 if (funcT == 0)
461 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
462 SourceRange(Fn->getLocStart(), RParenLoc));
463
464 // If a prototype isn't declared, the parser implicitly defines a func decl
465 QualType resultType = funcT->getResultType();
466
467 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
468 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
469 // assignment, to the types of the corresponding parameter, ...
470
471 unsigned NumArgsInProto = proto->getNumArgs();
472 unsigned NumArgsToCheck = NumArgsInCall;
473
474 if (NumArgsInCall < NumArgsInProto)
475 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
476 Fn->getSourceRange());
477 else if (NumArgsInCall > NumArgsInProto) {
478 if (!proto->isVariadic()) {
479 Diag(Args[NumArgsInProto]->getLocStart(),
480 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
481 SourceRange(Args[NumArgsInProto]->getLocStart(),
482 Args[NumArgsInCall-1]->getLocEnd()));
483 }
484 NumArgsToCheck = NumArgsInProto;
485 }
486 // Continue to check argument types (even if we have too few/many args).
487 for (unsigned i = 0; i < NumArgsToCheck; i++) {
488 Expr *argExpr = Args[i];
489 assert(argExpr && "ParseCallExpr(): missing argument expression");
490
491 QualType lhsType = proto->getArgType(i);
492 QualType rhsType = argExpr->getType();
493
Steve Naroff75644062007-07-25 20:45:33 +0000494 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattner4b009652007-07-25 00:24:17 +0000495 if (const ArrayType *ary = lhsType->isArrayType())
496 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000497 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000498 lhsType = Context.getPointerType(lhsType);
499
500 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
501 argExpr);
502 SourceLocation l = argExpr->getLocStart();
503
504 // decode the result (notice that AST's are still created for extensions).
505 switch (result) {
506 case Compatible:
507 break;
508 case PointerFromInt:
509 // check for null pointer constant (C99 6.3.2.3p3)
510 if (!argExpr->isNullPointerConstant(Context)) {
511 Diag(l, diag::ext_typecheck_passing_pointer_int,
512 lhsType.getAsString(), rhsType.getAsString(),
513 Fn->getSourceRange(), argExpr->getSourceRange());
514 }
515 break;
516 case IntFromPointer:
517 Diag(l, diag::ext_typecheck_passing_pointer_int,
518 lhsType.getAsString(), rhsType.getAsString(),
519 Fn->getSourceRange(), argExpr->getSourceRange());
520 break;
521 case IncompatiblePointer:
522 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
523 rhsType.getAsString(), lhsType.getAsString(),
524 Fn->getSourceRange(), argExpr->getSourceRange());
525 break;
526 case CompatiblePointerDiscardsQualifiers:
527 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
528 rhsType.getAsString(), lhsType.getAsString(),
529 Fn->getSourceRange(), argExpr->getSourceRange());
530 break;
531 case Incompatible:
532 return Diag(l, diag::err_typecheck_passing_incompatible,
533 rhsType.getAsString(), lhsType.getAsString(),
534 Fn->getSourceRange(), argExpr->getSourceRange());
535 }
536 }
537 // Even if the types checked, bail if we had the wrong number of arguments.
538 if (NumArgsInCall != NumArgsInProto && !proto->isVariadic())
539 return true;
540 }
541 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
542}
543
544Action::ExprResult Sema::
545ParseCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
546 SourceLocation RParenLoc, ExprTy *InitExpr) {
547 assert((Ty != 0) && "ParseCompoundLiteral(): missing type");
548 QualType literalType = QualType::getFromOpaquePtr(Ty);
549 // FIXME: put back this assert when initializers are worked out.
550 //assert((InitExpr != 0) && "ParseCompoundLiteral(): missing expression");
551 Expr *literalExpr = static_cast<Expr*>(InitExpr);
552
553 // FIXME: add semantic analysis (C99 6.5.2.5).
554 return new CompoundLiteralExpr(literalType, literalExpr);
555}
556
557Action::ExprResult Sema::
558ParseInitList(SourceLocation LParenLoc, ExprTy **InitList, unsigned NumInit,
559 SourceLocation RParenLoc) {
560 // FIXME: add semantic analysis (C99 6.7.8). This involves
561 // knowledge of the object being intialized. As a result, the code for
562 // doing the semantic analysis will likely be located elsewhere (i.e. in
563 // consumers of InitListExpr (e.g. ParseDeclarator, ParseCompoundLiteral).
564 return false; // FIXME instantiate an InitListExpr.
565}
566
567Action::ExprResult Sema::
568ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
569 SourceLocation RParenLoc, ExprTy *Op) {
570 assert((Ty != 0) && (Op != 0) && "ParseCastExpr(): missing type or expr");
571
572 Expr *castExpr = static_cast<Expr*>(Op);
573 QualType castType = QualType::getFromOpaquePtr(Ty);
574
575 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
576 // type needs to be scalar.
577 if (!castType->isScalarType() && !castType->isVoidType()) {
578 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
579 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
580 }
581 if (!castExpr->getType()->isScalarType()) {
582 return Diag(castExpr->getLocStart(),
583 diag::err_typecheck_expect_scalar_operand,
584 castExpr->getType().getAsString(), castExpr->getSourceRange());
585 }
586 return new CastExpr(castType, castExpr, LParenLoc);
587}
588
589inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
590 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
591 UsualUnaryConversions(cond);
592 UsualUnaryConversions(lex);
593 UsualUnaryConversions(rex);
594 QualType condT = cond->getType();
595 QualType lexT = lex->getType();
596 QualType rexT = rex->getType();
597
598 // first, check the condition.
599 if (!condT->isScalarType()) { // C99 6.5.15p2
600 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
601 condT.getAsString());
602 return QualType();
603 }
604 // now check the two expressions.
605 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
606 UsualArithmeticConversions(lex, rex);
607 return lex->getType();
608 }
609 if ((lexT->isStructureType() && rexT->isStructureType()) || // C99 6.5.15p3
610 (lexT->isUnionType() && rexT->isUnionType())) {
611 TagType *lTag = cast<TagType>(lexT.getCanonicalType());
612 TagType *rTag = cast<TagType>(rexT.getCanonicalType());
613
614 if (lTag->getDecl()->getIdentifier() == rTag->getDecl()->getIdentifier())
615 return lexT;
616 else {
617 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
629 if (lexT->isPointerType() && rexT->isPointerType()) { // C99 6.5.15p3,6
630 QualType lhptee, rhptee;
631
632 // get the "pointed to" type
633 lhptee = cast<PointerType>(lexT.getCanonicalType())->getPointeeType();
634 rhptee = cast<PointerType>(rexT.getCanonicalType())->getPointeeType();
635
636 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
637 if (lhptee.getUnqualifiedType()->isVoidType() &&
638 (rhptee->isObjectType() || rhptee->isIncompleteType()))
639 return lexT;
640 if (rhptee.getUnqualifiedType()->isVoidType() &&
641 (lhptee->isObjectType() || lhptee->isIncompleteType()))
642 return rexT;
643
Chris Lattner4b009652007-07-25 00:24:17 +0000644 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
645 rhptee.getUnqualifiedType())) {
646 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
647 lexT.getAsString(), rexT.getAsString(),
648 lex->getSourceRange(), rex->getSourceRange());
649 return lexT; // FIXME: this is an _ext - is this return o.k?
650 }
Steve Naroffdd598cf2007-07-26 14:35:56 +0000651 // The pointer types are compatible.
652 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
653 // differently qualified versions of compatible types, the result type is a
654 // pointer to an appropriately qualified version of the *composite* type.
655 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000656 }
657 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
658 return lexT;
659
660 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
661 lexT.getAsString(), rexT.getAsString(),
662 lex->getSourceRange(), rex->getSourceRange());
663 return QualType();
664}
665
666/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
667/// in the case of a the GNU conditional expr extension.
668Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
669 SourceLocation ColonLoc,
670 ExprTy *Cond, ExprTy *LHS,
671 ExprTy *RHS) {
672 Expr *CondExpr = (Expr *) Cond;
673 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
674 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
675 RHSExpr, QuestionLoc);
676 if (result.isNull())
677 return true;
678 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
679}
680
681// promoteExprToType - a helper function to ensure we create exactly one
682// ImplicitCastExpr. As a convenience (to the caller), we return the type.
683static void promoteExprToType(Expr *&expr, QualType type) {
684 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
685 impCast->setType(type);
686 else
687 expr = new ImplicitCastExpr(type, expr);
688 return;
689}
690
691/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
692void Sema::DefaultFunctionArrayConversion(Expr *&e) {
693 QualType t = e->getType();
694 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
695
696 if (const ReferenceType *ref = t->isReferenceType()) {
697 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
698 t = e->getType();
699 }
700 if (t->isFunctionType())
701 promoteExprToType(e, Context.getPointerType(t));
702 else if (const ArrayType *ary = t->isArrayType())
703 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
704}
705
706/// UsualUnaryConversion - Performs various conversions that are common to most
707/// operators (C99 6.3). The conversions of array and function types are
708/// sometimes surpressed. For example, the array->pointer conversion doesn't
709/// apply if the array is an argument to the sizeof or address (&) operators.
710/// In these instances, this routine should *not* be called.
711void Sema::UsualUnaryConversions(Expr *&expr) {
712 QualType t = expr->getType();
713 assert(!t.isNull() && "UsualUnaryConversions - missing type");
714
715 if (const ReferenceType *ref = t->isReferenceType()) {
716 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
717 t = expr->getType();
718 }
719 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
720 promoteExprToType(expr, Context.IntTy);
721 else
722 DefaultFunctionArrayConversion(expr);
723}
724
725/// UsualArithmeticConversions - Performs various conversions that are common to
726/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
727/// routine returns the first non-arithmetic type found. The client is
728/// responsible for emitting appropriate error diagnostics.
729void Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr) {
730 UsualUnaryConversions(lhsExpr);
731 UsualUnaryConversions(rhsExpr);
732
733 QualType lhs = lhsExpr->getType();
734 QualType rhs = rhsExpr->getType();
735
736 // If both types are identical, no conversion is needed.
737 if (lhs == rhs)
738 return;
739
740 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
741 // The caller can deal with this (e.g. pointer + int).
742 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
743 return;
744
745 // At this point, we have two different arithmetic types.
746
747 // Handle complex types first (C99 6.3.1.8p1).
748 if (lhs->isComplexType() || rhs->isComplexType()) {
749 // if we have an integer operand, the result is the complex type.
750 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
751 promoteExprToType(rhsExpr, lhs);
752 return;
753 }
754 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
755 promoteExprToType(lhsExpr, rhs);
756 return;
757 }
758 // Two complex types. Convert the smaller operand to the bigger result.
759 if (Context.maxComplexType(lhs, rhs) == lhs) { // convert the rhs
760 promoteExprToType(rhsExpr, lhs);
761 return;
762 }
763 promoteExprToType(lhsExpr, rhs); // convert the lhs
764 return;
765 }
766 // Now handle "real" floating types (i.e. float, double, long double).
767 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
768 // if we have an integer operand, the result is the real floating type.
769 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
770 promoteExprToType(rhsExpr, lhs);
771 return;
772 }
773 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
774 promoteExprToType(lhsExpr, rhs);
775 return;
776 }
777 // We have two real floating types, float/complex combos were handled above.
778 // Convert the smaller operand to the bigger result.
779 if (Context.maxFloatingType(lhs, rhs) == lhs) { // convert the rhs
780 promoteExprToType(rhsExpr, lhs);
781 return;
782 }
783 promoteExprToType(lhsExpr, rhs); // convert the lhs
784 return;
785 }
786 // Finally, we have two differing integer types.
787 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
788 promoteExprToType(rhsExpr, lhs);
789 return;
790 }
791 promoteExprToType(lhsExpr, rhs); // convert the lhs
792 return;
793}
794
795// CheckPointerTypesForAssignment - This is a very tricky routine (despite
796// being closely modeled after the C99 spec:-). The odd characteristic of this
797// routine is it effectively iqnores the qualifiers on the top level pointee.
798// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
799// FIXME: add a couple examples in this comment.
800Sema::AssignmentCheckResult
801Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
802 QualType lhptee, rhptee;
803
804 // get the "pointed to" type (ignoring qualifiers at the top level)
805 lhptee = cast<PointerType>(lhsType.getCanonicalType())->getPointeeType();
806 rhptee = cast<PointerType>(rhsType.getCanonicalType())->getPointeeType();
807
808 // make sure we operate on the canonical type
809 lhptee = lhptee.getCanonicalType();
810 rhptee = rhptee.getCanonicalType();
811
812 AssignmentCheckResult r = Compatible;
813
814 // C99 6.5.16.1p1: This following citation is common to constraints
815 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
816 // qualifiers of the type *pointed to* by the right;
817 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
818 rhptee.getQualifiers())
819 r = CompatiblePointerDiscardsQualifiers;
820
821 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
822 // incomplete type and the other is a pointer to a qualified or unqualified
823 // version of void...
824 if (lhptee.getUnqualifiedType()->isVoidType() &&
825 (rhptee->isObjectType() || rhptee->isIncompleteType()))
826 ;
827 else if (rhptee.getUnqualifiedType()->isVoidType() &&
828 (lhptee->isObjectType() || lhptee->isIncompleteType()))
829 ;
830 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
831 // unqualified versions of compatible types, ...
832 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
833 rhptee.getUnqualifiedType()))
834 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
835 return r;
836}
837
838/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
839/// has code to accommodate several GCC extensions when type checking
840/// pointers. Here are some objectionable examples that GCC considers warnings:
841///
842/// int a, *pint;
843/// short *pshort;
844/// struct foo *pfoo;
845///
846/// pint = pshort; // warning: assignment from incompatible pointer type
847/// a = pint; // warning: assignment makes integer from pointer without a cast
848/// pint = a; // warning: assignment makes pointer from integer without a cast
849/// pint = pfoo; // warning: assignment from incompatible pointer type
850///
851/// As a result, the code for dealing with pointers is more complex than the
852/// C99 spec dictates.
853/// Note: the warning above turn into errors when -pedantic-errors is enabled.
854///
855Sema::AssignmentCheckResult
856Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
857 if (lhsType == rhsType) // common case, fast path...
858 return Compatible;
859
860 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
861 if (lhsType->isVectorType() || rhsType->isVectorType()) {
862 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
863 return Incompatible;
864 }
865 return Compatible;
866 } else if (lhsType->isPointerType()) {
867 if (rhsType->isIntegerType())
868 return PointerFromInt;
869
870 if (rhsType->isPointerType())
871 return CheckPointerTypesForAssignment(lhsType, rhsType);
872 } else if (rhsType->isPointerType()) {
873 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
874 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
875 return IntFromPointer;
876
877 if (lhsType->isPointerType())
878 return CheckPointerTypesForAssignment(lhsType, rhsType);
879 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
880 if (Type::tagTypesAreCompatible(lhsType, rhsType))
881 return Compatible;
882 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
883 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
884 return Compatible;
885 }
886 return Incompatible;
887}
888
889Sema::AssignmentCheckResult
890Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
891 // This check seems unnatural, however it is necessary to insure the proper
892 // conversion of functions/arrays. If the conversion were done for all
893 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
894 // expressions that surpress this implicit conversion (&, sizeof).
895 DefaultFunctionArrayConversion(rExpr);
896
897 return CheckAssignmentConstraints(lhsType, rExpr->getType());
898}
899
900Sema::AssignmentCheckResult
901Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
902 return CheckAssignmentConstraints(lhsType, rhsType);
903}
904
905inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
906 Diag(loc, diag::err_typecheck_invalid_operands,
907 lex->getType().getAsString(), rex->getType().getAsString(),
908 lex->getSourceRange(), rex->getSourceRange());
909}
910
911inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
912 Expr *&rex) {
913 QualType lhsType = lex->getType(), rhsType = rex->getType();
914
915 // make sure the vector types are identical.
916 if (lhsType == rhsType)
917 return lhsType;
918 // You cannot convert between vector values of different size.
919 Diag(loc, diag::err_typecheck_vector_not_convertable,
920 lex->getType().getAsString(), rex->getType().getAsString(),
921 lex->getSourceRange(), rex->getSourceRange());
922 return QualType();
923}
924
925inline QualType Sema::CheckMultiplyDivideOperands(
926 Expr *&lex, Expr *&rex, SourceLocation loc)
927{
928 QualType lhsType = lex->getType(), rhsType = rex->getType();
929
930 if (lhsType->isVectorType() || rhsType->isVectorType())
931 return CheckVectorOperands(loc, lex, rex);
932
933 UsualArithmeticConversions(lex, rex);
934
935 // handle the common case first (both operands are arithmetic).
936 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
937 return lex->getType();
938 InvalidOperands(loc, lex, rex);
939 return QualType();
940}
941
942inline QualType Sema::CheckRemainderOperands(
943 Expr *&lex, Expr *&rex, SourceLocation loc)
944{
945 QualType lhsType = lex->getType(), rhsType = rex->getType();
946
947 UsualArithmeticConversions(lex, rex);
948
949 // handle the common case first (both operands are arithmetic).
950 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
951 return lex->getType();
952 InvalidOperands(loc, lex, rex);
953 return QualType();
954}
955
956inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
957 Expr *&lex, Expr *&rex, SourceLocation loc)
958{
959 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
960 return CheckVectorOperands(loc, lex, rex);
961
962 UsualArithmeticConversions(lex, rex);
963
964 // handle the common case first (both operands are arithmetic).
965 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
966 return lex->getType();
967
968 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
969 return lex->getType();
970 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
971 return rex->getType();
972 InvalidOperands(loc, lex, rex);
973 return QualType();
974}
975
976inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
977 Expr *&lex, Expr *&rex, SourceLocation loc)
978{
979 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
980 return CheckVectorOperands(loc, lex, rex);
981
982 UsualArithmeticConversions(lex, rex);
983
984 // handle the common case first (both operands are arithmetic).
985 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
986 return lex->getType();
987
988 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
989 return lex->getType();
990 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
991 return Context.getPointerDiffType();
992 InvalidOperands(loc, lex, rex);
993 return QualType();
994}
995
996inline QualType Sema::CheckShiftOperands( // C99 6.5.7
997 Expr *&lex, Expr *&rex, SourceLocation loc)
998{
999 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1000 // for int << longlong -> the result type should be int, not long long.
1001 UsualArithmeticConversions(lex, rex);
1002
1003 // handle the common case first (both operands are arithmetic).
1004 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1005 return lex->getType();
1006 InvalidOperands(loc, lex, rex);
1007 return QualType();
1008}
1009
1010inline QualType Sema::CheckRelationalOperands( // C99 6.5.8
1011 Expr *&lex, Expr *&rex, SourceLocation loc)
1012{
1013 UsualUnaryConversions(lex);
1014 UsualUnaryConversions(rex);
1015 QualType lType = lex->getType();
1016 QualType rType = rex->getType();
1017
1018 if (lType->isRealType() && rType->isRealType())
1019 return Context.IntTy;
1020
1021 if (lType->isPointerType()) {
1022 if (rType->isPointerType())
1023 return Context.IntTy;
1024 if (rType->isIntegerType()) {
1025 if (!rex->isNullPointerConstant(Context))
1026 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1027 lex->getSourceRange(), rex->getSourceRange());
1028 return Context.IntTy; // the previous diagnostic is a GCC extension.
1029 }
1030 } else if (rType->isPointerType()) {
1031 if (lType->isIntegerType()) {
1032 if (!lex->isNullPointerConstant(Context))
1033 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1034 lex->getSourceRange(), rex->getSourceRange());
1035 return Context.IntTy; // the previous diagnostic is a GCC extension.
1036 }
1037 }
1038 InvalidOperands(loc, lex, rex);
1039 return QualType();
1040}
1041
1042inline QualType Sema::CheckEqualityOperands( // C99 6.5.9
1043 Expr *&lex, Expr *&rex, SourceLocation loc)
1044{
1045 UsualUnaryConversions(lex);
1046 UsualUnaryConversions(rex);
1047 QualType lType = lex->getType();
1048 QualType rType = rex->getType();
1049
1050 if (lType->isArithmeticType() && rType->isArithmeticType())
1051 return Context.IntTy;
1052
1053 if (lType->isPointerType()) {
1054 if (rType->isPointerType())
1055 return Context.IntTy;
1056 if (rType->isIntegerType()) {
1057 if (!rex->isNullPointerConstant(Context))
1058 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1059 lex->getSourceRange(), rex->getSourceRange());
1060 return Context.IntTy; // the previous diagnostic is a GCC extension.
1061 }
1062 } else if (rType->isPointerType()) {
1063 if (lType->isIntegerType()) {
1064 if (!lex->isNullPointerConstant(Context))
1065 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1066 lex->getSourceRange(), rex->getSourceRange());
1067 return Context.IntTy; // the previous diagnostic is a GCC extension.
1068 }
1069 }
1070 InvalidOperands(loc, lex, rex);
1071 return QualType();
1072}
1073
1074inline QualType Sema::CheckBitwiseOperands(
1075 Expr *&lex, Expr *&rex, SourceLocation loc)
1076{
1077 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1078 return CheckVectorOperands(loc, lex, rex);
1079
1080 UsualArithmeticConversions(lex, rex);
1081
1082 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1083 return lex->getType();
1084 InvalidOperands(loc, lex, rex);
1085 return QualType();
1086}
1087
1088inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1089 Expr *&lex, Expr *&rex, SourceLocation loc)
1090{
1091 UsualUnaryConversions(lex);
1092 UsualUnaryConversions(rex);
1093
1094 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1095 return Context.IntTy;
1096 InvalidOperands(loc, lex, rex);
1097 return QualType();
1098}
1099
1100inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
1101 Expr *lex, Expr *rex, SourceLocation loc, QualType compoundType)
1102{
1103 QualType lhsType = lex->getType();
1104 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1105 bool hadError = false;
1106 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1107
1108 switch (mlval) { // C99 6.5.16p2
1109 case Expr::MLV_Valid:
1110 break;
1111 case Expr::MLV_ConstQualified:
1112 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1113 hadError = true;
1114 break;
1115 case Expr::MLV_ArrayType:
1116 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1117 lhsType.getAsString(), lex->getSourceRange());
1118 return QualType();
1119 case Expr::MLV_NotObjectType:
1120 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1121 lhsType.getAsString(), lex->getSourceRange());
1122 return QualType();
1123 case Expr::MLV_InvalidExpression:
1124 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1125 lex->getSourceRange());
1126 return QualType();
1127 case Expr::MLV_IncompleteType:
1128 case Expr::MLV_IncompleteVoidType:
1129 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1130 lhsType.getAsString(), lex->getSourceRange());
1131 return QualType();
1132 }
1133 AssignmentCheckResult result;
1134
1135 if (compoundType.isNull())
1136 result = CheckSingleAssignmentConstraints(lhsType, rex);
1137 else
1138 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1139
1140 // decode the result (notice that extensions still return a type).
1141 switch (result) {
1142 case Compatible:
1143 break;
1144 case Incompatible:
1145 Diag(loc, diag::err_typecheck_assign_incompatible,
1146 lhsType.getAsString(), rhsType.getAsString(),
1147 lex->getSourceRange(), rex->getSourceRange());
1148 hadError = true;
1149 break;
1150 case PointerFromInt:
1151 // check for null pointer constant (C99 6.3.2.3p3)
1152 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1153 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1154 lhsType.getAsString(), rhsType.getAsString(),
1155 lex->getSourceRange(), rex->getSourceRange());
1156 }
1157 break;
1158 case IntFromPointer:
1159 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1160 lhsType.getAsString(), rhsType.getAsString(),
1161 lex->getSourceRange(), rex->getSourceRange());
1162 break;
1163 case IncompatiblePointer:
1164 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1165 lhsType.getAsString(), rhsType.getAsString(),
1166 lex->getSourceRange(), rex->getSourceRange());
1167 break;
1168 case CompatiblePointerDiscardsQualifiers:
1169 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1170 lhsType.getAsString(), rhsType.getAsString(),
1171 lex->getSourceRange(), rex->getSourceRange());
1172 break;
1173 }
1174 // C99 6.5.16p3: The type of an assignment expression is the type of the
1175 // left operand unless the left operand has qualified type, in which case
1176 // it is the unqualified version of the type of the left operand.
1177 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1178 // is converted to the type of the assignment expression (above).
1179 // C++ 5.17p1: the type of the assignment expression is that of its left oprdu.
1180 return hadError ? QualType() : lhsType.getUnqualifiedType();
1181}
1182
1183inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1184 Expr *&lex, Expr *&rex, SourceLocation loc) {
1185 UsualUnaryConversions(rex);
1186 return rex->getType();
1187}
1188
1189/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1190/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1191QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1192 QualType resType = op->getType();
1193 assert(!resType.isNull() && "no type for increment/decrement expression");
1194
1195 // C99 6.5.2.4p1
1196 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1197 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1198 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1199 resType.getAsString(), op->getSourceRange());
1200 return QualType();
1201 }
1202 } else if (!resType->isRealType()) {
1203 // FIXME: Allow Complex as a GCC extension.
1204 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1205 resType.getAsString(), op->getSourceRange());
1206 return QualType();
1207 }
1208 // At this point, we know we have a real or pointer type. Now make sure
1209 // the operand is a modifiable lvalue.
1210 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1211 if (mlval != Expr::MLV_Valid) {
1212 // FIXME: emit a more precise diagnostic...
1213 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1214 op->getSourceRange());
1215 return QualType();
1216 }
1217 return resType;
1218}
1219
1220/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1221/// This routine allows us to typecheck complex/recursive expressions
1222/// where the declaration is needed for type checking. Here are some
1223/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1224static Decl *getPrimaryDeclaration(Expr *e) {
1225 switch (e->getStmtClass()) {
1226 case Stmt::DeclRefExprClass:
1227 return cast<DeclRefExpr>(e)->getDecl();
1228 case Stmt::MemberExprClass:
1229 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1230 case Stmt::ArraySubscriptExprClass:
1231 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1232 case Stmt::CallExprClass:
1233 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1234 case Stmt::UnaryOperatorClass:
1235 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1236 case Stmt::ParenExprClass:
1237 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1238 default:
1239 return 0;
1240 }
1241}
1242
1243/// CheckAddressOfOperand - The operand of & must be either a function
1244/// designator or an lvalue designating an object. If it is an lvalue, the
1245/// object cannot be declared with storage class register or be a bit field.
1246/// Note: The usual conversions are *not* applied to the operand of the &
1247/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1248QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1249 Decl *dcl = getPrimaryDeclaration(op);
1250 Expr::isLvalueResult lval = op->isLvalue();
1251
1252 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1253 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1254 ;
1255 else { // FIXME: emit more specific diag...
1256 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1257 op->getSourceRange());
1258 return QualType();
1259 }
1260 } else if (dcl) {
1261 // We have an lvalue with a decl. Make sure the decl is not declared
1262 // with the register storage-class specifier.
1263 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1264 if (vd->getStorageClass() == VarDecl::Register) {
1265 Diag(OpLoc, diag::err_typecheck_address_of_register,
1266 op->getSourceRange());
1267 return QualType();
1268 }
1269 } else
1270 assert(0 && "Unknown/unexpected decl type");
1271
1272 // FIXME: add check for bitfields!
1273 }
1274 // If the operand has type "type", the result has type "pointer to type".
1275 return Context.getPointerType(op->getType());
1276}
1277
1278QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1279 UsualUnaryConversions(op);
1280 QualType qType = op->getType();
1281
1282 if (PointerType *PT = dyn_cast<PointerType>(qType.getCanonicalType())) {
1283 QualType ptype = PT->getPointeeType();
1284 // C99 6.5.3.2p4. "if it points to an object,...".
1285 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1286 // GCC compat: special case 'void *' (treat as warning).
1287 if (ptype->isVoidType()) {
1288 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1289 qType.getAsString(), op->getSourceRange());
1290 } else {
1291 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1292 ptype.getAsString(), op->getSourceRange());
1293 return QualType();
1294 }
1295 }
1296 return ptype;
1297 }
1298 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1299 qType.getAsString(), op->getSourceRange());
1300 return QualType();
1301}
1302
1303static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1304 tok::TokenKind Kind) {
1305 BinaryOperator::Opcode Opc;
1306 switch (Kind) {
1307 default: assert(0 && "Unknown binop!");
1308 case tok::star: Opc = BinaryOperator::Mul; break;
1309 case tok::slash: Opc = BinaryOperator::Div; break;
1310 case tok::percent: Opc = BinaryOperator::Rem; break;
1311 case tok::plus: Opc = BinaryOperator::Add; break;
1312 case tok::minus: Opc = BinaryOperator::Sub; break;
1313 case tok::lessless: Opc = BinaryOperator::Shl; break;
1314 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1315 case tok::lessequal: Opc = BinaryOperator::LE; break;
1316 case tok::less: Opc = BinaryOperator::LT; break;
1317 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1318 case tok::greater: Opc = BinaryOperator::GT; break;
1319 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1320 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1321 case tok::amp: Opc = BinaryOperator::And; break;
1322 case tok::caret: Opc = BinaryOperator::Xor; break;
1323 case tok::pipe: Opc = BinaryOperator::Or; break;
1324 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1325 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1326 case tok::equal: Opc = BinaryOperator::Assign; break;
1327 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1328 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1329 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1330 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1331 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1332 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1333 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1334 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1335 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1336 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1337 case tok::comma: Opc = BinaryOperator::Comma; break;
1338 }
1339 return Opc;
1340}
1341
1342static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1343 tok::TokenKind Kind) {
1344 UnaryOperator::Opcode Opc;
1345 switch (Kind) {
1346 default: assert(0 && "Unknown unary op!");
1347 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1348 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1349 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1350 case tok::star: Opc = UnaryOperator::Deref; break;
1351 case tok::plus: Opc = UnaryOperator::Plus; break;
1352 case tok::minus: Opc = UnaryOperator::Minus; break;
1353 case tok::tilde: Opc = UnaryOperator::Not; break;
1354 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1355 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1356 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1357 case tok::kw___real: Opc = UnaryOperator::Real; break;
1358 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1359 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1360 }
1361 return Opc;
1362}
1363
1364// Binary Operators. 'Tok' is the token for the operator.
1365Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1366 ExprTy *LHS, ExprTy *RHS) {
1367 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1368 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1369
1370 assert((lhs != 0) && "ParseBinOp(): missing left expression");
1371 assert((rhs != 0) && "ParseBinOp(): missing right expression");
1372
1373 QualType ResultTy; // Result type of the binary operator.
1374 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1375
1376 switch (Opc) {
1377 default:
1378 assert(0 && "Unknown binary expr!");
1379 case BinaryOperator::Assign:
1380 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1381 break;
1382 case BinaryOperator::Mul:
1383 case BinaryOperator::Div:
1384 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1385 break;
1386 case BinaryOperator::Rem:
1387 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1388 break;
1389 case BinaryOperator::Add:
1390 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1391 break;
1392 case BinaryOperator::Sub:
1393 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1394 break;
1395 case BinaryOperator::Shl:
1396 case BinaryOperator::Shr:
1397 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1398 break;
1399 case BinaryOperator::LE:
1400 case BinaryOperator::LT:
1401 case BinaryOperator::GE:
1402 case BinaryOperator::GT:
1403 ResultTy = CheckRelationalOperands(lhs, rhs, TokLoc);
1404 break;
1405 case BinaryOperator::EQ:
1406 case BinaryOperator::NE:
1407 ResultTy = CheckEqualityOperands(lhs, rhs, TokLoc);
1408 break;
1409 case BinaryOperator::And:
1410 case BinaryOperator::Xor:
1411 case BinaryOperator::Or:
1412 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1413 break;
1414 case BinaryOperator::LAnd:
1415 case BinaryOperator::LOr:
1416 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1417 break;
1418 case BinaryOperator::MulAssign:
1419 case BinaryOperator::DivAssign:
1420 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1421 if (!CompTy.isNull())
1422 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1423 break;
1424 case BinaryOperator::RemAssign:
1425 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1426 if (!CompTy.isNull())
1427 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1428 break;
1429 case BinaryOperator::AddAssign:
1430 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1431 if (!CompTy.isNull())
1432 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1433 break;
1434 case BinaryOperator::SubAssign:
1435 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1436 if (!CompTy.isNull())
1437 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1438 break;
1439 case BinaryOperator::ShlAssign:
1440 case BinaryOperator::ShrAssign:
1441 CompTy = CheckShiftOperands(lhs, rhs, TokLoc);
1442 if (!CompTy.isNull())
1443 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1444 break;
1445 case BinaryOperator::AndAssign:
1446 case BinaryOperator::XorAssign:
1447 case BinaryOperator::OrAssign:
1448 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1449 if (!CompTy.isNull())
1450 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1451 break;
1452 case BinaryOperator::Comma:
1453 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1454 break;
1455 }
1456 if (ResultTy.isNull())
1457 return true;
1458 if (CompTy.isNull())
1459 return new BinaryOperator(lhs, rhs, Opc, ResultTy);
1460 else
1461 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy);
1462}
1463
1464// Unary Operators. 'Tok' is the token for the operator.
1465Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1466 ExprTy *input) {
1467 Expr *Input = (Expr*)input;
1468 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1469 QualType resultType;
1470 switch (Opc) {
1471 default:
1472 assert(0 && "Unimplemented unary expr!");
1473 case UnaryOperator::PreInc:
1474 case UnaryOperator::PreDec:
1475 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1476 break;
1477 case UnaryOperator::AddrOf:
1478 resultType = CheckAddressOfOperand(Input, OpLoc);
1479 break;
1480 case UnaryOperator::Deref:
1481 resultType = CheckIndirectionOperand(Input, OpLoc);
1482 break;
1483 case UnaryOperator::Plus:
1484 case UnaryOperator::Minus:
1485 UsualUnaryConversions(Input);
1486 resultType = Input->getType();
1487 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1488 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1489 resultType.getAsString());
1490 break;
1491 case UnaryOperator::Not: // bitwise complement
1492 UsualUnaryConversions(Input);
1493 resultType = Input->getType();
1494 if (!resultType->isIntegerType()) // C99 6.5.3.3p1
1495 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1496 resultType.getAsString());
1497 break;
1498 case UnaryOperator::LNot: // logical negation
1499 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1500 DefaultFunctionArrayConversion(Input);
1501 resultType = Input->getType();
1502 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1503 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1504 resultType.getAsString());
1505 // LNot always has type int. C99 6.5.3.3p5.
1506 resultType = Context.IntTy;
1507 break;
1508 case UnaryOperator::SizeOf:
1509 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1510 break;
1511 case UnaryOperator::AlignOf:
1512 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1513 break;
1514 case UnaryOperator::Extension:
1515 // FIXME: does __extension__ cause any promotions? I would think not.
1516 resultType = Input->getType();
1517 break;
1518 }
1519 if (resultType.isNull())
1520 return true;
1521 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1522}
1523
1524/// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
1525Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
1526 SourceLocation LabLoc,
1527 IdentifierInfo *LabelII) {
1528 // Look up the record for this label identifier.
1529 LabelStmt *&LabelDecl = LabelMap[LabelII];
1530
1531 // If we haven't seen this label yet, create a forward reference.
1532 if (LabelDecl == 0)
1533 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1534
1535 // Create the AST node. The address of a label always has type 'void*'.
1536 return new AddrLabel(OpLoc, LabLoc, LabelDecl,
1537 Context.getPointerType(Context.VoidTy));
1538}
1539
1540Sema::ExprResult Sema::ParseStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
1541 SourceLocation RPLoc) { // "({..})"
1542 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1543 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1544 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1545
1546 // FIXME: there are a variety of strange constraints to enforce here, for
1547 // example, it is not possible to goto into a stmt expression apparently.
1548 // More semantic analysis is needed.
1549
1550 // FIXME: the last statement in the compount stmt has its value used. We
1551 // should not warn about it being unused.
1552
1553 // If there are sub stmts in the compound stmt, take the type of the last one
1554 // as the type of the stmtexpr.
1555 QualType Ty = Context.VoidTy;
1556
1557 if (!Compound->body_empty())
1558 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1559 Ty = LastExpr->getType();
1560
1561 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1562}