blob: 7666ad0474d4cbce7c6858ac5741ca0be8ffc5d4 [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);
Steve Naroff0f32f432007-08-24 22:33:52 +0000530 if (Args[i] != argExpr) // The expression was converted.
531 Args[i] = argExpr; // Make sure we store the converted expression.
Chris Lattner4b009652007-07-25 00:24:17 +0000532 SourceLocation l = argExpr->getLocStart();
533
534 // decode the result (notice that AST's are still created for extensions).
535 switch (result) {
536 case Compatible:
537 break;
538 case PointerFromInt:
539 // check for null pointer constant (C99 6.3.2.3p3)
540 if (!argExpr->isNullPointerConstant(Context)) {
541 Diag(l, diag::ext_typecheck_passing_pointer_int,
542 lhsType.getAsString(), rhsType.getAsString(),
543 Fn->getSourceRange(), argExpr->getSourceRange());
544 }
545 break;
546 case IntFromPointer:
547 Diag(l, diag::ext_typecheck_passing_pointer_int,
548 lhsType.getAsString(), rhsType.getAsString(),
549 Fn->getSourceRange(), argExpr->getSourceRange());
550 break;
551 case IncompatiblePointer:
552 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
553 rhsType.getAsString(), lhsType.getAsString(),
554 Fn->getSourceRange(), argExpr->getSourceRange());
555 break;
556 case CompatiblePointerDiscardsQualifiers:
557 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
558 rhsType.getAsString(), lhsType.getAsString(),
559 Fn->getSourceRange(), argExpr->getSourceRange());
560 break;
561 case Incompatible:
562 return Diag(l, diag::err_typecheck_passing_incompatible,
563 rhsType.getAsString(), lhsType.getAsString(),
564 Fn->getSourceRange(), argExpr->getSourceRange());
565 }
566 }
567 // Even if the types checked, bail if we had the wrong number of arguments.
568 if (NumArgsInCall != NumArgsInProto && !proto->isVariadic())
569 return true;
570 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000571
572 // Do special checking on direct calls to functions.
573 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
574 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
575 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000576 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args, NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000577 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000578
Chris Lattner4b009652007-07-25 00:24:17 +0000579 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
580}
581
582Action::ExprResult Sema::
583ParseCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
584 SourceLocation RParenLoc, ExprTy *InitExpr) {
585 assert((Ty != 0) && "ParseCompoundLiteral(): missing type");
586 QualType literalType = QualType::getFromOpaquePtr(Ty);
587 // FIXME: put back this assert when initializers are worked out.
588 //assert((InitExpr != 0) && "ParseCompoundLiteral(): missing expression");
589 Expr *literalExpr = static_cast<Expr*>(InitExpr);
590
591 // FIXME: add semantic analysis (C99 6.5.2.5).
592 return new CompoundLiteralExpr(literalType, literalExpr);
593}
594
595Action::ExprResult Sema::
596ParseInitList(SourceLocation LParenLoc, ExprTy **InitList, unsigned NumInit,
597 SourceLocation RParenLoc) {
598 // FIXME: add semantic analysis (C99 6.7.8). This involves
599 // knowledge of the object being intialized. As a result, the code for
600 // doing the semantic analysis will likely be located elsewhere (i.e. in
601 // consumers of InitListExpr (e.g. ParseDeclarator, ParseCompoundLiteral).
602 return false; // FIXME instantiate an InitListExpr.
603}
604
605Action::ExprResult Sema::
606ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
607 SourceLocation RParenLoc, ExprTy *Op) {
608 assert((Ty != 0) && (Op != 0) && "ParseCastExpr(): missing type or expr");
609
610 Expr *castExpr = static_cast<Expr*>(Op);
611 QualType castType = QualType::getFromOpaquePtr(Ty);
612
613 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
614 // type needs to be scalar.
615 if (!castType->isScalarType() && !castType->isVoidType()) {
616 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
617 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
618 }
619 if (!castExpr->getType()->isScalarType()) {
620 return Diag(castExpr->getLocStart(),
621 diag::err_typecheck_expect_scalar_operand,
622 castExpr->getType().getAsString(), castExpr->getSourceRange());
623 }
624 return new CastExpr(castType, castExpr, LParenLoc);
625}
626
627inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
628 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
629 UsualUnaryConversions(cond);
630 UsualUnaryConversions(lex);
631 UsualUnaryConversions(rex);
632 QualType condT = cond->getType();
633 QualType lexT = lex->getType();
634 QualType rexT = rex->getType();
635
636 // first, check the condition.
637 if (!condT->isScalarType()) { // C99 6.5.15p2
638 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
639 condT.getAsString());
640 return QualType();
641 }
642 // now check the two expressions.
643 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
644 UsualArithmeticConversions(lex, rex);
645 return lex->getType();
646 }
Chris Lattner71225142007-07-31 21:27:01 +0000647 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
648 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
649
650 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
651 return lexT;
652
Chris Lattner4b009652007-07-25 00:24:17 +0000653 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
654 lexT.getAsString(), rexT.getAsString(),
655 lex->getSourceRange(), rex->getSourceRange());
656 return QualType();
657 }
658 }
659 // C99 6.5.15p3
660 if (lexT->isPointerType() && rex->isNullPointerConstant(Context))
661 return lexT;
662 if (rexT->isPointerType() && lex->isNullPointerConstant(Context))
663 return rexT;
664
Chris Lattner71225142007-07-31 21:27:01 +0000665 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
666 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
667 // get the "pointed to" types
668 QualType lhptee = LHSPT->getPointeeType();
669 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000670
Chris Lattner71225142007-07-31 21:27:01 +0000671 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
672 if (lhptee->isVoidType() &&
673 (rhptee->isObjectType() || rhptee->isIncompleteType()))
674 return lexT;
675 if (rhptee->isVoidType() &&
676 (lhptee->isObjectType() || lhptee->isIncompleteType()))
677 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000678
Chris Lattner71225142007-07-31 21:27:01 +0000679 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
680 rhptee.getUnqualifiedType())) {
681 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
682 lexT.getAsString(), rexT.getAsString(),
683 lex->getSourceRange(), rex->getSourceRange());
684 return lexT; // FIXME: this is an _ext - is this return o.k?
685 }
686 // The pointer types are compatible.
687 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
688 // differently qualified versions of compatible types, the result type is a
689 // pointer to an appropriately qualified version of the *composite* type.
690 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000691 }
Chris Lattner4b009652007-07-25 00:24:17 +0000692 }
Chris Lattner71225142007-07-31 21:27:01 +0000693
Chris Lattner4b009652007-07-25 00:24:17 +0000694 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
695 return lexT;
696
697 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
698 lexT.getAsString(), rexT.getAsString(),
699 lex->getSourceRange(), rex->getSourceRange());
700 return QualType();
701}
702
703/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
704/// in the case of a the GNU conditional expr extension.
705Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
706 SourceLocation ColonLoc,
707 ExprTy *Cond, ExprTy *LHS,
708 ExprTy *RHS) {
709 Expr *CondExpr = (Expr *) Cond;
710 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
711 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
712 RHSExpr, QuestionLoc);
713 if (result.isNull())
714 return true;
715 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
716}
717
718// promoteExprToType - a helper function to ensure we create exactly one
719// ImplicitCastExpr. As a convenience (to the caller), we return the type.
720static void promoteExprToType(Expr *&expr, QualType type) {
721 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
722 impCast->setType(type);
723 else
724 expr = new ImplicitCastExpr(type, expr);
725 return;
726}
727
728/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
729void Sema::DefaultFunctionArrayConversion(Expr *&e) {
730 QualType t = e->getType();
731 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
732
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000733 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000734 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
735 t = e->getType();
736 }
737 if (t->isFunctionType())
738 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000739 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000740 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
741}
742
743/// UsualUnaryConversion - Performs various conversions that are common to most
744/// operators (C99 6.3). The conversions of array and function types are
745/// sometimes surpressed. For example, the array->pointer conversion doesn't
746/// apply if the array is an argument to the sizeof or address (&) operators.
747/// In these instances, this routine should *not* be called.
748void Sema::UsualUnaryConversions(Expr *&expr) {
749 QualType t = expr->getType();
750 assert(!t.isNull() && "UsualUnaryConversions - missing type");
751
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000752 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000753 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
754 t = expr->getType();
755 }
756 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
757 promoteExprToType(expr, Context.IntTy);
758 else
759 DefaultFunctionArrayConversion(expr);
760}
761
762/// UsualArithmeticConversions - Performs various conversions that are common to
763/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
764/// routine returns the first non-arithmetic type found. The client is
765/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000766QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
767 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000768 if (!isCompAssign) {
769 UsualUnaryConversions(lhsExpr);
770 UsualUnaryConversions(rhsExpr);
771 }
Chris Lattner4b009652007-07-25 00:24:17 +0000772 QualType lhs = lhsExpr->getType();
773 QualType rhs = rhsExpr->getType();
774
775 // If both types are identical, no conversion is needed.
776 if (lhs == rhs)
Steve Naroff8f708362007-08-24 19:07:16 +0000777 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000778
779 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
780 // The caller can deal with this (e.g. pointer + int).
781 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000782 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000783
784 // At this point, we have two different arithmetic types.
785
786 // Handle complex types first (C99 6.3.1.8p1).
787 if (lhs->isComplexType() || rhs->isComplexType()) {
788 // if we have an integer operand, the result is the complex type.
789 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000790 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
791 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000792 }
793 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000794 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
795 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000796 }
797 // Two complex types. Convert the smaller operand to the bigger result.
798 if (Context.maxComplexType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000799 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
800 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000801 }
Steve Naroff8f708362007-08-24 19:07:16 +0000802 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
803 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000804 }
805 // Now handle "real" floating types (i.e. float, double, long double).
806 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
807 // if we have an integer operand, the result is the real floating type.
808 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000809 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
810 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000811 }
812 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000813 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
814 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000815 }
816 // We have two real floating types, float/complex combos were handled above.
817 // Convert the smaller operand to the bigger result.
818 if (Context.maxFloatingType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000819 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
820 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000821 }
Steve Naroff8f708362007-08-24 19:07:16 +0000822 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
823 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000824 }
825 // Finally, we have two differing integer types.
826 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000827 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
828 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000829 }
Steve Naroff8f708362007-08-24 19:07:16 +0000830 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
831 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000832}
833
834// CheckPointerTypesForAssignment - This is a very tricky routine (despite
835// being closely modeled after the C99 spec:-). The odd characteristic of this
836// routine is it effectively iqnores the qualifiers on the top level pointee.
837// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
838// FIXME: add a couple examples in this comment.
839Sema::AssignmentCheckResult
840Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
841 QualType lhptee, rhptee;
842
843 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +0000844 lhptee = lhsType->getAsPointerType()->getPointeeType();
845 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000846
847 // make sure we operate on the canonical type
848 lhptee = lhptee.getCanonicalType();
849 rhptee = rhptee.getCanonicalType();
850
851 AssignmentCheckResult r = Compatible;
852
853 // C99 6.5.16.1p1: This following citation is common to constraints
854 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
855 // qualifiers of the type *pointed to* by the right;
856 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
857 rhptee.getQualifiers())
858 r = CompatiblePointerDiscardsQualifiers;
859
860 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
861 // incomplete type and the other is a pointer to a qualified or unqualified
862 // version of void...
863 if (lhptee.getUnqualifiedType()->isVoidType() &&
864 (rhptee->isObjectType() || rhptee->isIncompleteType()))
865 ;
866 else if (rhptee.getUnqualifiedType()->isVoidType() &&
867 (lhptee->isObjectType() || lhptee->isIncompleteType()))
868 ;
869 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
870 // unqualified versions of compatible types, ...
871 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
872 rhptee.getUnqualifiedType()))
873 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
874 return r;
875}
876
877/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
878/// has code to accommodate several GCC extensions when type checking
879/// pointers. Here are some objectionable examples that GCC considers warnings:
880///
881/// int a, *pint;
882/// short *pshort;
883/// struct foo *pfoo;
884///
885/// pint = pshort; // warning: assignment from incompatible pointer type
886/// a = pint; // warning: assignment makes integer from pointer without a cast
887/// pint = a; // warning: assignment makes pointer from integer without a cast
888/// pint = pfoo; // warning: assignment from incompatible pointer type
889///
890/// As a result, the code for dealing with pointers is more complex than the
891/// C99 spec dictates.
892/// Note: the warning above turn into errors when -pedantic-errors is enabled.
893///
894Sema::AssignmentCheckResult
895Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
896 if (lhsType == rhsType) // common case, fast path...
897 return Compatible;
898
899 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
900 if (lhsType->isVectorType() || rhsType->isVectorType()) {
901 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
902 return Incompatible;
903 }
904 return Compatible;
905 } else if (lhsType->isPointerType()) {
906 if (rhsType->isIntegerType())
907 return PointerFromInt;
908
909 if (rhsType->isPointerType())
910 return CheckPointerTypesForAssignment(lhsType, rhsType);
911 } else if (rhsType->isPointerType()) {
912 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
913 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
914 return IntFromPointer;
915
916 if (lhsType->isPointerType())
917 return CheckPointerTypesForAssignment(lhsType, rhsType);
918 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
919 if (Type::tagTypesAreCompatible(lhsType, rhsType))
920 return Compatible;
921 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
922 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
923 return Compatible;
924 }
925 return Incompatible;
926}
927
928Sema::AssignmentCheckResult
929Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
930 // This check seems unnatural, however it is necessary to insure the proper
931 // conversion of functions/arrays. If the conversion were done for all
932 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
933 // expressions that surpress this implicit conversion (&, sizeof).
934 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000935
936 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +0000937
Steve Naroff0f32f432007-08-24 22:33:52 +0000938 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
939
940 // C99 6.5.16.1p2: The value of the right operand is converted to the
941 // type of the assignment expression.
942 if (rExpr->getType() != lhsType)
943 promoteExprToType(rExpr, lhsType);
944 return result;
Chris Lattner4b009652007-07-25 00:24:17 +0000945}
946
947Sema::AssignmentCheckResult
948Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
949 return CheckAssignmentConstraints(lhsType, rhsType);
950}
951
952inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
953 Diag(loc, diag::err_typecheck_invalid_operands,
954 lex->getType().getAsString(), rex->getType().getAsString(),
955 lex->getSourceRange(), rex->getSourceRange());
956}
957
958inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
959 Expr *&rex) {
960 QualType lhsType = lex->getType(), rhsType = rex->getType();
961
962 // make sure the vector types are identical.
963 if (lhsType == rhsType)
964 return lhsType;
965 // You cannot convert between vector values of different size.
966 Diag(loc, diag::err_typecheck_vector_not_convertable,
967 lex->getType().getAsString(), rex->getType().getAsString(),
968 lex->getSourceRange(), rex->getSourceRange());
969 return QualType();
970}
971
972inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +0000973 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +0000974{
975 QualType lhsType = lex->getType(), rhsType = rex->getType();
976
977 if (lhsType->isVectorType() || rhsType->isVectorType())
978 return CheckVectorOperands(loc, lex, rex);
979
Steve Naroff8f708362007-08-24 19:07:16 +0000980 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +0000981
Chris Lattner4b009652007-07-25 00:24:17 +0000982 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000983 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +0000984 InvalidOperands(loc, lex, rex);
985 return QualType();
986}
987
988inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +0000989 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +0000990{
991 QualType lhsType = lex->getType(), rhsType = rex->getType();
992
Steve Naroff8f708362007-08-24 19:07:16 +0000993 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +0000994
Chris Lattner4b009652007-07-25 00:24:17 +0000995 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +0000996 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +0000997 InvalidOperands(loc, lex, rex);
998 return QualType();
999}
1000
1001inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001002 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001003{
1004 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1005 return CheckVectorOperands(loc, lex, rex);
1006
Steve Naroff8f708362007-08-24 19:07:16 +00001007 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001008
1009 // handle the common case first (both operands are arithmetic).
1010 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001011 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001012
1013 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1014 return lex->getType();
1015 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1016 return rex->getType();
1017 InvalidOperands(loc, lex, rex);
1018 return QualType();
1019}
1020
1021inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001022 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001023{
1024 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1025 return CheckVectorOperands(loc, lex, rex);
1026
Steve Naroff8f708362007-08-24 19:07:16 +00001027 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001028
1029 // handle the common case first (both operands are arithmetic).
1030 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001031 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001032
1033 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001034 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001035 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1036 return Context.getPointerDiffType();
1037 InvalidOperands(loc, lex, rex);
1038 return QualType();
1039}
1040
1041inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001042 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001043{
1044 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1045 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001046 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001047
1048 // handle the common case first (both operands are arithmetic).
1049 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001050 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001051 InvalidOperands(loc, lex, rex);
1052 return QualType();
1053}
1054
1055inline QualType Sema::CheckRelationalOperands( // C99 6.5.8
1056 Expr *&lex, Expr *&rex, SourceLocation loc)
1057{
Steve Naroffecc4fa12007-08-10 18:26:40 +00001058 // C99 6.5.8p3
1059 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1060 UsualArithmeticConversions(lex, rex);
1061 else {
1062 UsualUnaryConversions(lex);
1063 UsualUnaryConversions(rex);
1064 }
Chris Lattner4b009652007-07-25 00:24:17 +00001065 QualType lType = lex->getType();
1066 QualType rType = rex->getType();
1067
1068 if (lType->isRealType() && rType->isRealType())
1069 return Context.IntTy;
1070
Steve Naroff4462cb02007-08-16 21:48:38 +00001071 // All of the following pointer related warnings are GCC extensions. One
1072 // day, we can consider making them errors (when -pedantic-errors is enabled).
1073 if (lType->isPointerType() && rType->isPointerType()) {
1074 if (!Type::pointerTypesAreCompatible(lType, rType)) {
1075 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1076 lType.getAsString(), rType.getAsString(),
1077 lex->getSourceRange(), rex->getSourceRange());
1078 promoteExprToType(rex, lType); // promote the pointer to pointer
Chris Lattner4b009652007-07-25 00:24:17 +00001079 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001080 return Context.IntTy;
1081 }
1082 if (lType->isPointerType() && rType->isIntegerType()) {
1083 if (!rex->isNullPointerConstant(Context)) {
1084 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1085 lType.getAsString(), rType.getAsString(),
1086 lex->getSourceRange(), rex->getSourceRange());
1087 promoteExprToType(rex, lType); // promote the integer to pointer
Chris Lattner4b009652007-07-25 00:24:17 +00001088 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001089 return Context.IntTy;
1090 }
1091 if (lType->isIntegerType() && rType->isPointerType()) {
1092 if (!lex->isNullPointerConstant(Context)) {
1093 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1094 lType.getAsString(), rType.getAsString(),
1095 lex->getSourceRange(), rex->getSourceRange());
1096 promoteExprToType(lex, rType); // promote the integer to pointer
1097 }
1098 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001099 }
1100 InvalidOperands(loc, lex, rex);
1101 return QualType();
1102}
1103
1104inline QualType Sema::CheckEqualityOperands( // C99 6.5.9
1105 Expr *&lex, Expr *&rex, SourceLocation loc)
1106{
Steve Naroffecc4fa12007-08-10 18:26:40 +00001107 // C99 6.5.9p4
1108 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1109 UsualArithmeticConversions(lex, rex);
1110 else {
1111 UsualUnaryConversions(lex);
1112 UsualUnaryConversions(rex);
1113 }
Chris Lattner4b009652007-07-25 00:24:17 +00001114 QualType lType = lex->getType();
1115 QualType rType = rex->getType();
1116
1117 if (lType->isArithmeticType() && rType->isArithmeticType())
1118 return Context.IntTy;
1119
Steve Naroff4462cb02007-08-16 21:48:38 +00001120 // All of the following pointer related warnings are GCC extensions. One
1121 // day, we can consider making them errors (when -pedantic-errors is enabled).
1122 if (lType->isPointerType() && rType->isPointerType()) {
1123 if (!Type::pointerTypesAreCompatible(lType, rType)) {
1124 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1125 lType.getAsString(), rType.getAsString(),
1126 lex->getSourceRange(), rex->getSourceRange());
1127 promoteExprToType(rex, lType); // promote the pointer to pointer
Chris Lattner4b009652007-07-25 00:24:17 +00001128 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001129 return Context.IntTy;
1130 }
1131 if (lType->isPointerType() && rType->isIntegerType()) {
1132 if (!rex->isNullPointerConstant(Context)) {
1133 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1134 lType.getAsString(), rType.getAsString(),
1135 lex->getSourceRange(), rex->getSourceRange());
1136 promoteExprToType(rex, lType); // promote the integer to pointer
Chris Lattner4b009652007-07-25 00:24:17 +00001137 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001138 return Context.IntTy;
1139 }
1140 if (lType->isIntegerType() && rType->isPointerType()) {
1141 if (!lex->isNullPointerConstant(Context)) {
1142 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1143 lType.getAsString(), rType.getAsString(),
1144 lex->getSourceRange(), rex->getSourceRange());
1145 promoteExprToType(lex, rType); // promote the integer to pointer
1146 }
1147 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001148 }
1149 InvalidOperands(loc, lex, rex);
1150 return QualType();
1151}
1152
1153inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001154 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001155{
1156 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1157 return CheckVectorOperands(loc, lex, rex);
1158
Steve Naroff8f708362007-08-24 19:07:16 +00001159 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001160
1161 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001162 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001163 InvalidOperands(loc, lex, rex);
1164 return QualType();
1165}
1166
1167inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1168 Expr *&lex, Expr *&rex, SourceLocation loc)
1169{
1170 UsualUnaryConversions(lex);
1171 UsualUnaryConversions(rex);
1172
1173 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1174 return Context.IntTy;
1175 InvalidOperands(loc, lex, rex);
1176 return QualType();
1177}
1178
1179inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001180 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001181{
1182 QualType lhsType = lex->getType();
1183 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1184 bool hadError = false;
1185 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1186
1187 switch (mlval) { // C99 6.5.16p2
1188 case Expr::MLV_Valid:
1189 break;
1190 case Expr::MLV_ConstQualified:
1191 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1192 hadError = true;
1193 break;
1194 case Expr::MLV_ArrayType:
1195 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1196 lhsType.getAsString(), lex->getSourceRange());
1197 return QualType();
1198 case Expr::MLV_NotObjectType:
1199 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1200 lhsType.getAsString(), lex->getSourceRange());
1201 return QualType();
1202 case Expr::MLV_InvalidExpression:
1203 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1204 lex->getSourceRange());
1205 return QualType();
1206 case Expr::MLV_IncompleteType:
1207 case Expr::MLV_IncompleteVoidType:
1208 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1209 lhsType.getAsString(), lex->getSourceRange());
1210 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001211 case Expr::MLV_DuplicateVectorComponents:
1212 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1213 lex->getSourceRange());
1214 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001215 }
1216 AssignmentCheckResult result;
1217
1218 if (compoundType.isNull())
1219 result = CheckSingleAssignmentConstraints(lhsType, rex);
1220 else
1221 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001222
Chris Lattner4b009652007-07-25 00:24:17 +00001223 // decode the result (notice that extensions still return a type).
1224 switch (result) {
1225 case Compatible:
1226 break;
1227 case Incompatible:
1228 Diag(loc, diag::err_typecheck_assign_incompatible,
1229 lhsType.getAsString(), rhsType.getAsString(),
1230 lex->getSourceRange(), rex->getSourceRange());
1231 hadError = true;
1232 break;
1233 case PointerFromInt:
1234 // check for null pointer constant (C99 6.3.2.3p3)
1235 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1236 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1237 lhsType.getAsString(), rhsType.getAsString(),
1238 lex->getSourceRange(), rex->getSourceRange());
1239 }
1240 break;
1241 case IntFromPointer:
1242 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1243 lhsType.getAsString(), rhsType.getAsString(),
1244 lex->getSourceRange(), rex->getSourceRange());
1245 break;
1246 case IncompatiblePointer:
1247 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1248 lhsType.getAsString(), rhsType.getAsString(),
1249 lex->getSourceRange(), rex->getSourceRange());
1250 break;
1251 case CompatiblePointerDiscardsQualifiers:
1252 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1253 lhsType.getAsString(), rhsType.getAsString(),
1254 lex->getSourceRange(), rex->getSourceRange());
1255 break;
1256 }
1257 // C99 6.5.16p3: The type of an assignment expression is the type of the
1258 // left operand unless the left operand has qualified type, in which case
1259 // it is the unqualified version of the type of the left operand.
1260 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1261 // is converted to the type of the assignment expression (above).
1262 // C++ 5.17p1: the type of the assignment expression is that of its left oprdu.
1263 return hadError ? QualType() : lhsType.getUnqualifiedType();
1264}
1265
1266inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1267 Expr *&lex, Expr *&rex, SourceLocation loc) {
1268 UsualUnaryConversions(rex);
1269 return rex->getType();
1270}
1271
1272/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1273/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1274QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1275 QualType resType = op->getType();
1276 assert(!resType.isNull() && "no type for increment/decrement expression");
1277
Steve Naroffd30e1932007-08-24 17:20:07 +00001278 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattner4b009652007-07-25 00:24:17 +00001279 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1280 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1281 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1282 resType.getAsString(), op->getSourceRange());
1283 return QualType();
1284 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001285 } else if (!resType->isRealType()) {
1286 if (resType->isComplexType())
1287 // C99 does not support ++/-- on complex types.
1288 Diag(OpLoc, diag::ext_integer_increment_complex,
1289 resType.getAsString(), op->getSourceRange());
1290 else {
1291 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1292 resType.getAsString(), op->getSourceRange());
1293 return QualType();
1294 }
Chris Lattner4b009652007-07-25 00:24:17 +00001295 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001296 // At this point, we know we have a real, complex or pointer type.
1297 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001298 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1299 if (mlval != Expr::MLV_Valid) {
1300 // FIXME: emit a more precise diagnostic...
1301 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1302 op->getSourceRange());
1303 return QualType();
1304 }
1305 return resType;
1306}
1307
1308/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1309/// This routine allows us to typecheck complex/recursive expressions
1310/// where the declaration is needed for type checking. Here are some
1311/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1312static Decl *getPrimaryDeclaration(Expr *e) {
1313 switch (e->getStmtClass()) {
1314 case Stmt::DeclRefExprClass:
1315 return cast<DeclRefExpr>(e)->getDecl();
1316 case Stmt::MemberExprClass:
1317 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1318 case Stmt::ArraySubscriptExprClass:
1319 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1320 case Stmt::CallExprClass:
1321 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1322 case Stmt::UnaryOperatorClass:
1323 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1324 case Stmt::ParenExprClass:
1325 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1326 default:
1327 return 0;
1328 }
1329}
1330
1331/// CheckAddressOfOperand - The operand of & must be either a function
1332/// designator or an lvalue designating an object. If it is an lvalue, the
1333/// object cannot be declared with storage class register or be a bit field.
1334/// Note: The usual conversions are *not* applied to the operand of the &
1335/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1336QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1337 Decl *dcl = getPrimaryDeclaration(op);
1338 Expr::isLvalueResult lval = op->isLvalue();
1339
1340 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1341 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1342 ;
1343 else { // FIXME: emit more specific diag...
1344 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1345 op->getSourceRange());
1346 return QualType();
1347 }
1348 } else if (dcl) {
1349 // We have an lvalue with a decl. Make sure the decl is not declared
1350 // with the register storage-class specifier.
1351 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1352 if (vd->getStorageClass() == VarDecl::Register) {
1353 Diag(OpLoc, diag::err_typecheck_address_of_register,
1354 op->getSourceRange());
1355 return QualType();
1356 }
1357 } else
1358 assert(0 && "Unknown/unexpected decl type");
1359
1360 // FIXME: add check for bitfields!
1361 }
1362 // If the operand has type "type", the result has type "pointer to type".
1363 return Context.getPointerType(op->getType());
1364}
1365
1366QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1367 UsualUnaryConversions(op);
1368 QualType qType = op->getType();
1369
Chris Lattner7931f4a2007-07-31 16:53:04 +00001370 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001371 QualType ptype = PT->getPointeeType();
1372 // C99 6.5.3.2p4. "if it points to an object,...".
1373 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1374 // GCC compat: special case 'void *' (treat as warning).
1375 if (ptype->isVoidType()) {
1376 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1377 qType.getAsString(), op->getSourceRange());
1378 } else {
1379 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1380 ptype.getAsString(), op->getSourceRange());
1381 return QualType();
1382 }
1383 }
1384 return ptype;
1385 }
1386 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1387 qType.getAsString(), op->getSourceRange());
1388 return QualType();
1389}
1390
1391static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1392 tok::TokenKind Kind) {
1393 BinaryOperator::Opcode Opc;
1394 switch (Kind) {
1395 default: assert(0 && "Unknown binop!");
1396 case tok::star: Opc = BinaryOperator::Mul; break;
1397 case tok::slash: Opc = BinaryOperator::Div; break;
1398 case tok::percent: Opc = BinaryOperator::Rem; break;
1399 case tok::plus: Opc = BinaryOperator::Add; break;
1400 case tok::minus: Opc = BinaryOperator::Sub; break;
1401 case tok::lessless: Opc = BinaryOperator::Shl; break;
1402 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1403 case tok::lessequal: Opc = BinaryOperator::LE; break;
1404 case tok::less: Opc = BinaryOperator::LT; break;
1405 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1406 case tok::greater: Opc = BinaryOperator::GT; break;
1407 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1408 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1409 case tok::amp: Opc = BinaryOperator::And; break;
1410 case tok::caret: Opc = BinaryOperator::Xor; break;
1411 case tok::pipe: Opc = BinaryOperator::Or; break;
1412 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1413 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1414 case tok::equal: Opc = BinaryOperator::Assign; break;
1415 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1416 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1417 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1418 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1419 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1420 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1421 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1422 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1423 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1424 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1425 case tok::comma: Opc = BinaryOperator::Comma; break;
1426 }
1427 return Opc;
1428}
1429
1430static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1431 tok::TokenKind Kind) {
1432 UnaryOperator::Opcode Opc;
1433 switch (Kind) {
1434 default: assert(0 && "Unknown unary op!");
1435 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1436 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1437 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1438 case tok::star: Opc = UnaryOperator::Deref; break;
1439 case tok::plus: Opc = UnaryOperator::Plus; break;
1440 case tok::minus: Opc = UnaryOperator::Minus; break;
1441 case tok::tilde: Opc = UnaryOperator::Not; break;
1442 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1443 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1444 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1445 case tok::kw___real: Opc = UnaryOperator::Real; break;
1446 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1447 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1448 }
1449 return Opc;
1450}
1451
1452// Binary Operators. 'Tok' is the token for the operator.
1453Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1454 ExprTy *LHS, ExprTy *RHS) {
1455 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1456 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1457
1458 assert((lhs != 0) && "ParseBinOp(): missing left expression");
1459 assert((rhs != 0) && "ParseBinOp(): missing right expression");
1460
1461 QualType ResultTy; // Result type of the binary operator.
1462 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1463
1464 switch (Opc) {
1465 default:
1466 assert(0 && "Unknown binary expr!");
1467 case BinaryOperator::Assign:
1468 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1469 break;
1470 case BinaryOperator::Mul:
1471 case BinaryOperator::Div:
1472 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1473 break;
1474 case BinaryOperator::Rem:
1475 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1476 break;
1477 case BinaryOperator::Add:
1478 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1479 break;
1480 case BinaryOperator::Sub:
1481 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1482 break;
1483 case BinaryOperator::Shl:
1484 case BinaryOperator::Shr:
1485 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1486 break;
1487 case BinaryOperator::LE:
1488 case BinaryOperator::LT:
1489 case BinaryOperator::GE:
1490 case BinaryOperator::GT:
1491 ResultTy = CheckRelationalOperands(lhs, rhs, TokLoc);
1492 break;
1493 case BinaryOperator::EQ:
1494 case BinaryOperator::NE:
1495 ResultTy = CheckEqualityOperands(lhs, rhs, TokLoc);
1496 break;
1497 case BinaryOperator::And:
1498 case BinaryOperator::Xor:
1499 case BinaryOperator::Or:
1500 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1501 break;
1502 case BinaryOperator::LAnd:
1503 case BinaryOperator::LOr:
1504 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1505 break;
1506 case BinaryOperator::MulAssign:
1507 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001508 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001509 if (!CompTy.isNull())
1510 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1511 break;
1512 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001513 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001514 if (!CompTy.isNull())
1515 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1516 break;
1517 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001518 CompTy = CheckAdditionOperands(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::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001523 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001524 if (!CompTy.isNull())
1525 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1526 break;
1527 case BinaryOperator::ShlAssign:
1528 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001529 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001530 if (!CompTy.isNull())
1531 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1532 break;
1533 case BinaryOperator::AndAssign:
1534 case BinaryOperator::XorAssign:
1535 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001536 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001537 if (!CompTy.isNull())
1538 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1539 break;
1540 case BinaryOperator::Comma:
1541 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1542 break;
1543 }
1544 if (ResultTy.isNull())
1545 return true;
1546 if (CompTy.isNull())
1547 return new BinaryOperator(lhs, rhs, Opc, ResultTy);
1548 else
1549 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy);
1550}
1551
1552// Unary Operators. 'Tok' is the token for the operator.
1553Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1554 ExprTy *input) {
1555 Expr *Input = (Expr*)input;
1556 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1557 QualType resultType;
1558 switch (Opc) {
1559 default:
1560 assert(0 && "Unimplemented unary expr!");
1561 case UnaryOperator::PreInc:
1562 case UnaryOperator::PreDec:
1563 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1564 break;
1565 case UnaryOperator::AddrOf:
1566 resultType = CheckAddressOfOperand(Input, OpLoc);
1567 break;
1568 case UnaryOperator::Deref:
1569 resultType = CheckIndirectionOperand(Input, OpLoc);
1570 break;
1571 case UnaryOperator::Plus:
1572 case UnaryOperator::Minus:
1573 UsualUnaryConversions(Input);
1574 resultType = Input->getType();
1575 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1576 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1577 resultType.getAsString());
1578 break;
1579 case UnaryOperator::Not: // bitwise complement
1580 UsualUnaryConversions(Input);
1581 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001582 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1583 if (!resultType->isIntegerType()) {
1584 if (resultType->isComplexType())
1585 // C99 does not support '~' for complex conjugation.
1586 Diag(OpLoc, diag::ext_integer_complement_complex,
1587 resultType.getAsString());
1588 else
1589 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1590 resultType.getAsString());
1591 }
Chris Lattner4b009652007-07-25 00:24:17 +00001592 break;
1593 case UnaryOperator::LNot: // logical negation
1594 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1595 DefaultFunctionArrayConversion(Input);
1596 resultType = Input->getType();
1597 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1598 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1599 resultType.getAsString());
1600 // LNot always has type int. C99 6.5.3.3p5.
1601 resultType = Context.IntTy;
1602 break;
1603 case UnaryOperator::SizeOf:
1604 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1605 break;
1606 case UnaryOperator::AlignOf:
1607 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1608 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001609 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001610 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001611 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001612 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001613 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001614 resultType = Input->getType();
1615 break;
1616 }
1617 if (resultType.isNull())
1618 return true;
1619 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1620}
1621
1622/// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
1623Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
1624 SourceLocation LabLoc,
1625 IdentifierInfo *LabelII) {
1626 // Look up the record for this label identifier.
1627 LabelStmt *&LabelDecl = LabelMap[LabelII];
1628
1629 // If we haven't seen this label yet, create a forward reference.
1630 if (LabelDecl == 0)
1631 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1632
1633 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001634 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1635 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001636}
1637
1638Sema::ExprResult Sema::ParseStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
1639 SourceLocation RPLoc) { // "({..})"
1640 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1641 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1642 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1643
1644 // FIXME: there are a variety of strange constraints to enforce here, for
1645 // example, it is not possible to goto into a stmt expression apparently.
1646 // More semantic analysis is needed.
1647
1648 // FIXME: the last statement in the compount stmt has its value used. We
1649 // should not warn about it being unused.
1650
1651 // If there are sub stmts in the compound stmt, take the type of the last one
1652 // as the type of the stmtexpr.
1653 QualType Ty = Context.VoidTy;
1654
1655 if (!Compound->body_empty())
1656 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1657 Ty = LastExpr->getType();
1658
1659 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1660}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001661
Steve Naroff5b528922007-08-01 23:45:51 +00001662Sema::ExprResult Sema::ParseTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001663 TypeTy *arg1, TypeTy *arg2,
1664 SourceLocation RPLoc) {
1665 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1666 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1667
1668 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1669
Steve Naroff5b528922007-08-01 23:45:51 +00001670 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001671}
1672
Steve Naroff93c53012007-08-03 21:21:27 +00001673Sema::ExprResult Sema::ParseChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
1674 ExprTy *expr1, ExprTy *expr2,
1675 SourceLocation RPLoc) {
1676 Expr *CondExpr = static_cast<Expr*>(cond);
1677 Expr *LHSExpr = static_cast<Expr*>(expr1);
1678 Expr *RHSExpr = static_cast<Expr*>(expr2);
1679
1680 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1681
1682 // The conditional expression is required to be a constant expression.
1683 llvm::APSInt condEval(32);
1684 SourceLocation ExpLoc;
1685 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1686 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1687 CondExpr->getSourceRange());
1688
1689 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1690 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1691 RHSExpr->getType();
1692 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1693}
1694
Anders Carlssona66cad42007-08-21 17:43:55 +00001695// TODO: Move this to SemaObjC.cpp
Anders Carlsson8be1d402007-08-22 15:14:15 +00001696Sema::ExprResult Sema::ParseObjCStringLiteral(ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00001697 StringLiteral* S = static_cast<StringLiteral *>(string);
1698
1699 if (CheckBuiltinCFStringArgument(S))
1700 return true;
1701
1702 QualType t = Context.getCFConstantStringType();
1703 t = t.getQualifiedType(QualType::Const);
1704 t = Context.getPointerType(t);
1705
1706 return new ObjCStringLiteral(S, t);
1707}
Anders Carlsson8be1d402007-08-22 15:14:15 +00001708
1709Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1710 SourceLocation LParenLoc,
1711 TypeTy *Ty,
1712 SourceLocation RParenLoc) {
1713 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
1714
1715 QualType t = Context.getPointerType(Context.CharTy);
1716 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
1717}