blob: b715556ce2ced1ad4aa9abc13a623b24663e3d26 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/Expr.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Lex/LiteralSupport.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/LangOptions.h"
23#include "clang/Basic/TargetInfo.h"
24#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000025#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026using namespace clang;
27
28/// ParseStringLiteral - The specified tokens were lexed as pasted string
29/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
30/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
31/// multiple tokens. However, the common case is that StringToks points to one
32/// string.
33///
34Action::ExprResult
35Sema::ParseStringLiteral(const Token *StringToks, unsigned NumStringToks) {
36 assert(NumStringToks && "Must have at least one string!");
37
38 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
39 if (Literal.hadError)
40 return ExprResult(true);
41
42 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
43 for (unsigned i = 0; i != NumStringToks; ++i)
44 StringTokLocs.push_back(StringToks[i].getLocation());
45
46 // FIXME: handle wchar_t
47 QualType t = Context.getPointerType(Context.CharTy);
48
49 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
50 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
51 Literal.AnyWide, t, StringToks[0].getLocation(),
52 StringToks[NumStringToks-1].getLocation());
53}
54
55
56/// ParseIdentifierExpr - The parser read an identifier in expression context,
57/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
58/// identifier is used in an function call context.
59Sema::ExprResult Sema::ParseIdentifierExpr(Scope *S, SourceLocation Loc,
60 IdentifierInfo &II,
61 bool HasTrailingLParen) {
62 // Could be enum-constant or decl.
63 Decl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
64 if (D == 0) {
65 // Otherwise, this could be an implicitly declared function reference (legal
66 // in C90, extension in C99).
67 if (HasTrailingLParen &&
68 // Not in C++.
69 !getLangOptions().CPlusPlus)
70 D = ImplicitlyDefineFunction(Loc, II, S);
71 else {
72 // If this name wasn't predeclared and if this is not a function call,
73 // diagnose the problem.
74 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
75 }
76 }
Chris Lattner4b009652007-07-25 00:24:17 +000077 if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
78 return new DeclRefExpr(VD, VD->getType(), Loc);
79 if (isa<TypedefDecl>(D))
80 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
81
82 assert(0 && "Invalid decl");
83 abort();
84}
85
86Sema::ExprResult Sema::ParsePreDefinedExpr(SourceLocation Loc,
87 tok::TokenKind Kind) {
88 PreDefinedExpr::IdentType IT;
89
90 switch (Kind) {
91 default:
92 assert(0 && "Unknown simple primary expr!");
93 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
94 IT = PreDefinedExpr::Func;
95 break;
96 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
97 IT = PreDefinedExpr::Function;
98 break;
99 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
100 IT = PreDefinedExpr::PrettyFunction;
101 break;
102 }
103
104 // Pre-defined identifiers are always of type char *.
105 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
106}
107
108Sema::ExprResult Sema::ParseCharacterConstant(const Token &Tok) {
109 llvm::SmallString<16> CharBuffer;
110 CharBuffer.resize(Tok.getLength());
111 const char *ThisTokBegin = &CharBuffer[0];
112 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
113
114 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
115 Tok.getLocation(), PP);
116 if (Literal.hadError())
117 return ExprResult(true);
118 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
119 Tok.getLocation());
120}
121
122Action::ExprResult Sema::ParseNumericConstant(const Token &Tok) {
123 // fast path for a single digit (which is quite common). A single digit
124 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
125 if (Tok.getLength() == 1) {
126 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
127
128 unsigned IntSize = Context.getTypeSize(Context.IntTy, Tok.getLocation());
129 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
130 Context.IntTy,
131 Tok.getLocation()));
132 }
133 llvm::SmallString<512> IntegerBuffer;
134 IntegerBuffer.resize(Tok.getLength());
135 const char *ThisTokBegin = &IntegerBuffer[0];
136
137 // Get the spelling of the token, which eliminates trigraphs, etc.
138 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
139 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
140 Tok.getLocation(), PP);
141 if (Literal.hadError)
142 return ExprResult(true);
143
Chris Lattner1de66eb2007-08-26 03:42:43 +0000144 Expr *Res;
145
146 if (Literal.isFloatingLiteral()) {
147 // FIXME: handle float values > 32 (including compute the real type...).
148 QualType Ty = Literal.isFloat ? Context.FloatTy : Context.DoubleTy;
149 Res = new FloatingLiteral(Literal.GetFloatValue(), Ty, Tok.getLocation());
150 } else if (!Literal.isIntegerLiteral()) {
151 return ExprResult(true);
152 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000153 QualType t;
154
155 // Get the value in the widest-possible width.
156 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
157
158 if (Literal.GetIntegerValue(ResultVal)) {
159 // If this value didn't fit into uintmax_t, warn and force to ull.
160 Diag(Tok.getLocation(), diag::warn_integer_too_large);
161 t = Context.UnsignedLongLongTy;
162 assert(Context.getTypeSize(t, Tok.getLocation()) ==
163 ResultVal.getBitWidth() && "long long is not intmax_t?");
164 } else {
165 // If this value fits into a ULL, try to figure out what else it fits into
166 // according to the rules of C99 6.4.4.1p5.
167
168 // Octal, Hexadecimal, and integers with a U suffix are allowed to
169 // be an unsigned int.
170 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
171
172 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000173 if (!Literal.isLong && !Literal.isLongLong) {
174 // Are int/unsigned possibilities?
Chris Lattner4b009652007-07-25 00:24:17 +0000175 unsigned IntSize = Context.getTypeSize(Context.IntTy,Tok.getLocation());
176 // Does it fit in a unsigned int?
177 if (ResultVal.isIntN(IntSize)) {
178 // Does it fit in a signed int?
179 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
180 t = Context.IntTy;
181 else if (AllowUnsigned)
182 t = Context.UnsignedIntTy;
183 }
184
185 if (!t.isNull())
186 ResultVal.trunc(IntSize);
187 }
188
189 // Are long/unsigned long possibilities?
190 if (t.isNull() && !Literal.isLongLong) {
191 unsigned LongSize = Context.getTypeSize(Context.LongTy,
192 Tok.getLocation());
193
194 // Does it fit in a unsigned long?
195 if (ResultVal.isIntN(LongSize)) {
196 // Does it fit in a signed long?
197 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
198 t = Context.LongTy;
199 else if (AllowUnsigned)
200 t = Context.UnsignedLongTy;
201 }
202 if (!t.isNull())
203 ResultVal.trunc(LongSize);
204 }
205
206 // Finally, check long long if needed.
207 if (t.isNull()) {
208 unsigned LongLongSize =
209 Context.getTypeSize(Context.LongLongTy, Tok.getLocation());
210
211 // Does it fit in a unsigned long long?
212 if (ResultVal.isIntN(LongLongSize)) {
213 // Does it fit in a signed long long?
214 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
215 t = Context.LongLongTy;
216 else if (AllowUnsigned)
217 t = Context.UnsignedLongLongTy;
218 }
219 }
220
221 // If we still couldn't decide a type, we probably have something that
222 // does not fit in a signed long long, but has no U suffix.
223 if (t.isNull()) {
224 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
225 t = Context.UnsignedLongLongTy;
226 }
227 }
228
Chris Lattner1de66eb2007-08-26 03:42:43 +0000229 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000230 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000231
232 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
233 if (Literal.isImaginary)
234 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
235
236 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000237}
238
239Action::ExprResult Sema::ParseParenExpr(SourceLocation L, SourceLocation R,
240 ExprTy *Val) {
241 Expr *e = (Expr *)Val;
242 assert((e != 0) && "ParseParenExpr() missing expr");
243 return new ParenExpr(L, R, e);
244}
245
246/// The UsualUnaryConversions() function is *not* called by this routine.
247/// See C99 6.3.2.1p[2-4] for more details.
248QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
249 SourceLocation OpLoc, bool isSizeof) {
250 // C99 6.5.3.4p1:
251 if (isa<FunctionType>(exprType) && isSizeof)
252 // alignof(function) is allowed.
253 Diag(OpLoc, diag::ext_sizeof_function_type);
254 else if (exprType->isVoidType())
255 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
256 else if (exprType->isIncompleteType()) {
257 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
258 diag::err_alignof_incomplete_type,
259 exprType.getAsString());
260 return QualType(); // error
261 }
262 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
263 return Context.getSizeType();
264}
265
266Action::ExprResult Sema::
267ParseSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
268 SourceLocation LPLoc, TypeTy *Ty,
269 SourceLocation RPLoc) {
270 // If error parsing type, ignore.
271 if (Ty == 0) return true;
272
273 // Verify that this is a valid expression.
274 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
275
276 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
277
278 if (resultType.isNull())
279 return true;
280 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
281}
282
Chris Lattner5110ad52007-08-24 21:41:10 +0000283QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000284 DefaultFunctionArrayConversion(V);
285
Chris Lattnera16e42d2007-08-26 05:39:26 +0000286 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000287 if (const ComplexType *CT = V->getType()->getAsComplexType())
288 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000289
290 // Otherwise they pass through real integer and floating point types here.
291 if (V->getType()->isArithmeticType())
292 return V->getType();
293
294 // Reject anything else.
295 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
296 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000297}
298
299
Chris Lattner4b009652007-07-25 00:24:17 +0000300
301Action::ExprResult Sema::ParsePostfixUnaryOp(SourceLocation OpLoc,
302 tok::TokenKind Kind,
303 ExprTy *Input) {
304 UnaryOperator::Opcode Opc;
305 switch (Kind) {
306 default: assert(0 && "Unknown unary op!");
307 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
308 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
309 }
310 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
311 if (result.isNull())
312 return true;
313 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
314}
315
316Action::ExprResult Sema::
317ParseArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
318 ExprTy *Idx, SourceLocation RLoc) {
319 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
320
321 // Perform default conversions.
322 DefaultFunctionArrayConversion(LHSExp);
323 DefaultFunctionArrayConversion(RHSExp);
324
325 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
326
327 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
328 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
329 // in the subscript position. As a result, we need to derive the array base
330 // and index from the expression types.
331 Expr *BaseExpr, *IndexExpr;
332 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000333 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000334 BaseExpr = LHSExp;
335 IndexExpr = RHSExp;
336 // FIXME: need to deal with const...
337 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000338 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000339 // Handle the uncommon case of "123[Ptr]".
340 BaseExpr = RHSExp;
341 IndexExpr = LHSExp;
342 // FIXME: need to deal with const...
343 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000344 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
345 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000346 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000347
348 // Component access limited to variables (reject vec4.rg[1]).
349 if (!isa<DeclRefExpr>(BaseExpr))
350 return Diag(LLoc, diag::err_ocuvector_component_access,
351 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000352 // FIXME: need to deal with const...
353 ResultType = VTy->getElementType();
354 } else {
355 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
356 RHSExp->getSourceRange());
357 }
358 // C99 6.5.2.1p1
359 if (!IndexExpr->getType()->isIntegerType())
360 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
361 IndexExpr->getSourceRange());
362
363 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
364 // the following check catches trying to index a pointer to a function (e.g.
365 // void (*)(int)). Functions are not objects in C99.
366 if (!ResultType->isObjectType())
367 return Diag(BaseExpr->getLocStart(),
368 diag::err_typecheck_subscript_not_object,
369 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
370
371 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
372}
373
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000374QualType Sema::
375CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
376 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000377 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000378
379 // The vector accessor can't exceed the number of elements.
380 const char *compStr = CompName.getName();
381 if (strlen(compStr) > vecType->getNumElements()) {
382 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
383 baseType.getAsString(), SourceRange(CompLoc));
384 return QualType();
385 }
386 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000387 if (vecType->getPointAccessorIdx(*compStr) != -1) {
388 do
389 compStr++;
390 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
391 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
392 do
393 compStr++;
394 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
395 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
396 do
397 compStr++;
398 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
399 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000400
401 if (*compStr) {
402 // We didn't get to the end of the string. This means the component names
403 // didn't come from the same set *or* we encountered an illegal name.
404 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
405 std::string(compStr,compStr+1), SourceRange(CompLoc));
406 return QualType();
407 }
408 // Each component accessor can't exceed the vector type.
409 compStr = CompName.getName();
410 while (*compStr) {
411 if (vecType->isAccessorWithinNumElements(*compStr))
412 compStr++;
413 else
414 break;
415 }
416 if (*compStr) {
417 // We didn't get to the end of the string. This means a component accessor
418 // exceeds the number of elements in the vector.
419 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
420 baseType.getAsString(), SourceRange(CompLoc));
421 return QualType();
422 }
423 // The component accessor looks fine - now we need to compute the actual type.
424 // The vector type is implied by the component accessor. For example,
425 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
426 unsigned CompSize = strlen(CompName.getName());
427 if (CompSize == 1)
428 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000429
430 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
431 // Now look up the TypeDefDecl from the vector type. Without this,
432 // diagostics look bad. We want OCU vector types to appear built-in.
433 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
434 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
435 return Context.getTypedefType(OCUVectorDecls[i]);
436 }
437 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000438}
439
Chris Lattner4b009652007-07-25 00:24:17 +0000440Action::ExprResult Sema::
441ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
442 tok::TokenKind OpKind, SourceLocation MemberLoc,
443 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000444 Expr *BaseExpr = static_cast<Expr *>(Base);
445 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000446
Steve Naroff2cb66382007-07-26 03:11:44 +0000447 QualType BaseType = BaseExpr->getType();
448 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000449
Chris Lattner4b009652007-07-25 00:24:17 +0000450 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000451 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000452 BaseType = PT->getPointeeType();
453 else
454 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
455 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000456 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000457 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000458 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000459 RecordDecl *RDecl = RTy->getDecl();
460 if (RTy->isIncompleteType())
461 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
462 BaseExpr->getSourceRange());
463 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000464 FieldDecl *MemberDecl = RDecl->getMember(&Member);
465 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000466 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
467 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000468 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
469 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000470 // Component access limited to variables (reject vec4.rg.g).
471 if (!isa<DeclRefExpr>(BaseExpr))
472 return Diag(OpLoc, diag::err_ocuvector_component_access,
473 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000474 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
475 if (ret.isNull())
476 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000477 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Steve Naroff2cb66382007-07-26 03:11:44 +0000478 } else
479 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
480 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000481}
482
483/// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
484/// This provides the location of the left/right parens and a list of comma
485/// locations.
486Action::ExprResult Sema::
487ParseCallExpr(ExprTy *fn, SourceLocation LParenLoc,
488 ExprTy **args, unsigned NumArgsInCall,
489 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
490 Expr *Fn = static_cast<Expr *>(fn);
491 Expr **Args = reinterpret_cast<Expr**>(args);
492 assert(Fn && "no function call expression");
493
494 UsualUnaryConversions(Fn);
495 QualType funcType = Fn->getType();
496
497 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
498 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000499 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000500 if (PT == 0)
501 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
502 SourceRange(Fn->getLocStart(), RParenLoc));
503
Chris Lattner71225142007-07-31 21:27:01 +0000504 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000505 if (funcT == 0)
506 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
507 SourceRange(Fn->getLocStart(), RParenLoc));
508
509 // If a prototype isn't declared, the parser implicitly defines a func decl
510 QualType resultType = funcT->getResultType();
511
512 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
513 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
514 // assignment, to the types of the corresponding parameter, ...
515
516 unsigned NumArgsInProto = proto->getNumArgs();
517 unsigned NumArgsToCheck = NumArgsInCall;
518
519 if (NumArgsInCall < NumArgsInProto)
520 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
521 Fn->getSourceRange());
522 else if (NumArgsInCall > NumArgsInProto) {
523 if (!proto->isVariadic()) {
524 Diag(Args[NumArgsInProto]->getLocStart(),
525 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
526 SourceRange(Args[NumArgsInProto]->getLocStart(),
527 Args[NumArgsInCall-1]->getLocEnd()));
528 }
529 NumArgsToCheck = NumArgsInProto;
530 }
531 // Continue to check argument types (even if we have too few/many args).
532 for (unsigned i = 0; i < NumArgsToCheck; i++) {
533 Expr *argExpr = Args[i];
534 assert(argExpr && "ParseCallExpr(): missing argument expression");
535
536 QualType lhsType = proto->getArgType(i);
537 QualType rhsType = argExpr->getType();
538
Steve Naroff75644062007-07-25 20:45:33 +0000539 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000540 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000541 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000542 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000543 lhsType = Context.getPointerType(lhsType);
544
545 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
546 argExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000547 if (Args[i] != argExpr) // The expression was converted.
548 Args[i] = argExpr; // Make sure we store the converted expression.
Chris Lattner4b009652007-07-25 00:24:17 +0000549 SourceLocation l = argExpr->getLocStart();
550
551 // decode the result (notice that AST's are still created for extensions).
552 switch (result) {
553 case Compatible:
554 break;
555 case PointerFromInt:
556 // check for null pointer constant (C99 6.3.2.3p3)
557 if (!argExpr->isNullPointerConstant(Context)) {
558 Diag(l, diag::ext_typecheck_passing_pointer_int,
559 lhsType.getAsString(), rhsType.getAsString(),
560 Fn->getSourceRange(), argExpr->getSourceRange());
561 }
562 break;
563 case IntFromPointer:
564 Diag(l, diag::ext_typecheck_passing_pointer_int,
565 lhsType.getAsString(), rhsType.getAsString(),
566 Fn->getSourceRange(), argExpr->getSourceRange());
567 break;
568 case IncompatiblePointer:
569 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
570 rhsType.getAsString(), lhsType.getAsString(),
571 Fn->getSourceRange(), argExpr->getSourceRange());
572 break;
573 case CompatiblePointerDiscardsQualifiers:
574 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
575 rhsType.getAsString(), lhsType.getAsString(),
576 Fn->getSourceRange(), argExpr->getSourceRange());
577 break;
578 case Incompatible:
579 return Diag(l, diag::err_typecheck_passing_incompatible,
580 rhsType.getAsString(), lhsType.getAsString(),
581 Fn->getSourceRange(), argExpr->getSourceRange());
582 }
583 }
584 // Even if the types checked, bail if we had the wrong number of arguments.
585 if (NumArgsInCall != NumArgsInProto && !proto->isVariadic())
586 return true;
587 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000588
589 // Do special checking on direct calls to functions.
590 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
591 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
592 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000593 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args, NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000594 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000595
Chris Lattner4b009652007-07-25 00:24:17 +0000596 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
597}
598
599Action::ExprResult Sema::
600ParseCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
601 SourceLocation RParenLoc, ExprTy *InitExpr) {
602 assert((Ty != 0) && "ParseCompoundLiteral(): missing type");
603 QualType literalType = QualType::getFromOpaquePtr(Ty);
604 // FIXME: put back this assert when initializers are worked out.
605 //assert((InitExpr != 0) && "ParseCompoundLiteral(): missing expression");
606 Expr *literalExpr = static_cast<Expr*>(InitExpr);
607
608 // FIXME: add semantic analysis (C99 6.5.2.5).
609 return new CompoundLiteralExpr(literalType, literalExpr);
610}
611
612Action::ExprResult Sema::
613ParseInitList(SourceLocation LParenLoc, ExprTy **InitList, unsigned NumInit,
614 SourceLocation RParenLoc) {
615 // FIXME: add semantic analysis (C99 6.7.8). This involves
616 // knowledge of the object being intialized. As a result, the code for
617 // doing the semantic analysis will likely be located elsewhere (i.e. in
618 // consumers of InitListExpr (e.g. ParseDeclarator, ParseCompoundLiteral).
619 return false; // FIXME instantiate an InitListExpr.
620}
621
622Action::ExprResult Sema::
623ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
624 SourceLocation RParenLoc, ExprTy *Op) {
625 assert((Ty != 0) && (Op != 0) && "ParseCastExpr(): missing type or expr");
626
627 Expr *castExpr = static_cast<Expr*>(Op);
628 QualType castType = QualType::getFromOpaquePtr(Ty);
629
630 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
631 // type needs to be scalar.
632 if (!castType->isScalarType() && !castType->isVoidType()) {
633 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
634 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
635 }
636 if (!castExpr->getType()->isScalarType()) {
637 return Diag(castExpr->getLocStart(),
638 diag::err_typecheck_expect_scalar_operand,
639 castExpr->getType().getAsString(), castExpr->getSourceRange());
640 }
641 return new CastExpr(castType, castExpr, LParenLoc);
642}
643
644inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
645 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
646 UsualUnaryConversions(cond);
647 UsualUnaryConversions(lex);
648 UsualUnaryConversions(rex);
649 QualType condT = cond->getType();
650 QualType lexT = lex->getType();
651 QualType rexT = rex->getType();
652
653 // first, check the condition.
654 if (!condT->isScalarType()) { // C99 6.5.15p2
655 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
656 condT.getAsString());
657 return QualType();
658 }
659 // now check the two expressions.
660 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
661 UsualArithmeticConversions(lex, rex);
662 return lex->getType();
663 }
Chris Lattner71225142007-07-31 21:27:01 +0000664 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
665 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
666
667 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
668 return lexT;
669
Chris Lattner4b009652007-07-25 00:24:17 +0000670 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
671 lexT.getAsString(), rexT.getAsString(),
672 lex->getSourceRange(), rex->getSourceRange());
673 return QualType();
674 }
675 }
676 // C99 6.5.15p3
677 if (lexT->isPointerType() && rex->isNullPointerConstant(Context))
678 return lexT;
679 if (rexT->isPointerType() && lex->isNullPointerConstant(Context))
680 return rexT;
681
Chris Lattner71225142007-07-31 21:27:01 +0000682 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
683 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
684 // get the "pointed to" types
685 QualType lhptee = LHSPT->getPointeeType();
686 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000687
Chris Lattner71225142007-07-31 21:27:01 +0000688 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
689 if (lhptee->isVoidType() &&
690 (rhptee->isObjectType() || rhptee->isIncompleteType()))
691 return lexT;
692 if (rhptee->isVoidType() &&
693 (lhptee->isObjectType() || lhptee->isIncompleteType()))
694 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000695
Chris Lattner71225142007-07-31 21:27:01 +0000696 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
697 rhptee.getUnqualifiedType())) {
698 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
699 lexT.getAsString(), rexT.getAsString(),
700 lex->getSourceRange(), rex->getSourceRange());
701 return lexT; // FIXME: this is an _ext - is this return o.k?
702 }
703 // The pointer types are compatible.
704 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
705 // differently qualified versions of compatible types, the result type is a
706 // pointer to an appropriately qualified version of the *composite* type.
707 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000708 }
Chris Lattner4b009652007-07-25 00:24:17 +0000709 }
Chris Lattner71225142007-07-31 21:27:01 +0000710
Chris Lattner4b009652007-07-25 00:24:17 +0000711 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
712 return lexT;
713
714 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
715 lexT.getAsString(), rexT.getAsString(),
716 lex->getSourceRange(), rex->getSourceRange());
717 return QualType();
718}
719
720/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
721/// in the case of a the GNU conditional expr extension.
722Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
723 SourceLocation ColonLoc,
724 ExprTy *Cond, ExprTy *LHS,
725 ExprTy *RHS) {
726 Expr *CondExpr = (Expr *) Cond;
727 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
728 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
729 RHSExpr, QuestionLoc);
730 if (result.isNull())
731 return true;
732 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
733}
734
735// promoteExprToType - a helper function to ensure we create exactly one
736// ImplicitCastExpr. As a convenience (to the caller), we return the type.
737static void promoteExprToType(Expr *&expr, QualType type) {
738 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
739 impCast->setType(type);
740 else
741 expr = new ImplicitCastExpr(type, expr);
742 return;
743}
744
745/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
746void Sema::DefaultFunctionArrayConversion(Expr *&e) {
747 QualType t = e->getType();
748 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
749
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000750 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000751 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
752 t = e->getType();
753 }
754 if (t->isFunctionType())
755 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000756 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000757 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
758}
759
760/// UsualUnaryConversion - Performs various conversions that are common to most
761/// operators (C99 6.3). The conversions of array and function types are
762/// sometimes surpressed. For example, the array->pointer conversion doesn't
763/// apply if the array is an argument to the sizeof or address (&) operators.
764/// In these instances, this routine should *not* be called.
765void Sema::UsualUnaryConversions(Expr *&expr) {
766 QualType t = expr->getType();
767 assert(!t.isNull() && "UsualUnaryConversions - missing type");
768
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000769 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000770 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
771 t = expr->getType();
772 }
773 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
774 promoteExprToType(expr, Context.IntTy);
775 else
776 DefaultFunctionArrayConversion(expr);
777}
778
779/// UsualArithmeticConversions - Performs various conversions that are common to
780/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
781/// routine returns the first non-arithmetic type found. The client is
782/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000783QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
784 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000785 if (!isCompAssign) {
786 UsualUnaryConversions(lhsExpr);
787 UsualUnaryConversions(rhsExpr);
788 }
Chris Lattner4b009652007-07-25 00:24:17 +0000789 QualType lhs = lhsExpr->getType();
790 QualType rhs = rhsExpr->getType();
791
792 // If both types are identical, no conversion is needed.
793 if (lhs == rhs)
Steve Naroff8f708362007-08-24 19:07:16 +0000794 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000795
796 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
797 // The caller can deal with this (e.g. pointer + int).
798 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000799 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000800
801 // At this point, we have two different arithmetic types.
802
803 // Handle complex types first (C99 6.3.1.8p1).
804 if (lhs->isComplexType() || rhs->isComplexType()) {
805 // if we have an integer operand, the result is the complex type.
806 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000807 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
808 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000809 }
810 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000811 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
812 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000813 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000814 // This handles complex/complex, complex/float, or float/complex.
815 // When both operands are complex, the shorter operand is converted to the
816 // type of the longer, and that is the type of the result. This corresponds
817 // to what is done when combining two real floating-point operands.
818 // The fun begins when size promotion occur across type domains.
819 // From H&S 6.3.4: When one operand is complex and the other is a real
820 // floating-point type, the less precise type is converted, within it's
821 // real or complex domain, to the precision of the other type. For example,
822 // when combining a "long double" with a "double _Complex", the
823 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000824 int result = Context.compareFloatingType(lhs, rhs);
825
826 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000827 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
828 if (!isCompAssign)
829 promoteExprToType(rhsExpr, rhs);
830 } else if (result < 0) { // The right side is bigger, convert lhs.
831 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
832 if (!isCompAssign)
833 promoteExprToType(lhsExpr, lhs);
834 }
835 // At this point, lhs and rhs have the same rank/size. Now, make sure the
836 // domains match. This is a requirement for our implementation, C99
837 // does not require this promotion.
838 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
839 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000840 if (!isCompAssign)
841 promoteExprToType(lhsExpr, rhs);
842 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000843 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000844 if (!isCompAssign)
845 promoteExprToType(rhsExpr, lhs);
846 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000847 }
Chris Lattner4b009652007-07-25 00:24:17 +0000848 }
Steve Naroff3b6157f2007-08-27 21:43:43 +0000849 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +0000850 }
851 // Now handle "real" floating types (i.e. float, double, long double).
852 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
853 // if we have an integer operand, the result is the real floating type.
854 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000855 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
856 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000857 }
858 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000859 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
860 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000861 }
862 // We have two real floating types, float/complex combos were handled above.
863 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +0000864 int result = Context.compareFloatingType(lhs, rhs);
865
866 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000867 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
868 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000869 }
Steve Naroff45fc9822007-08-27 15:30:22 +0000870 if (result < 0) { // convert the lhs
871 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
872 return rhs;
873 }
874 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +0000875 }
876 // Finally, we have two differing integer types.
877 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000878 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
879 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000880 }
Steve Naroff8f708362007-08-24 19:07:16 +0000881 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
882 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000883}
884
885// CheckPointerTypesForAssignment - This is a very tricky routine (despite
886// being closely modeled after the C99 spec:-). The odd characteristic of this
887// routine is it effectively iqnores the qualifiers on the top level pointee.
888// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
889// FIXME: add a couple examples in this comment.
890Sema::AssignmentCheckResult
891Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
892 QualType lhptee, rhptee;
893
894 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +0000895 lhptee = lhsType->getAsPointerType()->getPointeeType();
896 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000897
898 // make sure we operate on the canonical type
899 lhptee = lhptee.getCanonicalType();
900 rhptee = rhptee.getCanonicalType();
901
902 AssignmentCheckResult r = Compatible;
903
904 // C99 6.5.16.1p1: This following citation is common to constraints
905 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
906 // qualifiers of the type *pointed to* by the right;
907 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
908 rhptee.getQualifiers())
909 r = CompatiblePointerDiscardsQualifiers;
910
911 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
912 // incomplete type and the other is a pointer to a qualified or unqualified
913 // version of void...
914 if (lhptee.getUnqualifiedType()->isVoidType() &&
915 (rhptee->isObjectType() || rhptee->isIncompleteType()))
916 ;
917 else if (rhptee.getUnqualifiedType()->isVoidType() &&
918 (lhptee->isObjectType() || lhptee->isIncompleteType()))
919 ;
920 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
921 // unqualified versions of compatible types, ...
922 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
923 rhptee.getUnqualifiedType()))
924 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
925 return r;
926}
927
928/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
929/// has code to accommodate several GCC extensions when type checking
930/// pointers. Here are some objectionable examples that GCC considers warnings:
931///
932/// int a, *pint;
933/// short *pshort;
934/// struct foo *pfoo;
935///
936/// pint = pshort; // warning: assignment from incompatible pointer type
937/// a = pint; // warning: assignment makes integer from pointer without a cast
938/// pint = a; // warning: assignment makes pointer from integer without a cast
939/// pint = pfoo; // warning: assignment from incompatible pointer type
940///
941/// As a result, the code for dealing with pointers is more complex than the
942/// C99 spec dictates.
943/// Note: the warning above turn into errors when -pedantic-errors is enabled.
944///
945Sema::AssignmentCheckResult
946Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
947 if (lhsType == rhsType) // common case, fast path...
948 return Compatible;
949
950 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
951 if (lhsType->isVectorType() || rhsType->isVectorType()) {
952 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
953 return Incompatible;
954 }
955 return Compatible;
956 } else if (lhsType->isPointerType()) {
957 if (rhsType->isIntegerType())
958 return PointerFromInt;
959
960 if (rhsType->isPointerType())
961 return CheckPointerTypesForAssignment(lhsType, rhsType);
962 } else if (rhsType->isPointerType()) {
963 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
964 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
965 return IntFromPointer;
966
967 if (lhsType->isPointerType())
968 return CheckPointerTypesForAssignment(lhsType, rhsType);
969 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
970 if (Type::tagTypesAreCompatible(lhsType, rhsType))
971 return Compatible;
972 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
973 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
974 return Compatible;
975 }
976 return Incompatible;
977}
978
979Sema::AssignmentCheckResult
980Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
981 // This check seems unnatural, however it is necessary to insure the proper
982 // conversion of functions/arrays. If the conversion were done for all
983 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
984 // expressions that surpress this implicit conversion (&, sizeof).
985 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000986
987 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +0000988
Steve Naroff0f32f432007-08-24 22:33:52 +0000989 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
990
991 // C99 6.5.16.1p2: The value of the right operand is converted to the
992 // type of the assignment expression.
993 if (rExpr->getType() != lhsType)
994 promoteExprToType(rExpr, lhsType);
995 return result;
Chris Lattner4b009652007-07-25 00:24:17 +0000996}
997
998Sema::AssignmentCheckResult
999Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1000 return CheckAssignmentConstraints(lhsType, rhsType);
1001}
1002
1003inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1004 Diag(loc, diag::err_typecheck_invalid_operands,
1005 lex->getType().getAsString(), rex->getType().getAsString(),
1006 lex->getSourceRange(), rex->getSourceRange());
1007}
1008
1009inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1010 Expr *&rex) {
1011 QualType lhsType = lex->getType(), rhsType = rex->getType();
1012
1013 // make sure the vector types are identical.
1014 if (lhsType == rhsType)
1015 return lhsType;
1016 // You cannot convert between vector values of different size.
1017 Diag(loc, diag::err_typecheck_vector_not_convertable,
1018 lex->getType().getAsString(), rex->getType().getAsString(),
1019 lex->getSourceRange(), rex->getSourceRange());
1020 return QualType();
1021}
1022
1023inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001024 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001025{
1026 QualType lhsType = lex->getType(), rhsType = rex->getType();
1027
1028 if (lhsType->isVectorType() || rhsType->isVectorType())
1029 return CheckVectorOperands(loc, lex, rex);
1030
Steve Naroff8f708362007-08-24 19:07:16 +00001031 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001032
Chris Lattner4b009652007-07-25 00:24:17 +00001033 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001034 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001035 InvalidOperands(loc, lex, rex);
1036 return QualType();
1037}
1038
1039inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001040 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001041{
1042 QualType lhsType = lex->getType(), rhsType = rex->getType();
1043
Steve Naroff8f708362007-08-24 19:07:16 +00001044 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001045
Chris Lattner4b009652007-07-25 00:24:17 +00001046 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001047 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001048 InvalidOperands(loc, lex, rex);
1049 return QualType();
1050}
1051
1052inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001053 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001054{
1055 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1056 return CheckVectorOperands(loc, lex, rex);
1057
Steve Naroff8f708362007-08-24 19:07:16 +00001058 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001059
1060 // handle the common case first (both operands are arithmetic).
1061 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001062 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001063
1064 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1065 return lex->getType();
1066 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1067 return rex->getType();
1068 InvalidOperands(loc, lex, rex);
1069 return QualType();
1070}
1071
1072inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001073 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001074{
1075 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1076 return CheckVectorOperands(loc, lex, rex);
1077
Steve Naroff8f708362007-08-24 19:07:16 +00001078 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001079
1080 // handle the common case first (both operands are arithmetic).
1081 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001082 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001083
1084 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001085 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001086 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1087 return Context.getPointerDiffType();
1088 InvalidOperands(loc, lex, rex);
1089 return QualType();
1090}
1091
1092inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001093 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001094{
1095 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1096 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001097 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001098
1099 // handle the common case first (both operands are arithmetic).
1100 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001101 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001102 InvalidOperands(loc, lex, rex);
1103 return QualType();
1104}
1105
Chris Lattner254f3bc2007-08-26 01:18:55 +00001106inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1107 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001108{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001109 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001110 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1111 UsualArithmeticConversions(lex, rex);
1112 else {
1113 UsualUnaryConversions(lex);
1114 UsualUnaryConversions(rex);
1115 }
Chris Lattner4b009652007-07-25 00:24:17 +00001116 QualType lType = lex->getType();
1117 QualType rType = rex->getType();
1118
Chris Lattner254f3bc2007-08-26 01:18:55 +00001119 if (isRelational) {
1120 if (lType->isRealType() && rType->isRealType())
1121 return Context.IntTy;
1122 } else {
1123 if (lType->isArithmeticType() && rType->isArithmeticType())
1124 return Context.IntTy;
1125 }
Chris Lattner4b009652007-07-25 00:24:17 +00001126
Chris Lattner22be8422007-08-26 01:10:14 +00001127 bool LHSIsNull = lex->isNullPointerConstant(Context);
1128 bool RHSIsNull = rex->isNullPointerConstant(Context);
1129
Chris Lattner254f3bc2007-08-26 01:18:55 +00001130 // All of the following pointer related warnings are GCC extensions, except
1131 // when handling null pointer constants. One day, we can consider making them
1132 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001133 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner22be8422007-08-26 01:10:14 +00001134 if (!LHSIsNull && !RHSIsNull &&
Steve Naroffc33c0602007-08-27 04:08:11 +00001135 !Type::pointerTypesAreCompatible(lType.getUnqualifiedType(),
1136 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001137 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1138 lType.getAsString(), rType.getAsString(),
1139 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001140 }
Chris Lattner22be8422007-08-26 01:10:14 +00001141 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001142 return Context.IntTy;
1143 }
1144 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001145 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001146 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1147 lType.getAsString(), rType.getAsString(),
1148 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001149 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001150 return Context.IntTy;
1151 }
1152 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001153 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001154 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1155 lType.getAsString(), rType.getAsString(),
1156 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001157 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001158 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001159 }
1160 InvalidOperands(loc, lex, rex);
1161 return QualType();
1162}
1163
Chris Lattner4b009652007-07-25 00:24:17 +00001164inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001165 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001166{
1167 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1168 return CheckVectorOperands(loc, lex, rex);
1169
Steve Naroff8f708362007-08-24 19:07:16 +00001170 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001171
1172 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001173 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001174 InvalidOperands(loc, lex, rex);
1175 return QualType();
1176}
1177
1178inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1179 Expr *&lex, Expr *&rex, SourceLocation loc)
1180{
1181 UsualUnaryConversions(lex);
1182 UsualUnaryConversions(rex);
1183
1184 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1185 return Context.IntTy;
1186 InvalidOperands(loc, lex, rex);
1187 return QualType();
1188}
1189
1190inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001191 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001192{
1193 QualType lhsType = lex->getType();
1194 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1195 bool hadError = false;
1196 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1197
1198 switch (mlval) { // C99 6.5.16p2
1199 case Expr::MLV_Valid:
1200 break;
1201 case Expr::MLV_ConstQualified:
1202 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1203 hadError = true;
1204 break;
1205 case Expr::MLV_ArrayType:
1206 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1207 lhsType.getAsString(), lex->getSourceRange());
1208 return QualType();
1209 case Expr::MLV_NotObjectType:
1210 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1211 lhsType.getAsString(), lex->getSourceRange());
1212 return QualType();
1213 case Expr::MLV_InvalidExpression:
1214 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1215 lex->getSourceRange());
1216 return QualType();
1217 case Expr::MLV_IncompleteType:
1218 case Expr::MLV_IncompleteVoidType:
1219 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1220 lhsType.getAsString(), lex->getSourceRange());
1221 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001222 case Expr::MLV_DuplicateVectorComponents:
1223 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1224 lex->getSourceRange());
1225 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001226 }
1227 AssignmentCheckResult result;
1228
1229 if (compoundType.isNull())
1230 result = CheckSingleAssignmentConstraints(lhsType, rex);
1231 else
1232 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001233
Chris Lattner4b009652007-07-25 00:24:17 +00001234 // decode the result (notice that extensions still return a type).
1235 switch (result) {
1236 case Compatible:
1237 break;
1238 case Incompatible:
1239 Diag(loc, diag::err_typecheck_assign_incompatible,
1240 lhsType.getAsString(), rhsType.getAsString(),
1241 lex->getSourceRange(), rex->getSourceRange());
1242 hadError = true;
1243 break;
1244 case PointerFromInt:
1245 // check for null pointer constant (C99 6.3.2.3p3)
1246 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1247 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1248 lhsType.getAsString(), rhsType.getAsString(),
1249 lex->getSourceRange(), rex->getSourceRange());
1250 }
1251 break;
1252 case IntFromPointer:
1253 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1254 lhsType.getAsString(), rhsType.getAsString(),
1255 lex->getSourceRange(), rex->getSourceRange());
1256 break;
1257 case IncompatiblePointer:
1258 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1259 lhsType.getAsString(), rhsType.getAsString(),
1260 lex->getSourceRange(), rex->getSourceRange());
1261 break;
1262 case CompatiblePointerDiscardsQualifiers:
1263 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1264 lhsType.getAsString(), rhsType.getAsString(),
1265 lex->getSourceRange(), rex->getSourceRange());
1266 break;
1267 }
1268 // C99 6.5.16p3: The type of an assignment expression is the type of the
1269 // left operand unless the left operand has qualified type, in which case
1270 // it is the unqualified version of the type of the left operand.
1271 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1272 // is converted to the type of the assignment expression (above).
1273 // C++ 5.17p1: the type of the assignment expression is that of its left oprdu.
1274 return hadError ? QualType() : lhsType.getUnqualifiedType();
1275}
1276
1277inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1278 Expr *&lex, Expr *&rex, SourceLocation loc) {
1279 UsualUnaryConversions(rex);
1280 return rex->getType();
1281}
1282
1283/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1284/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1285QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1286 QualType resType = op->getType();
1287 assert(!resType.isNull() && "no type for increment/decrement expression");
1288
Steve Naroffd30e1932007-08-24 17:20:07 +00001289 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattner4b009652007-07-25 00:24:17 +00001290 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1291 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1292 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1293 resType.getAsString(), op->getSourceRange());
1294 return QualType();
1295 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001296 } else if (!resType->isRealType()) {
1297 if (resType->isComplexType())
1298 // C99 does not support ++/-- on complex types.
1299 Diag(OpLoc, diag::ext_integer_increment_complex,
1300 resType.getAsString(), op->getSourceRange());
1301 else {
1302 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1303 resType.getAsString(), op->getSourceRange());
1304 return QualType();
1305 }
Chris Lattner4b009652007-07-25 00:24:17 +00001306 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001307 // At this point, we know we have a real, complex or pointer type.
1308 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001309 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1310 if (mlval != Expr::MLV_Valid) {
1311 // FIXME: emit a more precise diagnostic...
1312 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1313 op->getSourceRange());
1314 return QualType();
1315 }
1316 return resType;
1317}
1318
1319/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1320/// This routine allows us to typecheck complex/recursive expressions
1321/// where the declaration is needed for type checking. Here are some
1322/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1323static Decl *getPrimaryDeclaration(Expr *e) {
1324 switch (e->getStmtClass()) {
1325 case Stmt::DeclRefExprClass:
1326 return cast<DeclRefExpr>(e)->getDecl();
1327 case Stmt::MemberExprClass:
1328 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1329 case Stmt::ArraySubscriptExprClass:
1330 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1331 case Stmt::CallExprClass:
1332 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1333 case Stmt::UnaryOperatorClass:
1334 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1335 case Stmt::ParenExprClass:
1336 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1337 default:
1338 return 0;
1339 }
1340}
1341
1342/// CheckAddressOfOperand - The operand of & must be either a function
1343/// designator or an lvalue designating an object. If it is an lvalue, the
1344/// object cannot be declared with storage class register or be a bit field.
1345/// Note: The usual conversions are *not* applied to the operand of the &
1346/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1347QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1348 Decl *dcl = getPrimaryDeclaration(op);
1349 Expr::isLvalueResult lval = op->isLvalue();
1350
1351 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1352 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1353 ;
1354 else { // FIXME: emit more specific diag...
1355 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1356 op->getSourceRange());
1357 return QualType();
1358 }
1359 } else if (dcl) {
1360 // We have an lvalue with a decl. Make sure the decl is not declared
1361 // with the register storage-class specifier.
1362 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1363 if (vd->getStorageClass() == VarDecl::Register) {
1364 Diag(OpLoc, diag::err_typecheck_address_of_register,
1365 op->getSourceRange());
1366 return QualType();
1367 }
1368 } else
1369 assert(0 && "Unknown/unexpected decl type");
1370
1371 // FIXME: add check for bitfields!
1372 }
1373 // If the operand has type "type", the result has type "pointer to type".
1374 return Context.getPointerType(op->getType());
1375}
1376
1377QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1378 UsualUnaryConversions(op);
1379 QualType qType = op->getType();
1380
Chris Lattner7931f4a2007-07-31 16:53:04 +00001381 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001382 QualType ptype = PT->getPointeeType();
1383 // C99 6.5.3.2p4. "if it points to an object,...".
1384 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1385 // GCC compat: special case 'void *' (treat as warning).
1386 if (ptype->isVoidType()) {
1387 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1388 qType.getAsString(), op->getSourceRange());
1389 } else {
1390 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1391 ptype.getAsString(), op->getSourceRange());
1392 return QualType();
1393 }
1394 }
1395 return ptype;
1396 }
1397 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1398 qType.getAsString(), op->getSourceRange());
1399 return QualType();
1400}
1401
1402static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1403 tok::TokenKind Kind) {
1404 BinaryOperator::Opcode Opc;
1405 switch (Kind) {
1406 default: assert(0 && "Unknown binop!");
1407 case tok::star: Opc = BinaryOperator::Mul; break;
1408 case tok::slash: Opc = BinaryOperator::Div; break;
1409 case tok::percent: Opc = BinaryOperator::Rem; break;
1410 case tok::plus: Opc = BinaryOperator::Add; break;
1411 case tok::minus: Opc = BinaryOperator::Sub; break;
1412 case tok::lessless: Opc = BinaryOperator::Shl; break;
1413 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1414 case tok::lessequal: Opc = BinaryOperator::LE; break;
1415 case tok::less: Opc = BinaryOperator::LT; break;
1416 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1417 case tok::greater: Opc = BinaryOperator::GT; break;
1418 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1419 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1420 case tok::amp: Opc = BinaryOperator::And; break;
1421 case tok::caret: Opc = BinaryOperator::Xor; break;
1422 case tok::pipe: Opc = BinaryOperator::Or; break;
1423 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1424 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1425 case tok::equal: Opc = BinaryOperator::Assign; break;
1426 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1427 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1428 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1429 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1430 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1431 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1432 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1433 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1434 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1435 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1436 case tok::comma: Opc = BinaryOperator::Comma; break;
1437 }
1438 return Opc;
1439}
1440
1441static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1442 tok::TokenKind Kind) {
1443 UnaryOperator::Opcode Opc;
1444 switch (Kind) {
1445 default: assert(0 && "Unknown unary op!");
1446 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1447 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1448 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1449 case tok::star: Opc = UnaryOperator::Deref; break;
1450 case tok::plus: Opc = UnaryOperator::Plus; break;
1451 case tok::minus: Opc = UnaryOperator::Minus; break;
1452 case tok::tilde: Opc = UnaryOperator::Not; break;
1453 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1454 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1455 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1456 case tok::kw___real: Opc = UnaryOperator::Real; break;
1457 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1458 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1459 }
1460 return Opc;
1461}
1462
1463// Binary Operators. 'Tok' is the token for the operator.
1464Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1465 ExprTy *LHS, ExprTy *RHS) {
1466 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1467 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1468
1469 assert((lhs != 0) && "ParseBinOp(): missing left expression");
1470 assert((rhs != 0) && "ParseBinOp(): missing right expression");
1471
1472 QualType ResultTy; // Result type of the binary operator.
1473 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1474
1475 switch (Opc) {
1476 default:
1477 assert(0 && "Unknown binary expr!");
1478 case BinaryOperator::Assign:
1479 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1480 break;
1481 case BinaryOperator::Mul:
1482 case BinaryOperator::Div:
1483 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1484 break;
1485 case BinaryOperator::Rem:
1486 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1487 break;
1488 case BinaryOperator::Add:
1489 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1490 break;
1491 case BinaryOperator::Sub:
1492 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1493 break;
1494 case BinaryOperator::Shl:
1495 case BinaryOperator::Shr:
1496 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1497 break;
1498 case BinaryOperator::LE:
1499 case BinaryOperator::LT:
1500 case BinaryOperator::GE:
1501 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001502 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001503 break;
1504 case BinaryOperator::EQ:
1505 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001506 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001507 break;
1508 case BinaryOperator::And:
1509 case BinaryOperator::Xor:
1510 case BinaryOperator::Or:
1511 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1512 break;
1513 case BinaryOperator::LAnd:
1514 case BinaryOperator::LOr:
1515 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1516 break;
1517 case BinaryOperator::MulAssign:
1518 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001519 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001520 if (!CompTy.isNull())
1521 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1522 break;
1523 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001524 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001525 if (!CompTy.isNull())
1526 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1527 break;
1528 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001529 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001530 if (!CompTy.isNull())
1531 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1532 break;
1533 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001534 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001535 if (!CompTy.isNull())
1536 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1537 break;
1538 case BinaryOperator::ShlAssign:
1539 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001540 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001541 if (!CompTy.isNull())
1542 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1543 break;
1544 case BinaryOperator::AndAssign:
1545 case BinaryOperator::XorAssign:
1546 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001547 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001548 if (!CompTy.isNull())
1549 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1550 break;
1551 case BinaryOperator::Comma:
1552 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1553 break;
1554 }
1555 if (ResultTy.isNull())
1556 return true;
1557 if (CompTy.isNull())
1558 return new BinaryOperator(lhs, rhs, Opc, ResultTy);
1559 else
1560 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy);
1561}
1562
1563// Unary Operators. 'Tok' is the token for the operator.
1564Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1565 ExprTy *input) {
1566 Expr *Input = (Expr*)input;
1567 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1568 QualType resultType;
1569 switch (Opc) {
1570 default:
1571 assert(0 && "Unimplemented unary expr!");
1572 case UnaryOperator::PreInc:
1573 case UnaryOperator::PreDec:
1574 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1575 break;
1576 case UnaryOperator::AddrOf:
1577 resultType = CheckAddressOfOperand(Input, OpLoc);
1578 break;
1579 case UnaryOperator::Deref:
1580 resultType = CheckIndirectionOperand(Input, OpLoc);
1581 break;
1582 case UnaryOperator::Plus:
1583 case UnaryOperator::Minus:
1584 UsualUnaryConversions(Input);
1585 resultType = Input->getType();
1586 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1587 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1588 resultType.getAsString());
1589 break;
1590 case UnaryOperator::Not: // bitwise complement
1591 UsualUnaryConversions(Input);
1592 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001593 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1594 if (!resultType->isIntegerType()) {
1595 if (resultType->isComplexType())
1596 // C99 does not support '~' for complex conjugation.
1597 Diag(OpLoc, diag::ext_integer_complement_complex,
1598 resultType.getAsString());
1599 else
1600 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1601 resultType.getAsString());
1602 }
Chris Lattner4b009652007-07-25 00:24:17 +00001603 break;
1604 case UnaryOperator::LNot: // logical negation
1605 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1606 DefaultFunctionArrayConversion(Input);
1607 resultType = Input->getType();
1608 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1609 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1610 resultType.getAsString());
1611 // LNot always has type int. C99 6.5.3.3p5.
1612 resultType = Context.IntTy;
1613 break;
1614 case UnaryOperator::SizeOf:
1615 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1616 break;
1617 case UnaryOperator::AlignOf:
1618 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1619 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001620 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001621 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001622 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001623 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001624 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001625 resultType = Input->getType();
1626 break;
1627 }
1628 if (resultType.isNull())
1629 return true;
1630 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1631}
1632
1633/// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
1634Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
1635 SourceLocation LabLoc,
1636 IdentifierInfo *LabelII) {
1637 // Look up the record for this label identifier.
1638 LabelStmt *&LabelDecl = LabelMap[LabelII];
1639
1640 // If we haven't seen this label yet, create a forward reference.
1641 if (LabelDecl == 0)
1642 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1643
1644 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001645 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1646 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001647}
1648
1649Sema::ExprResult Sema::ParseStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
1650 SourceLocation RPLoc) { // "({..})"
1651 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1652 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1653 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1654
1655 // FIXME: there are a variety of strange constraints to enforce here, for
1656 // example, it is not possible to goto into a stmt expression apparently.
1657 // More semantic analysis is needed.
1658
1659 // FIXME: the last statement in the compount stmt has its value used. We
1660 // should not warn about it being unused.
1661
1662 // If there are sub stmts in the compound stmt, take the type of the last one
1663 // as the type of the stmtexpr.
1664 QualType Ty = Context.VoidTy;
1665
1666 if (!Compound->body_empty())
1667 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1668 Ty = LastExpr->getType();
1669
1670 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1671}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001672
Steve Naroff5b528922007-08-01 23:45:51 +00001673Sema::ExprResult Sema::ParseTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001674 TypeTy *arg1, TypeTy *arg2,
1675 SourceLocation RPLoc) {
1676 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1677 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1678
1679 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1680
Steve Naroff5b528922007-08-01 23:45:51 +00001681 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001682}
1683
Steve Naroff93c53012007-08-03 21:21:27 +00001684Sema::ExprResult Sema::ParseChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
1685 ExprTy *expr1, ExprTy *expr2,
1686 SourceLocation RPLoc) {
1687 Expr *CondExpr = static_cast<Expr*>(cond);
1688 Expr *LHSExpr = static_cast<Expr*>(expr1);
1689 Expr *RHSExpr = static_cast<Expr*>(expr2);
1690
1691 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1692
1693 // The conditional expression is required to be a constant expression.
1694 llvm::APSInt condEval(32);
1695 SourceLocation ExpLoc;
1696 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1697 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1698 CondExpr->getSourceRange());
1699
1700 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1701 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1702 RHSExpr->getType();
1703 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1704}
1705
Anders Carlssona66cad42007-08-21 17:43:55 +00001706// TODO: Move this to SemaObjC.cpp
Anders Carlsson8be1d402007-08-22 15:14:15 +00001707Sema::ExprResult Sema::ParseObjCStringLiteral(ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00001708 StringLiteral* S = static_cast<StringLiteral *>(string);
1709
1710 if (CheckBuiltinCFStringArgument(S))
1711 return true;
1712
1713 QualType t = Context.getCFConstantStringType();
1714 t = t.getQualifiedType(QualType::Const);
1715 t = Context.getPointerType(t);
1716
1717 return new ObjCStringLiteral(S, t);
1718}
Anders Carlsson8be1d402007-08-22 15:14:15 +00001719
1720Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1721 SourceLocation LParenLoc,
1722 TypeTy *Ty,
1723 SourceLocation RParenLoc) {
1724 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
1725
1726 QualType t = Context.getPointerType(Context.CharTy);
1727 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
1728}