blob: a0fa38e1d86295af4a888638fba19efb4c70d717 [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
144 if (Literal.isIntegerLiteral()) {
145 QualType t;
146
147 // Get the value in the widest-possible width.
148 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
149
150 if (Literal.GetIntegerValue(ResultVal)) {
151 // If this value didn't fit into uintmax_t, warn and force to ull.
152 Diag(Tok.getLocation(), diag::warn_integer_too_large);
153 t = Context.UnsignedLongLongTy;
154 assert(Context.getTypeSize(t, Tok.getLocation()) ==
155 ResultVal.getBitWidth() && "long long is not intmax_t?");
156 } else {
157 // If this value fits into a ULL, try to figure out what else it fits into
158 // according to the rules of C99 6.4.4.1p5.
159
160 // Octal, Hexadecimal, and integers with a U suffix are allowed to
161 // be an unsigned int.
162 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
163
164 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000165 if (!Literal.isLong && !Literal.isLongLong) {
166 // Are int/unsigned possibilities?
Chris Lattner4b009652007-07-25 00:24:17 +0000167 unsigned IntSize = Context.getTypeSize(Context.IntTy,Tok.getLocation());
168 // Does it fit in a unsigned int?
169 if (ResultVal.isIntN(IntSize)) {
170 // Does it fit in a signed int?
171 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
172 t = Context.IntTy;
173 else if (AllowUnsigned)
174 t = Context.UnsignedIntTy;
175 }
176
177 if (!t.isNull())
178 ResultVal.trunc(IntSize);
179 }
180
181 // Are long/unsigned long possibilities?
182 if (t.isNull() && !Literal.isLongLong) {
183 unsigned LongSize = Context.getTypeSize(Context.LongTy,
184 Tok.getLocation());
185
186 // Does it fit in a unsigned long?
187 if (ResultVal.isIntN(LongSize)) {
188 // Does it fit in a signed long?
189 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
190 t = Context.LongTy;
191 else if (AllowUnsigned)
192 t = Context.UnsignedLongTy;
193 }
194 if (!t.isNull())
195 ResultVal.trunc(LongSize);
196 }
197
198 // Finally, check long long if needed.
199 if (t.isNull()) {
200 unsigned LongLongSize =
201 Context.getTypeSize(Context.LongLongTy, Tok.getLocation());
202
203 // Does it fit in a unsigned long long?
204 if (ResultVal.isIntN(LongLongSize)) {
205 // Does it fit in a signed long long?
206 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
207 t = Context.LongLongTy;
208 else if (AllowUnsigned)
209 t = Context.UnsignedLongLongTy;
210 }
211 }
212
213 // If we still couldn't decide a type, we probably have something that
214 // does not fit in a signed long long, but has no U suffix.
215 if (t.isNull()) {
216 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
217 t = Context.UnsignedLongLongTy;
218 }
219 }
220
221 return new IntegerLiteral(ResultVal, t, Tok.getLocation());
222 } else if (Literal.isFloatingLiteral()) {
223 // FIXME: handle float values > 32 (including compute the real type...).
224 return new FloatingLiteral(Literal.GetFloatValue(), Context.FloatTy,
225 Tok.getLocation());
226 }
227 return ExprResult(true);
228}
229
230Action::ExprResult Sema::ParseParenExpr(SourceLocation L, SourceLocation R,
231 ExprTy *Val) {
232 Expr *e = (Expr *)Val;
233 assert((e != 0) && "ParseParenExpr() missing expr");
234 return new ParenExpr(L, R, e);
235}
236
237/// The UsualUnaryConversions() function is *not* called by this routine.
238/// See C99 6.3.2.1p[2-4] for more details.
239QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
240 SourceLocation OpLoc, bool isSizeof) {
241 // C99 6.5.3.4p1:
242 if (isa<FunctionType>(exprType) && isSizeof)
243 // alignof(function) is allowed.
244 Diag(OpLoc, diag::ext_sizeof_function_type);
245 else if (exprType->isVoidType())
246 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
247 else if (exprType->isIncompleteType()) {
248 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
249 diag::err_alignof_incomplete_type,
250 exprType.getAsString());
251 return QualType(); // error
252 }
253 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
254 return Context.getSizeType();
255}
256
257Action::ExprResult Sema::
258ParseSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
259 SourceLocation LPLoc, TypeTy *Ty,
260 SourceLocation RPLoc) {
261 // If error parsing type, ignore.
262 if (Ty == 0) return true;
263
264 // Verify that this is a valid expression.
265 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
266
267 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
268
269 if (resultType.isNull())
270 return true;
271 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
272}
273
Chris Lattner5110ad52007-08-24 21:41:10 +0000274QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000275 DefaultFunctionArrayConversion(V);
276
277 if (const ComplexType *CT = V->getType()->getAsComplexType())
278 return CT->getElementType();
279 return V->getType();
280}
281
282
Chris Lattner4b009652007-07-25 00:24:17 +0000283
284Action::ExprResult Sema::ParsePostfixUnaryOp(SourceLocation OpLoc,
285 tok::TokenKind Kind,
286 ExprTy *Input) {
287 UnaryOperator::Opcode Opc;
288 switch (Kind) {
289 default: assert(0 && "Unknown unary op!");
290 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
291 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
292 }
293 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
294 if (result.isNull())
295 return true;
296 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
297}
298
299Action::ExprResult Sema::
300ParseArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
301 ExprTy *Idx, SourceLocation RLoc) {
302 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
303
304 // Perform default conversions.
305 DefaultFunctionArrayConversion(LHSExp);
306 DefaultFunctionArrayConversion(RHSExp);
307
308 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
309
310 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
311 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
312 // in the subscript position. As a result, we need to derive the array base
313 // and index from the expression types.
314 Expr *BaseExpr, *IndexExpr;
315 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000316 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000317 BaseExpr = LHSExp;
318 IndexExpr = RHSExp;
319 // FIXME: need to deal with const...
320 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000321 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000322 // Handle the uncommon case of "123[Ptr]".
323 BaseExpr = RHSExp;
324 IndexExpr = LHSExp;
325 // FIXME: need to deal with const...
326 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000327 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
328 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000329 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000330
331 // Component access limited to variables (reject vec4.rg[1]).
332 if (!isa<DeclRefExpr>(BaseExpr))
333 return Diag(LLoc, diag::err_ocuvector_component_access,
334 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000335 // FIXME: need to deal with const...
336 ResultType = VTy->getElementType();
337 } else {
338 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
339 RHSExp->getSourceRange());
340 }
341 // C99 6.5.2.1p1
342 if (!IndexExpr->getType()->isIntegerType())
343 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
344 IndexExpr->getSourceRange());
345
346 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
347 // the following check catches trying to index a pointer to a function (e.g.
348 // void (*)(int)). Functions are not objects in C99.
349 if (!ResultType->isObjectType())
350 return Diag(BaseExpr->getLocStart(),
351 diag::err_typecheck_subscript_not_object,
352 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
353
354 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
355}
356
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000357QualType Sema::
358CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
359 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000360 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000361
362 // The vector accessor can't exceed the number of elements.
363 const char *compStr = CompName.getName();
364 if (strlen(compStr) > vecType->getNumElements()) {
365 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
366 baseType.getAsString(), SourceRange(CompLoc));
367 return QualType();
368 }
369 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000370 if (vecType->getPointAccessorIdx(*compStr) != -1) {
371 do
372 compStr++;
373 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
374 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
375 do
376 compStr++;
377 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
378 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
379 do
380 compStr++;
381 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
382 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000383
384 if (*compStr) {
385 // We didn't get to the end of the string. This means the component names
386 // didn't come from the same set *or* we encountered an illegal name.
387 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
388 std::string(compStr,compStr+1), SourceRange(CompLoc));
389 return QualType();
390 }
391 // Each component accessor can't exceed the vector type.
392 compStr = CompName.getName();
393 while (*compStr) {
394 if (vecType->isAccessorWithinNumElements(*compStr))
395 compStr++;
396 else
397 break;
398 }
399 if (*compStr) {
400 // We didn't get to the end of the string. This means a component accessor
401 // exceeds the number of elements in the vector.
402 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
403 baseType.getAsString(), SourceRange(CompLoc));
404 return QualType();
405 }
406 // The component accessor looks fine - now we need to compute the actual type.
407 // The vector type is implied by the component accessor. For example,
408 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
409 unsigned CompSize = strlen(CompName.getName());
410 if (CompSize == 1)
411 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000412
413 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
414 // Now look up the TypeDefDecl from the vector type. Without this,
415 // diagostics look bad. We want OCU vector types to appear built-in.
416 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
417 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
418 return Context.getTypedefType(OCUVectorDecls[i]);
419 }
420 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000421}
422
Chris Lattner4b009652007-07-25 00:24:17 +0000423Action::ExprResult Sema::
424ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
425 tok::TokenKind OpKind, SourceLocation MemberLoc,
426 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000427 Expr *BaseExpr = static_cast<Expr *>(Base);
428 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000429
Steve Naroff2cb66382007-07-26 03:11:44 +0000430 QualType BaseType = BaseExpr->getType();
431 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000432
Chris Lattner4b009652007-07-25 00:24:17 +0000433 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000434 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000435 BaseType = PT->getPointeeType();
436 else
437 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
438 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000439 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000440 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000441 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000442 RecordDecl *RDecl = RTy->getDecl();
443 if (RTy->isIncompleteType())
444 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
445 BaseExpr->getSourceRange());
446 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000447 FieldDecl *MemberDecl = RDecl->getMember(&Member);
448 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000449 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
450 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000451 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
452 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000453 // Component access limited to variables (reject vec4.rg.g).
454 if (!isa<DeclRefExpr>(BaseExpr))
455 return Diag(OpLoc, diag::err_ocuvector_component_access,
456 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000457 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
458 if (ret.isNull())
459 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000460 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Steve Naroff2cb66382007-07-26 03:11:44 +0000461 } else
462 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
463 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000464}
465
466/// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
467/// This provides the location of the left/right parens and a list of comma
468/// locations.
469Action::ExprResult Sema::
470ParseCallExpr(ExprTy *fn, SourceLocation LParenLoc,
471 ExprTy **args, unsigned NumArgsInCall,
472 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
473 Expr *Fn = static_cast<Expr *>(fn);
474 Expr **Args = reinterpret_cast<Expr**>(args);
475 assert(Fn && "no function call expression");
476
477 UsualUnaryConversions(Fn);
478 QualType funcType = Fn->getType();
479
480 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
481 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000482 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000483 if (PT == 0)
484 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
485 SourceRange(Fn->getLocStart(), RParenLoc));
486
Chris Lattner71225142007-07-31 21:27:01 +0000487 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000488 if (funcT == 0)
489 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
490 SourceRange(Fn->getLocStart(), RParenLoc));
491
492 // If a prototype isn't declared, the parser implicitly defines a func decl
493 QualType resultType = funcT->getResultType();
494
495 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
496 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
497 // assignment, to the types of the corresponding parameter, ...
498
499 unsigned NumArgsInProto = proto->getNumArgs();
500 unsigned NumArgsToCheck = NumArgsInCall;
501
502 if (NumArgsInCall < NumArgsInProto)
503 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
504 Fn->getSourceRange());
505 else if (NumArgsInCall > NumArgsInProto) {
506 if (!proto->isVariadic()) {
507 Diag(Args[NumArgsInProto]->getLocStart(),
508 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
509 SourceRange(Args[NumArgsInProto]->getLocStart(),
510 Args[NumArgsInCall-1]->getLocEnd()));
511 }
512 NumArgsToCheck = NumArgsInProto;
513 }
514 // Continue to check argument types (even if we have too few/many args).
515 for (unsigned i = 0; i < NumArgsToCheck; i++) {
516 Expr *argExpr = Args[i];
517 assert(argExpr && "ParseCallExpr(): missing argument expression");
518
519 QualType lhsType = proto->getArgType(i);
520 QualType rhsType = argExpr->getType();
521
Steve Naroff75644062007-07-25 20:45:33 +0000522 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000523 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000524 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000525 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000526 lhsType = Context.getPointerType(lhsType);
527
528 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
529 argExpr);
530 SourceLocation l = argExpr->getLocStart();
531
532 // decode the result (notice that AST's are still created for extensions).
533 switch (result) {
534 case Compatible:
535 break;
536 case PointerFromInt:
537 // check for null pointer constant (C99 6.3.2.3p3)
538 if (!argExpr->isNullPointerConstant(Context)) {
539 Diag(l, diag::ext_typecheck_passing_pointer_int,
540 lhsType.getAsString(), rhsType.getAsString(),
541 Fn->getSourceRange(), argExpr->getSourceRange());
542 }
543 break;
544 case IntFromPointer:
545 Diag(l, diag::ext_typecheck_passing_pointer_int,
546 lhsType.getAsString(), rhsType.getAsString(),
547 Fn->getSourceRange(), argExpr->getSourceRange());
548 break;
549 case IncompatiblePointer:
550 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
551 rhsType.getAsString(), lhsType.getAsString(),
552 Fn->getSourceRange(), argExpr->getSourceRange());
553 break;
554 case CompatiblePointerDiscardsQualifiers:
555 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
556 rhsType.getAsString(), lhsType.getAsString(),
557 Fn->getSourceRange(), argExpr->getSourceRange());
558 break;
559 case Incompatible:
560 return Diag(l, diag::err_typecheck_passing_incompatible,
561 rhsType.getAsString(), lhsType.getAsString(),
562 Fn->getSourceRange(), argExpr->getSourceRange());
563 }
564 }
565 // Even if the types checked, bail if we had the wrong number of arguments.
566 if (NumArgsInCall != NumArgsInProto && !proto->isVariadic())
567 return true;
568 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000569
570 // Do special checking on direct calls to functions.
571 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
572 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
573 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000574 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args, NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000575 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000576
Chris Lattner4b009652007-07-25 00:24:17 +0000577 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
578}
579
580Action::ExprResult Sema::
581ParseCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
582 SourceLocation RParenLoc, ExprTy *InitExpr) {
583 assert((Ty != 0) && "ParseCompoundLiteral(): missing type");
584 QualType literalType = QualType::getFromOpaquePtr(Ty);
585 // FIXME: put back this assert when initializers are worked out.
586 //assert((InitExpr != 0) && "ParseCompoundLiteral(): missing expression");
587 Expr *literalExpr = static_cast<Expr*>(InitExpr);
588
589 // FIXME: add semantic analysis (C99 6.5.2.5).
590 return new CompoundLiteralExpr(literalType, literalExpr);
591}
592
593Action::ExprResult Sema::
594ParseInitList(SourceLocation LParenLoc, ExprTy **InitList, unsigned NumInit,
595 SourceLocation RParenLoc) {
596 // FIXME: add semantic analysis (C99 6.7.8). This involves
597 // knowledge of the object being intialized. As a result, the code for
598 // doing the semantic analysis will likely be located elsewhere (i.e. in
599 // consumers of InitListExpr (e.g. ParseDeclarator, ParseCompoundLiteral).
600 return false; // FIXME instantiate an InitListExpr.
601}
602
603Action::ExprResult Sema::
604ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
605 SourceLocation RParenLoc, ExprTy *Op) {
606 assert((Ty != 0) && (Op != 0) && "ParseCastExpr(): missing type or expr");
607
608 Expr *castExpr = static_cast<Expr*>(Op);
609 QualType castType = QualType::getFromOpaquePtr(Ty);
610
611 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
612 // type needs to be scalar.
613 if (!castType->isScalarType() && !castType->isVoidType()) {
614 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
615 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
616 }
617 if (!castExpr->getType()->isScalarType()) {
618 return Diag(castExpr->getLocStart(),
619 diag::err_typecheck_expect_scalar_operand,
620 castExpr->getType().getAsString(), castExpr->getSourceRange());
621 }
622 return new CastExpr(castType, castExpr, LParenLoc);
623}
624
625inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
626 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
627 UsualUnaryConversions(cond);
628 UsualUnaryConversions(lex);
629 UsualUnaryConversions(rex);
630 QualType condT = cond->getType();
631 QualType lexT = lex->getType();
632 QualType rexT = rex->getType();
633
634 // first, check the condition.
635 if (!condT->isScalarType()) { // C99 6.5.15p2
636 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
637 condT.getAsString());
638 return QualType();
639 }
640 // now check the two expressions.
641 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
642 UsualArithmeticConversions(lex, rex);
643 return lex->getType();
644 }
Chris Lattner71225142007-07-31 21:27:01 +0000645 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
646 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
647
648 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
649 return lexT;
650
Chris Lattner4b009652007-07-25 00:24:17 +0000651 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
652 lexT.getAsString(), rexT.getAsString(),
653 lex->getSourceRange(), rex->getSourceRange());
654 return QualType();
655 }
656 }
657 // C99 6.5.15p3
658 if (lexT->isPointerType() && rex->isNullPointerConstant(Context))
659 return lexT;
660 if (rexT->isPointerType() && lex->isNullPointerConstant(Context))
661 return rexT;
662
Chris Lattner71225142007-07-31 21:27:01 +0000663 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
664 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
665 // get the "pointed to" types
666 QualType lhptee = LHSPT->getPointeeType();
667 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000668
Chris Lattner71225142007-07-31 21:27:01 +0000669 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
670 if (lhptee->isVoidType() &&
671 (rhptee->isObjectType() || rhptee->isIncompleteType()))
672 return lexT;
673 if (rhptee->isVoidType() &&
674 (lhptee->isObjectType() || lhptee->isIncompleteType()))
675 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000676
Chris Lattner71225142007-07-31 21:27:01 +0000677 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
678 rhptee.getUnqualifiedType())) {
679 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
680 lexT.getAsString(), rexT.getAsString(),
681 lex->getSourceRange(), rex->getSourceRange());
682 return lexT; // FIXME: this is an _ext - is this return o.k?
683 }
684 // The pointer types are compatible.
685 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
686 // differently qualified versions of compatible types, the result type is a
687 // pointer to an appropriately qualified version of the *composite* type.
688 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000689 }
Chris Lattner4b009652007-07-25 00:24:17 +0000690 }
Chris Lattner71225142007-07-31 21:27:01 +0000691
Chris Lattner4b009652007-07-25 00:24:17 +0000692 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
693 return lexT;
694
695 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
696 lexT.getAsString(), rexT.getAsString(),
697 lex->getSourceRange(), rex->getSourceRange());
698 return QualType();
699}
700
701/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
702/// in the case of a the GNU conditional expr extension.
703Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
704 SourceLocation ColonLoc,
705 ExprTy *Cond, ExprTy *LHS,
706 ExprTy *RHS) {
707 Expr *CondExpr = (Expr *) Cond;
708 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
709 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
710 RHSExpr, QuestionLoc);
711 if (result.isNull())
712 return true;
713 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
714}
715
716// promoteExprToType - a helper function to ensure we create exactly one
717// ImplicitCastExpr. As a convenience (to the caller), we return the type.
718static void promoteExprToType(Expr *&expr, QualType type) {
719 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
720 impCast->setType(type);
721 else
722 expr = new ImplicitCastExpr(type, expr);
723 return;
724}
725
726/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
727void Sema::DefaultFunctionArrayConversion(Expr *&e) {
728 QualType t = e->getType();
729 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
730
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000731 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000732 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
733 t = e->getType();
734 }
735 if (t->isFunctionType())
736 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000737 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000738 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
739}
740
741/// UsualUnaryConversion - Performs various conversions that are common to most
742/// operators (C99 6.3). The conversions of array and function types are
743/// sometimes surpressed. For example, the array->pointer conversion doesn't
744/// apply if the array is an argument to the sizeof or address (&) operators.
745/// In these instances, this routine should *not* be called.
746void Sema::UsualUnaryConversions(Expr *&expr) {
747 QualType t = expr->getType();
748 assert(!t.isNull() && "UsualUnaryConversions - 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(expr, ref->getReferenceeType()); // C++ [expr]
752 t = expr->getType();
753 }
754 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
755 promoteExprToType(expr, Context.IntTy);
756 else
757 DefaultFunctionArrayConversion(expr);
758}
759
760/// UsualArithmeticConversions - Performs various conversions that are common to
761/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
762/// routine returns the first non-arithmetic type found. The client is
763/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000764QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
765 bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +0000766 UsualUnaryConversions(lhsExpr);
767 UsualUnaryConversions(rhsExpr);
768
769 QualType lhs = lhsExpr->getType();
770 QualType rhs = rhsExpr->getType();
771
772 // If both types are identical, no conversion is needed.
773 if (lhs == rhs)
Steve Naroff8f708362007-08-24 19:07:16 +0000774 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000775
776 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
777 // The caller can deal with this (e.g. pointer + int).
778 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000779 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000780
781 // At this point, we have two different arithmetic types.
782
783 // Handle complex types first (C99 6.3.1.8p1).
784 if (lhs->isComplexType() || rhs->isComplexType()) {
785 // if we have an integer operand, the result is the complex type.
786 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000787 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
788 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000789 }
790 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000791 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
792 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000793 }
794 // Two complex types. Convert the smaller operand to the bigger result.
795 if (Context.maxComplexType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000796 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
797 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000798 }
Steve Naroff8f708362007-08-24 19:07:16 +0000799 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
800 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000801 }
802 // Now handle "real" floating types (i.e. float, double, long double).
803 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
804 // if we have an integer operand, the result is the real floating type.
805 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000806 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
807 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000808 }
809 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000810 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
811 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000812 }
813 // We have two real floating types, float/complex combos were handled above.
814 // Convert the smaller operand to the bigger result.
815 if (Context.maxFloatingType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000816 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
817 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000818 }
Steve Naroff8f708362007-08-24 19:07:16 +0000819 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
820 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000821 }
822 // Finally, we have two differing integer types.
823 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000824 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
825 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000826 }
Steve Naroff8f708362007-08-24 19:07:16 +0000827 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
828 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000829}
830
831// CheckPointerTypesForAssignment - This is a very tricky routine (despite
832// being closely modeled after the C99 spec:-). The odd characteristic of this
833// routine is it effectively iqnores the qualifiers on the top level pointee.
834// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
835// FIXME: add a couple examples in this comment.
836Sema::AssignmentCheckResult
837Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
838 QualType lhptee, rhptee;
839
840 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +0000841 lhptee = lhsType->getAsPointerType()->getPointeeType();
842 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000843
844 // make sure we operate on the canonical type
845 lhptee = lhptee.getCanonicalType();
846 rhptee = rhptee.getCanonicalType();
847
848 AssignmentCheckResult r = Compatible;
849
850 // C99 6.5.16.1p1: This following citation is common to constraints
851 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
852 // qualifiers of the type *pointed to* by the right;
853 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
854 rhptee.getQualifiers())
855 r = CompatiblePointerDiscardsQualifiers;
856
857 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
858 // incomplete type and the other is a pointer to a qualified or unqualified
859 // version of void...
860 if (lhptee.getUnqualifiedType()->isVoidType() &&
861 (rhptee->isObjectType() || rhptee->isIncompleteType()))
862 ;
863 else if (rhptee.getUnqualifiedType()->isVoidType() &&
864 (lhptee->isObjectType() || lhptee->isIncompleteType()))
865 ;
866 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
867 // unqualified versions of compatible types, ...
868 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
869 rhptee.getUnqualifiedType()))
870 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
871 return r;
872}
873
874/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
875/// has code to accommodate several GCC extensions when type checking
876/// pointers. Here are some objectionable examples that GCC considers warnings:
877///
878/// int a, *pint;
879/// short *pshort;
880/// struct foo *pfoo;
881///
882/// pint = pshort; // warning: assignment from incompatible pointer type
883/// a = pint; // warning: assignment makes integer from pointer without a cast
884/// pint = a; // warning: assignment makes pointer from integer without a cast
885/// pint = pfoo; // warning: assignment from incompatible pointer type
886///
887/// As a result, the code for dealing with pointers is more complex than the
888/// C99 spec dictates.
889/// Note: the warning above turn into errors when -pedantic-errors is enabled.
890///
891Sema::AssignmentCheckResult
892Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
893 if (lhsType == rhsType) // common case, fast path...
894 return Compatible;
895
896 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
897 if (lhsType->isVectorType() || rhsType->isVectorType()) {
898 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
899 return Incompatible;
900 }
901 return Compatible;
902 } else if (lhsType->isPointerType()) {
903 if (rhsType->isIntegerType())
904 return PointerFromInt;
905
906 if (rhsType->isPointerType())
907 return CheckPointerTypesForAssignment(lhsType, rhsType);
908 } else if (rhsType->isPointerType()) {
909 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
910 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
911 return IntFromPointer;
912
913 if (lhsType->isPointerType())
914 return CheckPointerTypesForAssignment(lhsType, rhsType);
915 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
916 if (Type::tagTypesAreCompatible(lhsType, rhsType))
917 return Compatible;
918 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
919 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
920 return Compatible;
921 }
922 return Incompatible;
923}
924
925Sema::AssignmentCheckResult
926Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
927 // This check seems unnatural, however it is necessary to insure the proper
928 // conversion of functions/arrays. If the conversion were done for all
929 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
930 // expressions that surpress this implicit conversion (&, sizeof).
931 DefaultFunctionArrayConversion(rExpr);
932
933 return CheckAssignmentConstraints(lhsType, rExpr->getType());
934}
935
936Sema::AssignmentCheckResult
937Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
938 return CheckAssignmentConstraints(lhsType, rhsType);
939}
940
941inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
942 Diag(loc, diag::err_typecheck_invalid_operands,
943 lex->getType().getAsString(), rex->getType().getAsString(),
944 lex->getSourceRange(), rex->getSourceRange());
945}
946
947inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
948 Expr *&rex) {
949 QualType lhsType = lex->getType(), rhsType = rex->getType();
950
951 // make sure the vector types are identical.
952 if (lhsType == rhsType)
953 return lhsType;
954 // You cannot convert between vector values of different size.
955 Diag(loc, diag::err_typecheck_vector_not_convertable,
956 lex->getType().getAsString(), rex->getType().getAsString(),
957 lex->getSourceRange(), rex->getSourceRange());
958 return QualType();
959}
960
961inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +0000962 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +0000963{
964 QualType lhsType = lex->getType(), rhsType = rex->getType();
965
966 if (lhsType->isVectorType() || rhsType->isVectorType())
967 return CheckVectorOperands(loc, lex, rex);
968
Steve Naroff8f708362007-08-24 19:07:16 +0000969 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +0000970
Chris Lattner4b009652007-07-25 00:24:17 +0000971 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000972 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +0000973 InvalidOperands(loc, lex, rex);
974 return QualType();
975}
976
977inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +0000978 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +0000979{
980 QualType lhsType = lex->getType(), rhsType = rex->getType();
981
Steve Naroff8f708362007-08-24 19:07:16 +0000982 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +0000983
Chris Lattner4b009652007-07-25 00:24:17 +0000984 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +0000985 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +0000986 InvalidOperands(loc, lex, rex);
987 return QualType();
988}
989
990inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +0000991 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +0000992{
993 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
994 return CheckVectorOperands(loc, lex, rex);
995
Steve Naroff8f708362007-08-24 19:07:16 +0000996 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +0000997
998 // handle the common case first (both operands are arithmetic).
999 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001000 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001001
1002 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1003 return lex->getType();
1004 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1005 return rex->getType();
1006 InvalidOperands(loc, lex, rex);
1007 return QualType();
1008}
1009
1010inline QualType Sema::CheckSubtractionOperands( // 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())
Steve Naroff8f708362007-08-24 19:07:16 +00001023 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001024 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1025 return Context.getPointerDiffType();
1026 InvalidOperands(loc, lex, rex);
1027 return QualType();
1028}
1029
1030inline QualType Sema::CheckShiftOperands( // C99 6.5.7
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 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1034 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001035 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001036
1037 // handle the common case first (both operands are arithmetic).
1038 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001039 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001040 InvalidOperands(loc, lex, rex);
1041 return QualType();
1042}
1043
1044inline QualType Sema::CheckRelationalOperands( // C99 6.5.8
1045 Expr *&lex, Expr *&rex, SourceLocation loc)
1046{
Steve Naroffecc4fa12007-08-10 18:26:40 +00001047 // C99 6.5.8p3
1048 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1049 UsualArithmeticConversions(lex, rex);
1050 else {
1051 UsualUnaryConversions(lex);
1052 UsualUnaryConversions(rex);
1053 }
Chris Lattner4b009652007-07-25 00:24:17 +00001054 QualType lType = lex->getType();
1055 QualType rType = rex->getType();
1056
1057 if (lType->isRealType() && rType->isRealType())
1058 return Context.IntTy;
1059
Steve Naroff4462cb02007-08-16 21:48:38 +00001060 // All of the following pointer related warnings are GCC extensions. One
1061 // day, we can consider making them errors (when -pedantic-errors is enabled).
1062 if (lType->isPointerType() && rType->isPointerType()) {
1063 if (!Type::pointerTypesAreCompatible(lType, rType)) {
1064 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1065 lType.getAsString(), rType.getAsString(),
1066 lex->getSourceRange(), rex->getSourceRange());
1067 promoteExprToType(rex, lType); // promote the pointer to pointer
Chris Lattner4b009652007-07-25 00:24:17 +00001068 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001069 return Context.IntTy;
1070 }
1071 if (lType->isPointerType() && rType->isIntegerType()) {
1072 if (!rex->isNullPointerConstant(Context)) {
1073 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1074 lType.getAsString(), rType.getAsString(),
1075 lex->getSourceRange(), rex->getSourceRange());
1076 promoteExprToType(rex, lType); // promote the integer to pointer
Chris Lattner4b009652007-07-25 00:24:17 +00001077 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001078 return Context.IntTy;
1079 }
1080 if (lType->isIntegerType() && rType->isPointerType()) {
1081 if (!lex->isNullPointerConstant(Context)) {
1082 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1083 lType.getAsString(), rType.getAsString(),
1084 lex->getSourceRange(), rex->getSourceRange());
1085 promoteExprToType(lex, rType); // promote the integer to pointer
1086 }
1087 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001088 }
1089 InvalidOperands(loc, lex, rex);
1090 return QualType();
1091}
1092
1093inline QualType Sema::CheckEqualityOperands( // C99 6.5.9
1094 Expr *&lex, Expr *&rex, SourceLocation loc)
1095{
Steve Naroffecc4fa12007-08-10 18:26:40 +00001096 // C99 6.5.9p4
1097 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1098 UsualArithmeticConversions(lex, rex);
1099 else {
1100 UsualUnaryConversions(lex);
1101 UsualUnaryConversions(rex);
1102 }
Chris Lattner4b009652007-07-25 00:24:17 +00001103 QualType lType = lex->getType();
1104 QualType rType = rex->getType();
1105
1106 if (lType->isArithmeticType() && rType->isArithmeticType())
1107 return Context.IntTy;
1108
Steve Naroff4462cb02007-08-16 21:48:38 +00001109 // All of the following pointer related warnings are GCC extensions. One
1110 // day, we can consider making them errors (when -pedantic-errors is enabled).
1111 if (lType->isPointerType() && rType->isPointerType()) {
1112 if (!Type::pointerTypesAreCompatible(lType, rType)) {
1113 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1114 lType.getAsString(), rType.getAsString(),
1115 lex->getSourceRange(), rex->getSourceRange());
1116 promoteExprToType(rex, lType); // promote the pointer to pointer
Chris Lattner4b009652007-07-25 00:24:17 +00001117 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001118 return Context.IntTy;
1119 }
1120 if (lType->isPointerType() && rType->isIntegerType()) {
1121 if (!rex->isNullPointerConstant(Context)) {
1122 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1123 lType.getAsString(), rType.getAsString(),
1124 lex->getSourceRange(), rex->getSourceRange());
1125 promoteExprToType(rex, lType); // promote the integer to pointer
Chris Lattner4b009652007-07-25 00:24:17 +00001126 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001127 return Context.IntTy;
1128 }
1129 if (lType->isIntegerType() && rType->isPointerType()) {
1130 if (!lex->isNullPointerConstant(Context)) {
1131 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1132 lType.getAsString(), rType.getAsString(),
1133 lex->getSourceRange(), rex->getSourceRange());
1134 promoteExprToType(lex, rType); // promote the integer to pointer
1135 }
1136 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001137 }
1138 InvalidOperands(loc, lex, rex);
1139 return QualType();
1140}
1141
1142inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001143 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001144{
1145 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1146 return CheckVectorOperands(loc, lex, rex);
1147
Steve Naroff8f708362007-08-24 19:07:16 +00001148 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001149
1150 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001151 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001152 InvalidOperands(loc, lex, rex);
1153 return QualType();
1154}
1155
1156inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1157 Expr *&lex, Expr *&rex, SourceLocation loc)
1158{
1159 UsualUnaryConversions(lex);
1160 UsualUnaryConversions(rex);
1161
1162 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1163 return Context.IntTy;
1164 InvalidOperands(loc, lex, rex);
1165 return QualType();
1166}
1167
1168inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
1169 Expr *lex, Expr *rex, SourceLocation loc, QualType compoundType)
1170{
1171 QualType lhsType = lex->getType();
1172 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1173 bool hadError = false;
1174 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1175
1176 switch (mlval) { // C99 6.5.16p2
1177 case Expr::MLV_Valid:
1178 break;
1179 case Expr::MLV_ConstQualified:
1180 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1181 hadError = true;
1182 break;
1183 case Expr::MLV_ArrayType:
1184 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1185 lhsType.getAsString(), lex->getSourceRange());
1186 return QualType();
1187 case Expr::MLV_NotObjectType:
1188 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1189 lhsType.getAsString(), lex->getSourceRange());
1190 return QualType();
1191 case Expr::MLV_InvalidExpression:
1192 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1193 lex->getSourceRange());
1194 return QualType();
1195 case Expr::MLV_IncompleteType:
1196 case Expr::MLV_IncompleteVoidType:
1197 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1198 lhsType.getAsString(), lex->getSourceRange());
1199 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001200 case Expr::MLV_DuplicateVectorComponents:
1201 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1202 lex->getSourceRange());
1203 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001204 }
1205 AssignmentCheckResult result;
1206
1207 if (compoundType.isNull())
1208 result = CheckSingleAssignmentConstraints(lhsType, rex);
1209 else
1210 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001211
Chris Lattner4b009652007-07-25 00:24:17 +00001212 // decode the result (notice that extensions still return a type).
1213 switch (result) {
1214 case Compatible:
1215 break;
1216 case Incompatible:
1217 Diag(loc, diag::err_typecheck_assign_incompatible,
1218 lhsType.getAsString(), rhsType.getAsString(),
1219 lex->getSourceRange(), rex->getSourceRange());
1220 hadError = true;
1221 break;
1222 case PointerFromInt:
1223 // check for null pointer constant (C99 6.3.2.3p3)
1224 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1225 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1226 lhsType.getAsString(), rhsType.getAsString(),
1227 lex->getSourceRange(), rex->getSourceRange());
1228 }
1229 break;
1230 case IntFromPointer:
1231 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1232 lhsType.getAsString(), rhsType.getAsString(),
1233 lex->getSourceRange(), rex->getSourceRange());
1234 break;
1235 case IncompatiblePointer:
1236 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1237 lhsType.getAsString(), rhsType.getAsString(),
1238 lex->getSourceRange(), rex->getSourceRange());
1239 break;
1240 case CompatiblePointerDiscardsQualifiers:
1241 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1242 lhsType.getAsString(), rhsType.getAsString(),
1243 lex->getSourceRange(), rex->getSourceRange());
1244 break;
1245 }
1246 // C99 6.5.16p3: The type of an assignment expression is the type of the
1247 // left operand unless the left operand has qualified type, in which case
1248 // it is the unqualified version of the type of the left operand.
1249 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1250 // is converted to the type of the assignment expression (above).
1251 // C++ 5.17p1: the type of the assignment expression is that of its left oprdu.
1252 return hadError ? QualType() : lhsType.getUnqualifiedType();
1253}
1254
1255inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1256 Expr *&lex, Expr *&rex, SourceLocation loc) {
1257 UsualUnaryConversions(rex);
1258 return rex->getType();
1259}
1260
1261/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1262/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1263QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1264 QualType resType = op->getType();
1265 assert(!resType.isNull() && "no type for increment/decrement expression");
1266
Steve Naroffd30e1932007-08-24 17:20:07 +00001267 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattner4b009652007-07-25 00:24:17 +00001268 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1269 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1270 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1271 resType.getAsString(), op->getSourceRange());
1272 return QualType();
1273 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001274 } else if (!resType->isRealType()) {
1275 if (resType->isComplexType())
1276 // C99 does not support ++/-- on complex types.
1277 Diag(OpLoc, diag::ext_integer_increment_complex,
1278 resType.getAsString(), op->getSourceRange());
1279 else {
1280 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1281 resType.getAsString(), op->getSourceRange());
1282 return QualType();
1283 }
Chris Lattner4b009652007-07-25 00:24:17 +00001284 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001285 // At this point, we know we have a real, complex or pointer type.
1286 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001287 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1288 if (mlval != Expr::MLV_Valid) {
1289 // FIXME: emit a more precise diagnostic...
1290 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1291 op->getSourceRange());
1292 return QualType();
1293 }
1294 return resType;
1295}
1296
1297/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1298/// This routine allows us to typecheck complex/recursive expressions
1299/// where the declaration is needed for type checking. Here are some
1300/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1301static Decl *getPrimaryDeclaration(Expr *e) {
1302 switch (e->getStmtClass()) {
1303 case Stmt::DeclRefExprClass:
1304 return cast<DeclRefExpr>(e)->getDecl();
1305 case Stmt::MemberExprClass:
1306 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1307 case Stmt::ArraySubscriptExprClass:
1308 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1309 case Stmt::CallExprClass:
1310 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1311 case Stmt::UnaryOperatorClass:
1312 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1313 case Stmt::ParenExprClass:
1314 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1315 default:
1316 return 0;
1317 }
1318}
1319
1320/// CheckAddressOfOperand - The operand of & must be either a function
1321/// designator or an lvalue designating an object. If it is an lvalue, the
1322/// object cannot be declared with storage class register or be a bit field.
1323/// Note: The usual conversions are *not* applied to the operand of the &
1324/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1325QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1326 Decl *dcl = getPrimaryDeclaration(op);
1327 Expr::isLvalueResult lval = op->isLvalue();
1328
1329 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1330 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1331 ;
1332 else { // FIXME: emit more specific diag...
1333 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1334 op->getSourceRange());
1335 return QualType();
1336 }
1337 } else if (dcl) {
1338 // We have an lvalue with a decl. Make sure the decl is not declared
1339 // with the register storage-class specifier.
1340 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1341 if (vd->getStorageClass() == VarDecl::Register) {
1342 Diag(OpLoc, diag::err_typecheck_address_of_register,
1343 op->getSourceRange());
1344 return QualType();
1345 }
1346 } else
1347 assert(0 && "Unknown/unexpected decl type");
1348
1349 // FIXME: add check for bitfields!
1350 }
1351 // If the operand has type "type", the result has type "pointer to type".
1352 return Context.getPointerType(op->getType());
1353}
1354
1355QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1356 UsualUnaryConversions(op);
1357 QualType qType = op->getType();
1358
Chris Lattner7931f4a2007-07-31 16:53:04 +00001359 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001360 QualType ptype = PT->getPointeeType();
1361 // C99 6.5.3.2p4. "if it points to an object,...".
1362 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1363 // GCC compat: special case 'void *' (treat as warning).
1364 if (ptype->isVoidType()) {
1365 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1366 qType.getAsString(), op->getSourceRange());
1367 } else {
1368 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1369 ptype.getAsString(), op->getSourceRange());
1370 return QualType();
1371 }
1372 }
1373 return ptype;
1374 }
1375 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1376 qType.getAsString(), op->getSourceRange());
1377 return QualType();
1378}
1379
1380static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1381 tok::TokenKind Kind) {
1382 BinaryOperator::Opcode Opc;
1383 switch (Kind) {
1384 default: assert(0 && "Unknown binop!");
1385 case tok::star: Opc = BinaryOperator::Mul; break;
1386 case tok::slash: Opc = BinaryOperator::Div; break;
1387 case tok::percent: Opc = BinaryOperator::Rem; break;
1388 case tok::plus: Opc = BinaryOperator::Add; break;
1389 case tok::minus: Opc = BinaryOperator::Sub; break;
1390 case tok::lessless: Opc = BinaryOperator::Shl; break;
1391 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1392 case tok::lessequal: Opc = BinaryOperator::LE; break;
1393 case tok::less: Opc = BinaryOperator::LT; break;
1394 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1395 case tok::greater: Opc = BinaryOperator::GT; break;
1396 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1397 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1398 case tok::amp: Opc = BinaryOperator::And; break;
1399 case tok::caret: Opc = BinaryOperator::Xor; break;
1400 case tok::pipe: Opc = BinaryOperator::Or; break;
1401 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1402 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1403 case tok::equal: Opc = BinaryOperator::Assign; break;
1404 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1405 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1406 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1407 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1408 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1409 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1410 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1411 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1412 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1413 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1414 case tok::comma: Opc = BinaryOperator::Comma; break;
1415 }
1416 return Opc;
1417}
1418
1419static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1420 tok::TokenKind Kind) {
1421 UnaryOperator::Opcode Opc;
1422 switch (Kind) {
1423 default: assert(0 && "Unknown unary op!");
1424 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1425 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1426 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1427 case tok::star: Opc = UnaryOperator::Deref; break;
1428 case tok::plus: Opc = UnaryOperator::Plus; break;
1429 case tok::minus: Opc = UnaryOperator::Minus; break;
1430 case tok::tilde: Opc = UnaryOperator::Not; break;
1431 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1432 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1433 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1434 case tok::kw___real: Opc = UnaryOperator::Real; break;
1435 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1436 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1437 }
1438 return Opc;
1439}
1440
1441// Binary Operators. 'Tok' is the token for the operator.
1442Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1443 ExprTy *LHS, ExprTy *RHS) {
1444 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1445 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1446
1447 assert((lhs != 0) && "ParseBinOp(): missing left expression");
1448 assert((rhs != 0) && "ParseBinOp(): missing right expression");
1449
1450 QualType ResultTy; // Result type of the binary operator.
1451 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1452
1453 switch (Opc) {
1454 default:
1455 assert(0 && "Unknown binary expr!");
1456 case BinaryOperator::Assign:
1457 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1458 break;
1459 case BinaryOperator::Mul:
1460 case BinaryOperator::Div:
1461 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1462 break;
1463 case BinaryOperator::Rem:
1464 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1465 break;
1466 case BinaryOperator::Add:
1467 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1468 break;
1469 case BinaryOperator::Sub:
1470 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1471 break;
1472 case BinaryOperator::Shl:
1473 case BinaryOperator::Shr:
1474 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1475 break;
1476 case BinaryOperator::LE:
1477 case BinaryOperator::LT:
1478 case BinaryOperator::GE:
1479 case BinaryOperator::GT:
1480 ResultTy = CheckRelationalOperands(lhs, rhs, TokLoc);
1481 break;
1482 case BinaryOperator::EQ:
1483 case BinaryOperator::NE:
1484 ResultTy = CheckEqualityOperands(lhs, rhs, TokLoc);
1485 break;
1486 case BinaryOperator::And:
1487 case BinaryOperator::Xor:
1488 case BinaryOperator::Or:
1489 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1490 break;
1491 case BinaryOperator::LAnd:
1492 case BinaryOperator::LOr:
1493 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1494 break;
1495 case BinaryOperator::MulAssign:
1496 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001497 CompTy = CheckMultiplyDivideOperands(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::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001502 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001503 if (!CompTy.isNull())
1504 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1505 break;
1506 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001507 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001508 if (!CompTy.isNull())
1509 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1510 break;
1511 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001512 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001513 if (!CompTy.isNull())
1514 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1515 break;
1516 case BinaryOperator::ShlAssign:
1517 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001518 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001519 if (!CompTy.isNull())
1520 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1521 break;
1522 case BinaryOperator::AndAssign:
1523 case BinaryOperator::XorAssign:
1524 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001525 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001526 if (!CompTy.isNull())
1527 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1528 break;
1529 case BinaryOperator::Comma:
1530 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1531 break;
1532 }
1533 if (ResultTy.isNull())
1534 return true;
1535 if (CompTy.isNull())
1536 return new BinaryOperator(lhs, rhs, Opc, ResultTy);
1537 else
1538 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy);
1539}
1540
1541// Unary Operators. 'Tok' is the token for the operator.
1542Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1543 ExprTy *input) {
1544 Expr *Input = (Expr*)input;
1545 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1546 QualType resultType;
1547 switch (Opc) {
1548 default:
1549 assert(0 && "Unimplemented unary expr!");
1550 case UnaryOperator::PreInc:
1551 case UnaryOperator::PreDec:
1552 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1553 break;
1554 case UnaryOperator::AddrOf:
1555 resultType = CheckAddressOfOperand(Input, OpLoc);
1556 break;
1557 case UnaryOperator::Deref:
1558 resultType = CheckIndirectionOperand(Input, OpLoc);
1559 break;
1560 case UnaryOperator::Plus:
1561 case UnaryOperator::Minus:
1562 UsualUnaryConversions(Input);
1563 resultType = Input->getType();
1564 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1565 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1566 resultType.getAsString());
1567 break;
1568 case UnaryOperator::Not: // bitwise complement
1569 UsualUnaryConversions(Input);
1570 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001571 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1572 if (!resultType->isIntegerType()) {
1573 if (resultType->isComplexType())
1574 // C99 does not support '~' for complex conjugation.
1575 Diag(OpLoc, diag::ext_integer_complement_complex,
1576 resultType.getAsString());
1577 else
1578 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1579 resultType.getAsString());
1580 }
Chris Lattner4b009652007-07-25 00:24:17 +00001581 break;
1582 case UnaryOperator::LNot: // logical negation
1583 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1584 DefaultFunctionArrayConversion(Input);
1585 resultType = Input->getType();
1586 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1587 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1588 resultType.getAsString());
1589 // LNot always has type int. C99 6.5.3.3p5.
1590 resultType = Context.IntTy;
1591 break;
1592 case UnaryOperator::SizeOf:
1593 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1594 break;
1595 case UnaryOperator::AlignOf:
1596 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1597 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001598 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001599 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001600 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001601 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001602 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001603 resultType = Input->getType();
1604 break;
1605 }
1606 if (resultType.isNull())
1607 return true;
1608 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1609}
1610
1611/// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
1612Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
1613 SourceLocation LabLoc,
1614 IdentifierInfo *LabelII) {
1615 // Look up the record for this label identifier.
1616 LabelStmt *&LabelDecl = LabelMap[LabelII];
1617
1618 // If we haven't seen this label yet, create a forward reference.
1619 if (LabelDecl == 0)
1620 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1621
1622 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001623 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1624 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001625}
1626
1627Sema::ExprResult Sema::ParseStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
1628 SourceLocation RPLoc) { // "({..})"
1629 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1630 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1631 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1632
1633 // FIXME: there are a variety of strange constraints to enforce here, for
1634 // example, it is not possible to goto into a stmt expression apparently.
1635 // More semantic analysis is needed.
1636
1637 // FIXME: the last statement in the compount stmt has its value used. We
1638 // should not warn about it being unused.
1639
1640 // If there are sub stmts in the compound stmt, take the type of the last one
1641 // as the type of the stmtexpr.
1642 QualType Ty = Context.VoidTy;
1643
1644 if (!Compound->body_empty())
1645 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1646 Ty = LastExpr->getType();
1647
1648 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1649}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001650
Steve Naroff5b528922007-08-01 23:45:51 +00001651Sema::ExprResult Sema::ParseTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001652 TypeTy *arg1, TypeTy *arg2,
1653 SourceLocation RPLoc) {
1654 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1655 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1656
1657 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1658
Steve Naroff5b528922007-08-01 23:45:51 +00001659 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001660}
1661
Steve Naroff93c53012007-08-03 21:21:27 +00001662Sema::ExprResult Sema::ParseChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
1663 ExprTy *expr1, ExprTy *expr2,
1664 SourceLocation RPLoc) {
1665 Expr *CondExpr = static_cast<Expr*>(cond);
1666 Expr *LHSExpr = static_cast<Expr*>(expr1);
1667 Expr *RHSExpr = static_cast<Expr*>(expr2);
1668
1669 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1670
1671 // The conditional expression is required to be a constant expression.
1672 llvm::APSInt condEval(32);
1673 SourceLocation ExpLoc;
1674 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1675 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1676 CondExpr->getSourceRange());
1677
1678 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1679 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1680 RHSExpr->getType();
1681 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1682}
1683
Anders Carlssona66cad42007-08-21 17:43:55 +00001684// TODO: Move this to SemaObjC.cpp
Anders Carlsson8be1d402007-08-22 15:14:15 +00001685Sema::ExprResult Sema::ParseObjCStringLiteral(ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00001686 StringLiteral* S = static_cast<StringLiteral *>(string);
1687
1688 if (CheckBuiltinCFStringArgument(S))
1689 return true;
1690
1691 QualType t = Context.getCFConstantStringType();
1692 t = t.getQualifiedType(QualType::Const);
1693 t = Context.getPointerType(t);
1694
1695 return new ObjCStringLiteral(S, t);
1696}
Anders Carlsson8be1d402007-08-22 15:14:15 +00001697
1698Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1699 SourceLocation LParenLoc,
1700 TypeTy *Ty,
1701 SourceLocation RParenLoc) {
1702 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
1703
1704 QualType t = Context.getPointerType(Context.CharTy);
1705 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
1706}