blob: e4dd9bb490f2e9f7d66abc92c3358fd343477dbe [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
286 if (const ComplexType *CT = V->getType()->getAsComplexType())
287 return CT->getElementType();
288 return V->getType();
289}
290
291
Chris Lattner4b009652007-07-25 00:24:17 +0000292
293Action::ExprResult Sema::ParsePostfixUnaryOp(SourceLocation OpLoc,
294 tok::TokenKind Kind,
295 ExprTy *Input) {
296 UnaryOperator::Opcode Opc;
297 switch (Kind) {
298 default: assert(0 && "Unknown unary op!");
299 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
300 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
301 }
302 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
303 if (result.isNull())
304 return true;
305 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
306}
307
308Action::ExprResult Sema::
309ParseArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
310 ExprTy *Idx, SourceLocation RLoc) {
311 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
312
313 // Perform default conversions.
314 DefaultFunctionArrayConversion(LHSExp);
315 DefaultFunctionArrayConversion(RHSExp);
316
317 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
318
319 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
320 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
321 // in the subscript position. As a result, we need to derive the array base
322 // and index from the expression types.
323 Expr *BaseExpr, *IndexExpr;
324 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000325 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000326 BaseExpr = LHSExp;
327 IndexExpr = RHSExp;
328 // FIXME: need to deal with const...
329 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000330 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000331 // Handle the uncommon case of "123[Ptr]".
332 BaseExpr = RHSExp;
333 IndexExpr = LHSExp;
334 // FIXME: need to deal with const...
335 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000336 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
337 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000338 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000339
340 // Component access limited to variables (reject vec4.rg[1]).
341 if (!isa<DeclRefExpr>(BaseExpr))
342 return Diag(LLoc, diag::err_ocuvector_component_access,
343 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000344 // FIXME: need to deal with const...
345 ResultType = VTy->getElementType();
346 } else {
347 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
348 RHSExp->getSourceRange());
349 }
350 // C99 6.5.2.1p1
351 if (!IndexExpr->getType()->isIntegerType())
352 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
353 IndexExpr->getSourceRange());
354
355 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
356 // the following check catches trying to index a pointer to a function (e.g.
357 // void (*)(int)). Functions are not objects in C99.
358 if (!ResultType->isObjectType())
359 return Diag(BaseExpr->getLocStart(),
360 diag::err_typecheck_subscript_not_object,
361 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
362
363 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
364}
365
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000366QualType Sema::
367CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
368 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000369 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000370
371 // The vector accessor can't exceed the number of elements.
372 const char *compStr = CompName.getName();
373 if (strlen(compStr) > vecType->getNumElements()) {
374 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
375 baseType.getAsString(), SourceRange(CompLoc));
376 return QualType();
377 }
378 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000379 if (vecType->getPointAccessorIdx(*compStr) != -1) {
380 do
381 compStr++;
382 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
383 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
384 do
385 compStr++;
386 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
387 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
388 do
389 compStr++;
390 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
391 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000392
393 if (*compStr) {
394 // We didn't get to the end of the string. This means the component names
395 // didn't come from the same set *or* we encountered an illegal name.
396 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
397 std::string(compStr,compStr+1), SourceRange(CompLoc));
398 return QualType();
399 }
400 // Each component accessor can't exceed the vector type.
401 compStr = CompName.getName();
402 while (*compStr) {
403 if (vecType->isAccessorWithinNumElements(*compStr))
404 compStr++;
405 else
406 break;
407 }
408 if (*compStr) {
409 // We didn't get to the end of the string. This means a component accessor
410 // exceeds the number of elements in the vector.
411 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
412 baseType.getAsString(), SourceRange(CompLoc));
413 return QualType();
414 }
415 // The component accessor looks fine - now we need to compute the actual type.
416 // The vector type is implied by the component accessor. For example,
417 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
418 unsigned CompSize = strlen(CompName.getName());
419 if (CompSize == 1)
420 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000421
422 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
423 // Now look up the TypeDefDecl from the vector type. Without this,
424 // diagostics look bad. We want OCU vector types to appear built-in.
425 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
426 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
427 return Context.getTypedefType(OCUVectorDecls[i]);
428 }
429 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000430}
431
Chris Lattner4b009652007-07-25 00:24:17 +0000432Action::ExprResult Sema::
433ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
434 tok::TokenKind OpKind, SourceLocation MemberLoc,
435 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000436 Expr *BaseExpr = static_cast<Expr *>(Base);
437 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000438
Steve Naroff2cb66382007-07-26 03:11:44 +0000439 QualType BaseType = BaseExpr->getType();
440 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000441
Chris Lattner4b009652007-07-25 00:24:17 +0000442 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000443 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000444 BaseType = PT->getPointeeType();
445 else
446 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
447 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000448 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000449 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000450 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000451 RecordDecl *RDecl = RTy->getDecl();
452 if (RTy->isIncompleteType())
453 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
454 BaseExpr->getSourceRange());
455 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000456 FieldDecl *MemberDecl = RDecl->getMember(&Member);
457 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000458 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
459 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000460 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
461 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000462 // Component access limited to variables (reject vec4.rg.g).
463 if (!isa<DeclRefExpr>(BaseExpr))
464 return Diag(OpLoc, diag::err_ocuvector_component_access,
465 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000466 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
467 if (ret.isNull())
468 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000469 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Steve Naroff2cb66382007-07-26 03:11:44 +0000470 } else
471 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
472 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000473}
474
475/// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
476/// This provides the location of the left/right parens and a list of comma
477/// locations.
478Action::ExprResult Sema::
479ParseCallExpr(ExprTy *fn, SourceLocation LParenLoc,
480 ExprTy **args, unsigned NumArgsInCall,
481 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
482 Expr *Fn = static_cast<Expr *>(fn);
483 Expr **Args = reinterpret_cast<Expr**>(args);
484 assert(Fn && "no function call expression");
485
486 UsualUnaryConversions(Fn);
487 QualType funcType = Fn->getType();
488
489 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
490 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000491 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000492 if (PT == 0)
493 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
494 SourceRange(Fn->getLocStart(), RParenLoc));
495
Chris Lattner71225142007-07-31 21:27:01 +0000496 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000497 if (funcT == 0)
498 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
499 SourceRange(Fn->getLocStart(), RParenLoc));
500
501 // If a prototype isn't declared, the parser implicitly defines a func decl
502 QualType resultType = funcT->getResultType();
503
504 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
505 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
506 // assignment, to the types of the corresponding parameter, ...
507
508 unsigned NumArgsInProto = proto->getNumArgs();
509 unsigned NumArgsToCheck = NumArgsInCall;
510
511 if (NumArgsInCall < NumArgsInProto)
512 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
513 Fn->getSourceRange());
514 else if (NumArgsInCall > NumArgsInProto) {
515 if (!proto->isVariadic()) {
516 Diag(Args[NumArgsInProto]->getLocStart(),
517 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
518 SourceRange(Args[NumArgsInProto]->getLocStart(),
519 Args[NumArgsInCall-1]->getLocEnd()));
520 }
521 NumArgsToCheck = NumArgsInProto;
522 }
523 // Continue to check argument types (even if we have too few/many args).
524 for (unsigned i = 0; i < NumArgsToCheck; i++) {
525 Expr *argExpr = Args[i];
526 assert(argExpr && "ParseCallExpr(): missing argument expression");
527
528 QualType lhsType = proto->getArgType(i);
529 QualType rhsType = argExpr->getType();
530
Steve Naroff75644062007-07-25 20:45:33 +0000531 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000532 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000533 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000534 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000535 lhsType = Context.getPointerType(lhsType);
536
537 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
538 argExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000539 if (Args[i] != argExpr) // The expression was converted.
540 Args[i] = argExpr; // Make sure we store the converted expression.
Chris Lattner4b009652007-07-25 00:24:17 +0000541 SourceLocation l = argExpr->getLocStart();
542
543 // decode the result (notice that AST's are still created for extensions).
544 switch (result) {
545 case Compatible:
546 break;
547 case PointerFromInt:
548 // check for null pointer constant (C99 6.3.2.3p3)
549 if (!argExpr->isNullPointerConstant(Context)) {
550 Diag(l, diag::ext_typecheck_passing_pointer_int,
551 lhsType.getAsString(), rhsType.getAsString(),
552 Fn->getSourceRange(), argExpr->getSourceRange());
553 }
554 break;
555 case IntFromPointer:
556 Diag(l, diag::ext_typecheck_passing_pointer_int,
557 lhsType.getAsString(), rhsType.getAsString(),
558 Fn->getSourceRange(), argExpr->getSourceRange());
559 break;
560 case IncompatiblePointer:
561 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
562 rhsType.getAsString(), lhsType.getAsString(),
563 Fn->getSourceRange(), argExpr->getSourceRange());
564 break;
565 case CompatiblePointerDiscardsQualifiers:
566 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
567 rhsType.getAsString(), lhsType.getAsString(),
568 Fn->getSourceRange(), argExpr->getSourceRange());
569 break;
570 case Incompatible:
571 return Diag(l, diag::err_typecheck_passing_incompatible,
572 rhsType.getAsString(), lhsType.getAsString(),
573 Fn->getSourceRange(), argExpr->getSourceRange());
574 }
575 }
576 // Even if the types checked, bail if we had the wrong number of arguments.
577 if (NumArgsInCall != NumArgsInProto && !proto->isVariadic())
578 return true;
579 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000580
581 // Do special checking on direct calls to functions.
582 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
583 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
584 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000585 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args, NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000586 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000587
Chris Lattner4b009652007-07-25 00:24:17 +0000588 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
589}
590
591Action::ExprResult Sema::
592ParseCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
593 SourceLocation RParenLoc, ExprTy *InitExpr) {
594 assert((Ty != 0) && "ParseCompoundLiteral(): missing type");
595 QualType literalType = QualType::getFromOpaquePtr(Ty);
596 // FIXME: put back this assert when initializers are worked out.
597 //assert((InitExpr != 0) && "ParseCompoundLiteral(): missing expression");
598 Expr *literalExpr = static_cast<Expr*>(InitExpr);
599
600 // FIXME: add semantic analysis (C99 6.5.2.5).
601 return new CompoundLiteralExpr(literalType, literalExpr);
602}
603
604Action::ExprResult Sema::
605ParseInitList(SourceLocation LParenLoc, ExprTy **InitList, unsigned NumInit,
606 SourceLocation RParenLoc) {
607 // FIXME: add semantic analysis (C99 6.7.8). This involves
608 // knowledge of the object being intialized. As a result, the code for
609 // doing the semantic analysis will likely be located elsewhere (i.e. in
610 // consumers of InitListExpr (e.g. ParseDeclarator, ParseCompoundLiteral).
611 return false; // FIXME instantiate an InitListExpr.
612}
613
614Action::ExprResult Sema::
615ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
616 SourceLocation RParenLoc, ExprTy *Op) {
617 assert((Ty != 0) && (Op != 0) && "ParseCastExpr(): missing type or expr");
618
619 Expr *castExpr = static_cast<Expr*>(Op);
620 QualType castType = QualType::getFromOpaquePtr(Ty);
621
622 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
623 // type needs to be scalar.
624 if (!castType->isScalarType() && !castType->isVoidType()) {
625 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
626 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
627 }
628 if (!castExpr->getType()->isScalarType()) {
629 return Diag(castExpr->getLocStart(),
630 diag::err_typecheck_expect_scalar_operand,
631 castExpr->getType().getAsString(), castExpr->getSourceRange());
632 }
633 return new CastExpr(castType, castExpr, LParenLoc);
634}
635
636inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
637 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
638 UsualUnaryConversions(cond);
639 UsualUnaryConversions(lex);
640 UsualUnaryConversions(rex);
641 QualType condT = cond->getType();
642 QualType lexT = lex->getType();
643 QualType rexT = rex->getType();
644
645 // first, check the condition.
646 if (!condT->isScalarType()) { // C99 6.5.15p2
647 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
648 condT.getAsString());
649 return QualType();
650 }
651 // now check the two expressions.
652 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
653 UsualArithmeticConversions(lex, rex);
654 return lex->getType();
655 }
Chris Lattner71225142007-07-31 21:27:01 +0000656 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
657 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
658
659 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
660 return lexT;
661
Chris Lattner4b009652007-07-25 00:24:17 +0000662 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
663 lexT.getAsString(), rexT.getAsString(),
664 lex->getSourceRange(), rex->getSourceRange());
665 return QualType();
666 }
667 }
668 // C99 6.5.15p3
669 if (lexT->isPointerType() && rex->isNullPointerConstant(Context))
670 return lexT;
671 if (rexT->isPointerType() && lex->isNullPointerConstant(Context))
672 return rexT;
673
Chris Lattner71225142007-07-31 21:27:01 +0000674 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
675 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
676 // get the "pointed to" types
677 QualType lhptee = LHSPT->getPointeeType();
678 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000679
Chris Lattner71225142007-07-31 21:27:01 +0000680 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
681 if (lhptee->isVoidType() &&
682 (rhptee->isObjectType() || rhptee->isIncompleteType()))
683 return lexT;
684 if (rhptee->isVoidType() &&
685 (lhptee->isObjectType() || lhptee->isIncompleteType()))
686 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000687
Chris Lattner71225142007-07-31 21:27:01 +0000688 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
689 rhptee.getUnqualifiedType())) {
690 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
691 lexT.getAsString(), rexT.getAsString(),
692 lex->getSourceRange(), rex->getSourceRange());
693 return lexT; // FIXME: this is an _ext - is this return o.k?
694 }
695 // The pointer types are compatible.
696 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
697 // differently qualified versions of compatible types, the result type is a
698 // pointer to an appropriately qualified version of the *composite* type.
699 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000700 }
Chris Lattner4b009652007-07-25 00:24:17 +0000701 }
Chris Lattner71225142007-07-31 21:27:01 +0000702
Chris Lattner4b009652007-07-25 00:24:17 +0000703 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
704 return lexT;
705
706 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
707 lexT.getAsString(), rexT.getAsString(),
708 lex->getSourceRange(), rex->getSourceRange());
709 return QualType();
710}
711
712/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
713/// in the case of a the GNU conditional expr extension.
714Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
715 SourceLocation ColonLoc,
716 ExprTy *Cond, ExprTy *LHS,
717 ExprTy *RHS) {
718 Expr *CondExpr = (Expr *) Cond;
719 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
720 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
721 RHSExpr, QuestionLoc);
722 if (result.isNull())
723 return true;
724 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
725}
726
727// promoteExprToType - a helper function to ensure we create exactly one
728// ImplicitCastExpr. As a convenience (to the caller), we return the type.
729static void promoteExprToType(Expr *&expr, QualType type) {
730 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
731 impCast->setType(type);
732 else
733 expr = new ImplicitCastExpr(type, expr);
734 return;
735}
736
737/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
738void Sema::DefaultFunctionArrayConversion(Expr *&e) {
739 QualType t = e->getType();
740 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
741
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000742 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000743 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
744 t = e->getType();
745 }
746 if (t->isFunctionType())
747 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000748 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000749 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
750}
751
752/// UsualUnaryConversion - Performs various conversions that are common to most
753/// operators (C99 6.3). The conversions of array and function types are
754/// sometimes surpressed. For example, the array->pointer conversion doesn't
755/// apply if the array is an argument to the sizeof or address (&) operators.
756/// In these instances, this routine should *not* be called.
757void Sema::UsualUnaryConversions(Expr *&expr) {
758 QualType t = expr->getType();
759 assert(!t.isNull() && "UsualUnaryConversions - missing type");
760
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000761 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000762 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
763 t = expr->getType();
764 }
765 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
766 promoteExprToType(expr, Context.IntTy);
767 else
768 DefaultFunctionArrayConversion(expr);
769}
770
771/// UsualArithmeticConversions - Performs various conversions that are common to
772/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
773/// routine returns the first non-arithmetic type found. The client is
774/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000775QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
776 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000777 if (!isCompAssign) {
778 UsualUnaryConversions(lhsExpr);
779 UsualUnaryConversions(rhsExpr);
780 }
Chris Lattner4b009652007-07-25 00:24:17 +0000781 QualType lhs = lhsExpr->getType();
782 QualType rhs = rhsExpr->getType();
783
784 // If both types are identical, no conversion is needed.
785 if (lhs == rhs)
Steve Naroff8f708362007-08-24 19:07:16 +0000786 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000787
788 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
789 // The caller can deal with this (e.g. pointer + int).
790 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000791 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000792
793 // At this point, we have two different arithmetic types.
794
795 // Handle complex types first (C99 6.3.1.8p1).
796 if (lhs->isComplexType() || rhs->isComplexType()) {
797 // if we have an integer operand, the result is the complex type.
798 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000799 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
800 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000801 }
802 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000803 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
804 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000805 }
806 // Two complex types. Convert the smaller operand to the bigger result.
807 if (Context.maxComplexType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000808 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
809 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000810 }
Steve Naroff8f708362007-08-24 19:07:16 +0000811 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
812 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000813 }
814 // Now handle "real" floating types (i.e. float, double, long double).
815 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
816 // if we have an integer operand, the result is the real floating type.
817 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000818 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
819 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000820 }
821 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000822 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
823 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000824 }
825 // We have two real floating types, float/complex combos were handled above.
826 // Convert the smaller operand to the bigger result.
827 if (Context.maxFloatingType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000828 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
829 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000830 }
Steve Naroff8f708362007-08-24 19:07:16 +0000831 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
832 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000833 }
834 // Finally, we have two differing integer types.
835 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000836 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
837 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000838 }
Steve Naroff8f708362007-08-24 19:07:16 +0000839 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
840 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000841}
842
843// CheckPointerTypesForAssignment - This is a very tricky routine (despite
844// being closely modeled after the C99 spec:-). The odd characteristic of this
845// routine is it effectively iqnores the qualifiers on the top level pointee.
846// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
847// FIXME: add a couple examples in this comment.
848Sema::AssignmentCheckResult
849Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
850 QualType lhptee, rhptee;
851
852 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +0000853 lhptee = lhsType->getAsPointerType()->getPointeeType();
854 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000855
856 // make sure we operate on the canonical type
857 lhptee = lhptee.getCanonicalType();
858 rhptee = rhptee.getCanonicalType();
859
860 AssignmentCheckResult r = Compatible;
861
862 // C99 6.5.16.1p1: This following citation is common to constraints
863 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
864 // qualifiers of the type *pointed to* by the right;
865 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
866 rhptee.getQualifiers())
867 r = CompatiblePointerDiscardsQualifiers;
868
869 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
870 // incomplete type and the other is a pointer to a qualified or unqualified
871 // version of void...
872 if (lhptee.getUnqualifiedType()->isVoidType() &&
873 (rhptee->isObjectType() || rhptee->isIncompleteType()))
874 ;
875 else if (rhptee.getUnqualifiedType()->isVoidType() &&
876 (lhptee->isObjectType() || lhptee->isIncompleteType()))
877 ;
878 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
879 // unqualified versions of compatible types, ...
880 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
881 rhptee.getUnqualifiedType()))
882 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
883 return r;
884}
885
886/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
887/// has code to accommodate several GCC extensions when type checking
888/// pointers. Here are some objectionable examples that GCC considers warnings:
889///
890/// int a, *pint;
891/// short *pshort;
892/// struct foo *pfoo;
893///
894/// pint = pshort; // warning: assignment from incompatible pointer type
895/// a = pint; // warning: assignment makes integer from pointer without a cast
896/// pint = a; // warning: assignment makes pointer from integer without a cast
897/// pint = pfoo; // warning: assignment from incompatible pointer type
898///
899/// As a result, the code for dealing with pointers is more complex than the
900/// C99 spec dictates.
901/// Note: the warning above turn into errors when -pedantic-errors is enabled.
902///
903Sema::AssignmentCheckResult
904Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
905 if (lhsType == rhsType) // common case, fast path...
906 return Compatible;
907
908 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
909 if (lhsType->isVectorType() || rhsType->isVectorType()) {
910 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
911 return Incompatible;
912 }
913 return Compatible;
914 } else if (lhsType->isPointerType()) {
915 if (rhsType->isIntegerType())
916 return PointerFromInt;
917
918 if (rhsType->isPointerType())
919 return CheckPointerTypesForAssignment(lhsType, rhsType);
920 } else if (rhsType->isPointerType()) {
921 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
922 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
923 return IntFromPointer;
924
925 if (lhsType->isPointerType())
926 return CheckPointerTypesForAssignment(lhsType, rhsType);
927 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
928 if (Type::tagTypesAreCompatible(lhsType, rhsType))
929 return Compatible;
930 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
931 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
932 return Compatible;
933 }
934 return Incompatible;
935}
936
937Sema::AssignmentCheckResult
938Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
939 // This check seems unnatural, however it is necessary to insure the proper
940 // conversion of functions/arrays. If the conversion were done for all
941 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
942 // expressions that surpress this implicit conversion (&, sizeof).
943 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000944
945 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +0000946
Steve Naroff0f32f432007-08-24 22:33:52 +0000947 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
948
949 // C99 6.5.16.1p2: The value of the right operand is converted to the
950 // type of the assignment expression.
951 if (rExpr->getType() != lhsType)
952 promoteExprToType(rExpr, lhsType);
953 return result;
Chris Lattner4b009652007-07-25 00:24:17 +0000954}
955
956Sema::AssignmentCheckResult
957Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
958 return CheckAssignmentConstraints(lhsType, rhsType);
959}
960
961inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
962 Diag(loc, diag::err_typecheck_invalid_operands,
963 lex->getType().getAsString(), rex->getType().getAsString(),
964 lex->getSourceRange(), rex->getSourceRange());
965}
966
967inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
968 Expr *&rex) {
969 QualType lhsType = lex->getType(), rhsType = rex->getType();
970
971 // make sure the vector types are identical.
972 if (lhsType == rhsType)
973 return lhsType;
974 // You cannot convert between vector values of different size.
975 Diag(loc, diag::err_typecheck_vector_not_convertable,
976 lex->getType().getAsString(), rex->getType().getAsString(),
977 lex->getSourceRange(), rex->getSourceRange());
978 return QualType();
979}
980
981inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +0000982 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +0000983{
984 QualType lhsType = lex->getType(), rhsType = rex->getType();
985
986 if (lhsType->isVectorType() || rhsType->isVectorType())
987 return CheckVectorOperands(loc, lex, rex);
988
Steve Naroff8f708362007-08-24 19:07:16 +0000989 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +0000990
Chris Lattner4b009652007-07-25 00:24:17 +0000991 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000992 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +0000993 InvalidOperands(loc, lex, rex);
994 return QualType();
995}
996
997inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +0000998 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +0000999{
1000 QualType lhsType = lex->getType(), rhsType = rex->getType();
1001
Steve Naroff8f708362007-08-24 19:07:16 +00001002 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001003
Chris Lattner4b009652007-07-25 00:24:17 +00001004 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001005 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001006 InvalidOperands(loc, lex, rex);
1007 return QualType();
1008}
1009
1010inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001011 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001012{
1013 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1014 return CheckVectorOperands(loc, lex, rex);
1015
Steve Naroff8f708362007-08-24 19:07:16 +00001016 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001017
1018 // handle the common case first (both operands are arithmetic).
1019 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001020 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001021
1022 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1023 return lex->getType();
1024 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1025 return rex->getType();
1026 InvalidOperands(loc, lex, rex);
1027 return QualType();
1028}
1029
1030inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001031 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001032{
1033 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1034 return CheckVectorOperands(loc, lex, rex);
1035
Steve Naroff8f708362007-08-24 19:07:16 +00001036 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001037
1038 // handle the common case first (both operands are arithmetic).
1039 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001040 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001041
1042 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001043 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001044 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1045 return Context.getPointerDiffType();
1046 InvalidOperands(loc, lex, rex);
1047 return QualType();
1048}
1049
1050inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001051 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001052{
1053 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1054 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001055 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001056
1057 // handle the common case first (both operands are arithmetic).
1058 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001059 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001060 InvalidOperands(loc, lex, rex);
1061 return QualType();
1062}
1063
Chris Lattner254f3bc2007-08-26 01:18:55 +00001064inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1065 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001066{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001067 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001068 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1069 UsualArithmeticConversions(lex, rex);
1070 else {
1071 UsualUnaryConversions(lex);
1072 UsualUnaryConversions(rex);
1073 }
Chris Lattner4b009652007-07-25 00:24:17 +00001074 QualType lType = lex->getType();
1075 QualType rType = rex->getType();
1076
Chris Lattner254f3bc2007-08-26 01:18:55 +00001077 if (isRelational) {
1078 if (lType->isRealType() && rType->isRealType())
1079 return Context.IntTy;
1080 } else {
1081 if (lType->isArithmeticType() && rType->isArithmeticType())
1082 return Context.IntTy;
1083 }
Chris Lattner4b009652007-07-25 00:24:17 +00001084
Chris Lattner22be8422007-08-26 01:10:14 +00001085 bool LHSIsNull = lex->isNullPointerConstant(Context);
1086 bool RHSIsNull = rex->isNullPointerConstant(Context);
1087
Chris Lattner254f3bc2007-08-26 01:18:55 +00001088 // All of the following pointer related warnings are GCC extensions, except
1089 // when handling null pointer constants. One day, we can consider making them
1090 // errors (when -pedantic-errors is enabled).
Steve Naroff4462cb02007-08-16 21:48:38 +00001091 if (lType->isPointerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001092 if (!LHSIsNull && !RHSIsNull &&
1093 !Type::pointerTypesAreCompatible(lType, rType)) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001094 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1095 lType.getAsString(), rType.getAsString(),
1096 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001097 }
Chris Lattner22be8422007-08-26 01:10:14 +00001098 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001099 return Context.IntTy;
1100 }
1101 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001102 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001103 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1104 lType.getAsString(), rType.getAsString(),
1105 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001106 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001107 return Context.IntTy;
1108 }
1109 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001110 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001111 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1112 lType.getAsString(), rType.getAsString(),
1113 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001114 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001115 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001116 }
1117 InvalidOperands(loc, lex, rex);
1118 return QualType();
1119}
1120
Chris Lattner4b009652007-07-25 00:24:17 +00001121inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001122 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001123{
1124 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1125 return CheckVectorOperands(loc, lex, rex);
1126
Steve Naroff8f708362007-08-24 19:07:16 +00001127 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001128
1129 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001130 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001131 InvalidOperands(loc, lex, rex);
1132 return QualType();
1133}
1134
1135inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1136 Expr *&lex, Expr *&rex, SourceLocation loc)
1137{
1138 UsualUnaryConversions(lex);
1139 UsualUnaryConversions(rex);
1140
1141 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1142 return Context.IntTy;
1143 InvalidOperands(loc, lex, rex);
1144 return QualType();
1145}
1146
1147inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001148 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001149{
1150 QualType lhsType = lex->getType();
1151 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1152 bool hadError = false;
1153 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1154
1155 switch (mlval) { // C99 6.5.16p2
1156 case Expr::MLV_Valid:
1157 break;
1158 case Expr::MLV_ConstQualified:
1159 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1160 hadError = true;
1161 break;
1162 case Expr::MLV_ArrayType:
1163 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1164 lhsType.getAsString(), lex->getSourceRange());
1165 return QualType();
1166 case Expr::MLV_NotObjectType:
1167 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1168 lhsType.getAsString(), lex->getSourceRange());
1169 return QualType();
1170 case Expr::MLV_InvalidExpression:
1171 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1172 lex->getSourceRange());
1173 return QualType();
1174 case Expr::MLV_IncompleteType:
1175 case Expr::MLV_IncompleteVoidType:
1176 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1177 lhsType.getAsString(), lex->getSourceRange());
1178 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001179 case Expr::MLV_DuplicateVectorComponents:
1180 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1181 lex->getSourceRange());
1182 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001183 }
1184 AssignmentCheckResult result;
1185
1186 if (compoundType.isNull())
1187 result = CheckSingleAssignmentConstraints(lhsType, rex);
1188 else
1189 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001190
Chris Lattner4b009652007-07-25 00:24:17 +00001191 // decode the result (notice that extensions still return a type).
1192 switch (result) {
1193 case Compatible:
1194 break;
1195 case Incompatible:
1196 Diag(loc, diag::err_typecheck_assign_incompatible,
1197 lhsType.getAsString(), rhsType.getAsString(),
1198 lex->getSourceRange(), rex->getSourceRange());
1199 hadError = true;
1200 break;
1201 case PointerFromInt:
1202 // check for null pointer constant (C99 6.3.2.3p3)
1203 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1204 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1205 lhsType.getAsString(), rhsType.getAsString(),
1206 lex->getSourceRange(), rex->getSourceRange());
1207 }
1208 break;
1209 case IntFromPointer:
1210 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1211 lhsType.getAsString(), rhsType.getAsString(),
1212 lex->getSourceRange(), rex->getSourceRange());
1213 break;
1214 case IncompatiblePointer:
1215 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1216 lhsType.getAsString(), rhsType.getAsString(),
1217 lex->getSourceRange(), rex->getSourceRange());
1218 break;
1219 case CompatiblePointerDiscardsQualifiers:
1220 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1221 lhsType.getAsString(), rhsType.getAsString(),
1222 lex->getSourceRange(), rex->getSourceRange());
1223 break;
1224 }
1225 // C99 6.5.16p3: The type of an assignment expression is the type of the
1226 // left operand unless the left operand has qualified type, in which case
1227 // it is the unqualified version of the type of the left operand.
1228 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1229 // is converted to the type of the assignment expression (above).
1230 // C++ 5.17p1: the type of the assignment expression is that of its left oprdu.
1231 return hadError ? QualType() : lhsType.getUnqualifiedType();
1232}
1233
1234inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1235 Expr *&lex, Expr *&rex, SourceLocation loc) {
1236 UsualUnaryConversions(rex);
1237 return rex->getType();
1238}
1239
1240/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1241/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1242QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1243 QualType resType = op->getType();
1244 assert(!resType.isNull() && "no type for increment/decrement expression");
1245
Steve Naroffd30e1932007-08-24 17:20:07 +00001246 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattner4b009652007-07-25 00:24:17 +00001247 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1248 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1249 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1250 resType.getAsString(), op->getSourceRange());
1251 return QualType();
1252 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001253 } else if (!resType->isRealType()) {
1254 if (resType->isComplexType())
1255 // C99 does not support ++/-- on complex types.
1256 Diag(OpLoc, diag::ext_integer_increment_complex,
1257 resType.getAsString(), op->getSourceRange());
1258 else {
1259 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1260 resType.getAsString(), op->getSourceRange());
1261 return QualType();
1262 }
Chris Lattner4b009652007-07-25 00:24:17 +00001263 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001264 // At this point, we know we have a real, complex or pointer type.
1265 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001266 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1267 if (mlval != Expr::MLV_Valid) {
1268 // FIXME: emit a more precise diagnostic...
1269 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1270 op->getSourceRange());
1271 return QualType();
1272 }
1273 return resType;
1274}
1275
1276/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1277/// This routine allows us to typecheck complex/recursive expressions
1278/// where the declaration is needed for type checking. Here are some
1279/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1280static Decl *getPrimaryDeclaration(Expr *e) {
1281 switch (e->getStmtClass()) {
1282 case Stmt::DeclRefExprClass:
1283 return cast<DeclRefExpr>(e)->getDecl();
1284 case Stmt::MemberExprClass:
1285 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1286 case Stmt::ArraySubscriptExprClass:
1287 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1288 case Stmt::CallExprClass:
1289 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1290 case Stmt::UnaryOperatorClass:
1291 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1292 case Stmt::ParenExprClass:
1293 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1294 default:
1295 return 0;
1296 }
1297}
1298
1299/// CheckAddressOfOperand - The operand of & must be either a function
1300/// designator or an lvalue designating an object. If it is an lvalue, the
1301/// object cannot be declared with storage class register or be a bit field.
1302/// Note: The usual conversions are *not* applied to the operand of the &
1303/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1304QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1305 Decl *dcl = getPrimaryDeclaration(op);
1306 Expr::isLvalueResult lval = op->isLvalue();
1307
1308 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1309 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1310 ;
1311 else { // FIXME: emit more specific diag...
1312 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1313 op->getSourceRange());
1314 return QualType();
1315 }
1316 } else if (dcl) {
1317 // We have an lvalue with a decl. Make sure the decl is not declared
1318 // with the register storage-class specifier.
1319 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1320 if (vd->getStorageClass() == VarDecl::Register) {
1321 Diag(OpLoc, diag::err_typecheck_address_of_register,
1322 op->getSourceRange());
1323 return QualType();
1324 }
1325 } else
1326 assert(0 && "Unknown/unexpected decl type");
1327
1328 // FIXME: add check for bitfields!
1329 }
1330 // If the operand has type "type", the result has type "pointer to type".
1331 return Context.getPointerType(op->getType());
1332}
1333
1334QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1335 UsualUnaryConversions(op);
1336 QualType qType = op->getType();
1337
Chris Lattner7931f4a2007-07-31 16:53:04 +00001338 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001339 QualType ptype = PT->getPointeeType();
1340 // C99 6.5.3.2p4. "if it points to an object,...".
1341 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1342 // GCC compat: special case 'void *' (treat as warning).
1343 if (ptype->isVoidType()) {
1344 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1345 qType.getAsString(), op->getSourceRange());
1346 } else {
1347 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1348 ptype.getAsString(), op->getSourceRange());
1349 return QualType();
1350 }
1351 }
1352 return ptype;
1353 }
1354 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1355 qType.getAsString(), op->getSourceRange());
1356 return QualType();
1357}
1358
1359static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1360 tok::TokenKind Kind) {
1361 BinaryOperator::Opcode Opc;
1362 switch (Kind) {
1363 default: assert(0 && "Unknown binop!");
1364 case tok::star: Opc = BinaryOperator::Mul; break;
1365 case tok::slash: Opc = BinaryOperator::Div; break;
1366 case tok::percent: Opc = BinaryOperator::Rem; break;
1367 case tok::plus: Opc = BinaryOperator::Add; break;
1368 case tok::minus: Opc = BinaryOperator::Sub; break;
1369 case tok::lessless: Opc = BinaryOperator::Shl; break;
1370 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1371 case tok::lessequal: Opc = BinaryOperator::LE; break;
1372 case tok::less: Opc = BinaryOperator::LT; break;
1373 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1374 case tok::greater: Opc = BinaryOperator::GT; break;
1375 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1376 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1377 case tok::amp: Opc = BinaryOperator::And; break;
1378 case tok::caret: Opc = BinaryOperator::Xor; break;
1379 case tok::pipe: Opc = BinaryOperator::Or; break;
1380 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1381 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1382 case tok::equal: Opc = BinaryOperator::Assign; break;
1383 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1384 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1385 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1386 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1387 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1388 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1389 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1390 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1391 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1392 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1393 case tok::comma: Opc = BinaryOperator::Comma; break;
1394 }
1395 return Opc;
1396}
1397
1398static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1399 tok::TokenKind Kind) {
1400 UnaryOperator::Opcode Opc;
1401 switch (Kind) {
1402 default: assert(0 && "Unknown unary op!");
1403 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1404 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1405 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1406 case tok::star: Opc = UnaryOperator::Deref; break;
1407 case tok::plus: Opc = UnaryOperator::Plus; break;
1408 case tok::minus: Opc = UnaryOperator::Minus; break;
1409 case tok::tilde: Opc = UnaryOperator::Not; break;
1410 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1411 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1412 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1413 case tok::kw___real: Opc = UnaryOperator::Real; break;
1414 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1415 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1416 }
1417 return Opc;
1418}
1419
1420// Binary Operators. 'Tok' is the token for the operator.
1421Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1422 ExprTy *LHS, ExprTy *RHS) {
1423 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1424 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1425
1426 assert((lhs != 0) && "ParseBinOp(): missing left expression");
1427 assert((rhs != 0) && "ParseBinOp(): missing right expression");
1428
1429 QualType ResultTy; // Result type of the binary operator.
1430 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1431
1432 switch (Opc) {
1433 default:
1434 assert(0 && "Unknown binary expr!");
1435 case BinaryOperator::Assign:
1436 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1437 break;
1438 case BinaryOperator::Mul:
1439 case BinaryOperator::Div:
1440 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1441 break;
1442 case BinaryOperator::Rem:
1443 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1444 break;
1445 case BinaryOperator::Add:
1446 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1447 break;
1448 case BinaryOperator::Sub:
1449 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1450 break;
1451 case BinaryOperator::Shl:
1452 case BinaryOperator::Shr:
1453 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1454 break;
1455 case BinaryOperator::LE:
1456 case BinaryOperator::LT:
1457 case BinaryOperator::GE:
1458 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001459 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001460 break;
1461 case BinaryOperator::EQ:
1462 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001463 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001464 break;
1465 case BinaryOperator::And:
1466 case BinaryOperator::Xor:
1467 case BinaryOperator::Or:
1468 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1469 break;
1470 case BinaryOperator::LAnd:
1471 case BinaryOperator::LOr:
1472 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1473 break;
1474 case BinaryOperator::MulAssign:
1475 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001476 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001477 if (!CompTy.isNull())
1478 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1479 break;
1480 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001481 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001482 if (!CompTy.isNull())
1483 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1484 break;
1485 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001486 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001487 if (!CompTy.isNull())
1488 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1489 break;
1490 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001491 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001492 if (!CompTy.isNull())
1493 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1494 break;
1495 case BinaryOperator::ShlAssign:
1496 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001497 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001498 if (!CompTy.isNull())
1499 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1500 break;
1501 case BinaryOperator::AndAssign:
1502 case BinaryOperator::XorAssign:
1503 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001504 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001505 if (!CompTy.isNull())
1506 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1507 break;
1508 case BinaryOperator::Comma:
1509 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1510 break;
1511 }
1512 if (ResultTy.isNull())
1513 return true;
1514 if (CompTy.isNull())
1515 return new BinaryOperator(lhs, rhs, Opc, ResultTy);
1516 else
1517 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy);
1518}
1519
1520// Unary Operators. 'Tok' is the token for the operator.
1521Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1522 ExprTy *input) {
1523 Expr *Input = (Expr*)input;
1524 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1525 QualType resultType;
1526 switch (Opc) {
1527 default:
1528 assert(0 && "Unimplemented unary expr!");
1529 case UnaryOperator::PreInc:
1530 case UnaryOperator::PreDec:
1531 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1532 break;
1533 case UnaryOperator::AddrOf:
1534 resultType = CheckAddressOfOperand(Input, OpLoc);
1535 break;
1536 case UnaryOperator::Deref:
1537 resultType = CheckIndirectionOperand(Input, OpLoc);
1538 break;
1539 case UnaryOperator::Plus:
1540 case UnaryOperator::Minus:
1541 UsualUnaryConversions(Input);
1542 resultType = Input->getType();
1543 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1544 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1545 resultType.getAsString());
1546 break;
1547 case UnaryOperator::Not: // bitwise complement
1548 UsualUnaryConversions(Input);
1549 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001550 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1551 if (!resultType->isIntegerType()) {
1552 if (resultType->isComplexType())
1553 // C99 does not support '~' for complex conjugation.
1554 Diag(OpLoc, diag::ext_integer_complement_complex,
1555 resultType.getAsString());
1556 else
1557 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1558 resultType.getAsString());
1559 }
Chris Lattner4b009652007-07-25 00:24:17 +00001560 break;
1561 case UnaryOperator::LNot: // logical negation
1562 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1563 DefaultFunctionArrayConversion(Input);
1564 resultType = Input->getType();
1565 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1566 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1567 resultType.getAsString());
1568 // LNot always has type int. C99 6.5.3.3p5.
1569 resultType = Context.IntTy;
1570 break;
1571 case UnaryOperator::SizeOf:
1572 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1573 break;
1574 case UnaryOperator::AlignOf:
1575 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1576 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001577 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001578 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001579 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001580 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001581 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001582 resultType = Input->getType();
1583 break;
1584 }
1585 if (resultType.isNull())
1586 return true;
1587 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1588}
1589
1590/// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
1591Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
1592 SourceLocation LabLoc,
1593 IdentifierInfo *LabelII) {
1594 // Look up the record for this label identifier.
1595 LabelStmt *&LabelDecl = LabelMap[LabelII];
1596
1597 // If we haven't seen this label yet, create a forward reference.
1598 if (LabelDecl == 0)
1599 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1600
1601 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001602 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1603 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001604}
1605
1606Sema::ExprResult Sema::ParseStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
1607 SourceLocation RPLoc) { // "({..})"
1608 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1609 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1610 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1611
1612 // FIXME: there are a variety of strange constraints to enforce here, for
1613 // example, it is not possible to goto into a stmt expression apparently.
1614 // More semantic analysis is needed.
1615
1616 // FIXME: the last statement in the compount stmt has its value used. We
1617 // should not warn about it being unused.
1618
1619 // If there are sub stmts in the compound stmt, take the type of the last one
1620 // as the type of the stmtexpr.
1621 QualType Ty = Context.VoidTy;
1622
1623 if (!Compound->body_empty())
1624 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1625 Ty = LastExpr->getType();
1626
1627 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1628}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001629
Steve Naroff5b528922007-08-01 23:45:51 +00001630Sema::ExprResult Sema::ParseTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001631 TypeTy *arg1, TypeTy *arg2,
1632 SourceLocation RPLoc) {
1633 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1634 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1635
1636 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1637
Steve Naroff5b528922007-08-01 23:45:51 +00001638 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001639}
1640
Steve Naroff93c53012007-08-03 21:21:27 +00001641Sema::ExprResult Sema::ParseChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
1642 ExprTy *expr1, ExprTy *expr2,
1643 SourceLocation RPLoc) {
1644 Expr *CondExpr = static_cast<Expr*>(cond);
1645 Expr *LHSExpr = static_cast<Expr*>(expr1);
1646 Expr *RHSExpr = static_cast<Expr*>(expr2);
1647
1648 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1649
1650 // The conditional expression is required to be a constant expression.
1651 llvm::APSInt condEval(32);
1652 SourceLocation ExpLoc;
1653 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1654 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1655 CondExpr->getSourceRange());
1656
1657 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1658 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1659 RHSExpr->getType();
1660 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1661}
1662
Anders Carlssona66cad42007-08-21 17:43:55 +00001663// TODO: Move this to SemaObjC.cpp
Anders Carlsson8be1d402007-08-22 15:14:15 +00001664Sema::ExprResult Sema::ParseObjCStringLiteral(ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00001665 StringLiteral* S = static_cast<StringLiteral *>(string);
1666
1667 if (CheckBuiltinCFStringArgument(S))
1668 return true;
1669
1670 QualType t = Context.getCFConstantStringType();
1671 t = t.getQualifiedType(QualType::Const);
1672 t = Context.getPointerType(t);
1673
1674 return new ObjCStringLiteral(S, t);
1675}
Anders Carlsson8be1d402007-08-22 15:14:15 +00001676
1677Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1678 SourceLocation LParenLoc,
1679 TypeTy *Ty,
1680 SourceLocation RParenLoc) {
1681 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
1682
1683 QualType t = Context.getPointerType(Context.CharTy);
1684 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
1685}