blob: 88a057930b32ccb09a7585a028ed9f468a8383b2 [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 }
Steve Naroff91b03f72007-08-28 03:03:08 +000077 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
78 ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD);
79
80 // FIXME: generalize this for all decls.
81 if (PVD && PVD->getInvalidType())
82 return true;
Chris Lattner4b009652007-07-25 00:24:17 +000083 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +000084 }
Chris Lattner4b009652007-07-25 00:24:17 +000085 if (isa<TypedefDecl>(D))
86 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
87
88 assert(0 && "Invalid decl");
89 abort();
90}
91
92Sema::ExprResult Sema::ParsePreDefinedExpr(SourceLocation Loc,
93 tok::TokenKind Kind) {
94 PreDefinedExpr::IdentType IT;
95
96 switch (Kind) {
97 default:
98 assert(0 && "Unknown simple primary expr!");
99 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
100 IT = PreDefinedExpr::Func;
101 break;
102 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
103 IT = PreDefinedExpr::Function;
104 break;
105 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
106 IT = PreDefinedExpr::PrettyFunction;
107 break;
108 }
109
110 // Pre-defined identifiers are always of type char *.
111 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
112}
113
114Sema::ExprResult Sema::ParseCharacterConstant(const Token &Tok) {
115 llvm::SmallString<16> CharBuffer;
116 CharBuffer.resize(Tok.getLength());
117 const char *ThisTokBegin = &CharBuffer[0];
118 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
119
120 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
121 Tok.getLocation(), PP);
122 if (Literal.hadError())
123 return ExprResult(true);
124 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
125 Tok.getLocation());
126}
127
128Action::ExprResult Sema::ParseNumericConstant(const Token &Tok) {
129 // fast path for a single digit (which is quite common). A single digit
130 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
131 if (Tok.getLength() == 1) {
132 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
133
134 unsigned IntSize = Context.getTypeSize(Context.IntTy, Tok.getLocation());
135 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
136 Context.IntTy,
137 Tok.getLocation()));
138 }
139 llvm::SmallString<512> IntegerBuffer;
140 IntegerBuffer.resize(Tok.getLength());
141 const char *ThisTokBegin = &IntegerBuffer[0];
142
143 // Get the spelling of the token, which eliminates trigraphs, etc.
144 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
145 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
146 Tok.getLocation(), PP);
147 if (Literal.hadError)
148 return ExprResult(true);
149
Chris Lattner1de66eb2007-08-26 03:42:43 +0000150 Expr *Res;
151
152 if (Literal.isFloatingLiteral()) {
153 // FIXME: handle float values > 32 (including compute the real type...).
154 QualType Ty = Literal.isFloat ? Context.FloatTy : Context.DoubleTy;
155 Res = new FloatingLiteral(Literal.GetFloatValue(), Ty, Tok.getLocation());
156 } else if (!Literal.isIntegerLiteral()) {
157 return ExprResult(true);
158 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000159 QualType t;
160
161 // Get the value in the widest-possible width.
162 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
163
164 if (Literal.GetIntegerValue(ResultVal)) {
165 // If this value didn't fit into uintmax_t, warn and force to ull.
166 Diag(Tok.getLocation(), diag::warn_integer_too_large);
167 t = Context.UnsignedLongLongTy;
168 assert(Context.getTypeSize(t, Tok.getLocation()) ==
169 ResultVal.getBitWidth() && "long long is not intmax_t?");
170 } else {
171 // If this value fits into a ULL, try to figure out what else it fits into
172 // according to the rules of C99 6.4.4.1p5.
173
174 // Octal, Hexadecimal, and integers with a U suffix are allowed to
175 // be an unsigned int.
176 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
177
178 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000179 if (!Literal.isLong && !Literal.isLongLong) {
180 // Are int/unsigned possibilities?
Chris Lattner4b009652007-07-25 00:24:17 +0000181 unsigned IntSize = Context.getTypeSize(Context.IntTy,Tok.getLocation());
182 // Does it fit in a unsigned int?
183 if (ResultVal.isIntN(IntSize)) {
184 // Does it fit in a signed int?
185 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
186 t = Context.IntTy;
187 else if (AllowUnsigned)
188 t = Context.UnsignedIntTy;
189 }
190
191 if (!t.isNull())
192 ResultVal.trunc(IntSize);
193 }
194
195 // Are long/unsigned long possibilities?
196 if (t.isNull() && !Literal.isLongLong) {
197 unsigned LongSize = Context.getTypeSize(Context.LongTy,
198 Tok.getLocation());
199
200 // Does it fit in a unsigned long?
201 if (ResultVal.isIntN(LongSize)) {
202 // Does it fit in a signed long?
203 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
204 t = Context.LongTy;
205 else if (AllowUnsigned)
206 t = Context.UnsignedLongTy;
207 }
208 if (!t.isNull())
209 ResultVal.trunc(LongSize);
210 }
211
212 // Finally, check long long if needed.
213 if (t.isNull()) {
214 unsigned LongLongSize =
215 Context.getTypeSize(Context.LongLongTy, Tok.getLocation());
216
217 // Does it fit in a unsigned long long?
218 if (ResultVal.isIntN(LongLongSize)) {
219 // Does it fit in a signed long long?
220 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
221 t = Context.LongLongTy;
222 else if (AllowUnsigned)
223 t = Context.UnsignedLongLongTy;
224 }
225 }
226
227 // If we still couldn't decide a type, we probably have something that
228 // does not fit in a signed long long, but has no U suffix.
229 if (t.isNull()) {
230 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
231 t = Context.UnsignedLongLongTy;
232 }
233 }
234
Chris Lattner1de66eb2007-08-26 03:42:43 +0000235 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000236 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000237
238 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
239 if (Literal.isImaginary)
240 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
241
242 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000243}
244
245Action::ExprResult Sema::ParseParenExpr(SourceLocation L, SourceLocation R,
246 ExprTy *Val) {
247 Expr *e = (Expr *)Val;
248 assert((e != 0) && "ParseParenExpr() missing expr");
249 return new ParenExpr(L, R, e);
250}
251
252/// The UsualUnaryConversions() function is *not* called by this routine.
253/// See C99 6.3.2.1p[2-4] for more details.
254QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
255 SourceLocation OpLoc, bool isSizeof) {
256 // C99 6.5.3.4p1:
257 if (isa<FunctionType>(exprType) && isSizeof)
258 // alignof(function) is allowed.
259 Diag(OpLoc, diag::ext_sizeof_function_type);
260 else if (exprType->isVoidType())
261 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
262 else if (exprType->isIncompleteType()) {
263 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
264 diag::err_alignof_incomplete_type,
265 exprType.getAsString());
266 return QualType(); // error
267 }
268 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
269 return Context.getSizeType();
270}
271
272Action::ExprResult Sema::
273ParseSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
274 SourceLocation LPLoc, TypeTy *Ty,
275 SourceLocation RPLoc) {
276 // If error parsing type, ignore.
277 if (Ty == 0) return true;
278
279 // Verify that this is a valid expression.
280 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
281
282 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
283
284 if (resultType.isNull())
285 return true;
286 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
287}
288
Chris Lattner5110ad52007-08-24 21:41:10 +0000289QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000290 DefaultFunctionArrayConversion(V);
291
Chris Lattnera16e42d2007-08-26 05:39:26 +0000292 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000293 if (const ComplexType *CT = V->getType()->getAsComplexType())
294 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000295
296 // Otherwise they pass through real integer and floating point types here.
297 if (V->getType()->isArithmeticType())
298 return V->getType();
299
300 // Reject anything else.
301 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
302 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000303}
304
305
Chris Lattner4b009652007-07-25 00:24:17 +0000306
307Action::ExprResult Sema::ParsePostfixUnaryOp(SourceLocation OpLoc,
308 tok::TokenKind Kind,
309 ExprTy *Input) {
310 UnaryOperator::Opcode Opc;
311 switch (Kind) {
312 default: assert(0 && "Unknown unary op!");
313 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
314 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
315 }
316 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
317 if (result.isNull())
318 return true;
319 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
320}
321
322Action::ExprResult Sema::
323ParseArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
324 ExprTy *Idx, SourceLocation RLoc) {
325 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
326
327 // Perform default conversions.
328 DefaultFunctionArrayConversion(LHSExp);
329 DefaultFunctionArrayConversion(RHSExp);
330
331 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
332
333 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
334 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
335 // in the subscript position. As a result, we need to derive the array base
336 // and index from the expression types.
337 Expr *BaseExpr, *IndexExpr;
338 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000339 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000340 BaseExpr = LHSExp;
341 IndexExpr = RHSExp;
342 // FIXME: need to deal with const...
343 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000344 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000345 // Handle the uncommon case of "123[Ptr]".
346 BaseExpr = RHSExp;
347 IndexExpr = LHSExp;
348 // FIXME: need to deal with const...
349 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000350 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
351 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000352 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000353
354 // Component access limited to variables (reject vec4.rg[1]).
355 if (!isa<DeclRefExpr>(BaseExpr))
356 return Diag(LLoc, diag::err_ocuvector_component_access,
357 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000358 // FIXME: need to deal with const...
359 ResultType = VTy->getElementType();
360 } else {
361 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
362 RHSExp->getSourceRange());
363 }
364 // C99 6.5.2.1p1
365 if (!IndexExpr->getType()->isIntegerType())
366 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
367 IndexExpr->getSourceRange());
368
369 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
370 // the following check catches trying to index a pointer to a function (e.g.
371 // void (*)(int)). Functions are not objects in C99.
372 if (!ResultType->isObjectType())
373 return Diag(BaseExpr->getLocStart(),
374 diag::err_typecheck_subscript_not_object,
375 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
376
377 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
378}
379
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000380QualType Sema::
381CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
382 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000383 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000384
385 // The vector accessor can't exceed the number of elements.
386 const char *compStr = CompName.getName();
387 if (strlen(compStr) > vecType->getNumElements()) {
388 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
389 baseType.getAsString(), SourceRange(CompLoc));
390 return QualType();
391 }
392 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000393 if (vecType->getPointAccessorIdx(*compStr) != -1) {
394 do
395 compStr++;
396 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
397 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
398 do
399 compStr++;
400 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
401 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
402 do
403 compStr++;
404 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
405 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000406
407 if (*compStr) {
408 // We didn't get to the end of the string. This means the component names
409 // didn't come from the same set *or* we encountered an illegal name.
410 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
411 std::string(compStr,compStr+1), SourceRange(CompLoc));
412 return QualType();
413 }
414 // Each component accessor can't exceed the vector type.
415 compStr = CompName.getName();
416 while (*compStr) {
417 if (vecType->isAccessorWithinNumElements(*compStr))
418 compStr++;
419 else
420 break;
421 }
422 if (*compStr) {
423 // We didn't get to the end of the string. This means a component accessor
424 // exceeds the number of elements in the vector.
425 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
426 baseType.getAsString(), SourceRange(CompLoc));
427 return QualType();
428 }
429 // The component accessor looks fine - now we need to compute the actual type.
430 // The vector type is implied by the component accessor. For example,
431 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
432 unsigned CompSize = strlen(CompName.getName());
433 if (CompSize == 1)
434 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000435
436 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
437 // Now look up the TypeDefDecl from the vector type. Without this,
438 // diagostics look bad. We want OCU vector types to appear built-in.
439 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
440 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
441 return Context.getTypedefType(OCUVectorDecls[i]);
442 }
443 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000444}
445
Chris Lattner4b009652007-07-25 00:24:17 +0000446Action::ExprResult Sema::
447ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
448 tok::TokenKind OpKind, SourceLocation MemberLoc,
449 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000450 Expr *BaseExpr = static_cast<Expr *>(Base);
451 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000452
Steve Naroff2cb66382007-07-26 03:11:44 +0000453 QualType BaseType = BaseExpr->getType();
454 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000455
Chris Lattner4b009652007-07-25 00:24:17 +0000456 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000457 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000458 BaseType = PT->getPointeeType();
459 else
460 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
461 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000462 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000463 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000464 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000465 RecordDecl *RDecl = RTy->getDecl();
466 if (RTy->isIncompleteType())
467 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
468 BaseExpr->getSourceRange());
469 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000470 FieldDecl *MemberDecl = RDecl->getMember(&Member);
471 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000472 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
473 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000474 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
475 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000476 // Component access limited to variables (reject vec4.rg.g).
477 if (!isa<DeclRefExpr>(BaseExpr))
478 return Diag(OpLoc, diag::err_ocuvector_component_access,
479 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000480 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
481 if (ret.isNull())
482 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000483 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Steve Naroff2cb66382007-07-26 03:11:44 +0000484 } else
485 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
486 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000487}
488
489/// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
490/// This provides the location of the left/right parens and a list of comma
491/// locations.
492Action::ExprResult Sema::
493ParseCallExpr(ExprTy *fn, SourceLocation LParenLoc,
494 ExprTy **args, unsigned NumArgsInCall,
495 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
496 Expr *Fn = static_cast<Expr *>(fn);
497 Expr **Args = reinterpret_cast<Expr**>(args);
498 assert(Fn && "no function call expression");
499
500 UsualUnaryConversions(Fn);
501 QualType funcType = Fn->getType();
502
503 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
504 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000505 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000506 if (PT == 0)
507 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
508 SourceRange(Fn->getLocStart(), RParenLoc));
509
Chris Lattner71225142007-07-31 21:27:01 +0000510 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000511 if (funcT == 0)
512 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
513 SourceRange(Fn->getLocStart(), RParenLoc));
514
515 // If a prototype isn't declared, the parser implicitly defines a func decl
516 QualType resultType = funcT->getResultType();
517
518 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
519 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
520 // assignment, to the types of the corresponding parameter, ...
521
522 unsigned NumArgsInProto = proto->getNumArgs();
523 unsigned NumArgsToCheck = NumArgsInCall;
524
525 if (NumArgsInCall < NumArgsInProto)
526 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
527 Fn->getSourceRange());
528 else if (NumArgsInCall > NumArgsInProto) {
529 if (!proto->isVariadic()) {
530 Diag(Args[NumArgsInProto]->getLocStart(),
531 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
532 SourceRange(Args[NumArgsInProto]->getLocStart(),
533 Args[NumArgsInCall-1]->getLocEnd()));
534 }
535 NumArgsToCheck = NumArgsInProto;
536 }
537 // Continue to check argument types (even if we have too few/many args).
538 for (unsigned i = 0; i < NumArgsToCheck; i++) {
539 Expr *argExpr = Args[i];
540 assert(argExpr && "ParseCallExpr(): missing argument expression");
541
542 QualType lhsType = proto->getArgType(i);
543 QualType rhsType = argExpr->getType();
544
Steve Naroff75644062007-07-25 20:45:33 +0000545 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000546 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000547 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000548 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000549 lhsType = Context.getPointerType(lhsType);
550
551 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
552 argExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000553 if (Args[i] != argExpr) // The expression was converted.
554 Args[i] = argExpr; // Make sure we store the converted expression.
Chris Lattner4b009652007-07-25 00:24:17 +0000555 SourceLocation l = argExpr->getLocStart();
556
557 // decode the result (notice that AST's are still created for extensions).
558 switch (result) {
559 case Compatible:
560 break;
561 case PointerFromInt:
562 // check for null pointer constant (C99 6.3.2.3p3)
563 if (!argExpr->isNullPointerConstant(Context)) {
564 Diag(l, diag::ext_typecheck_passing_pointer_int,
565 lhsType.getAsString(), rhsType.getAsString(),
566 Fn->getSourceRange(), argExpr->getSourceRange());
567 }
568 break;
569 case IntFromPointer:
570 Diag(l, diag::ext_typecheck_passing_pointer_int,
571 lhsType.getAsString(), rhsType.getAsString(),
572 Fn->getSourceRange(), argExpr->getSourceRange());
573 break;
574 case IncompatiblePointer:
575 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
576 rhsType.getAsString(), lhsType.getAsString(),
577 Fn->getSourceRange(), argExpr->getSourceRange());
578 break;
579 case CompatiblePointerDiscardsQualifiers:
580 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
581 rhsType.getAsString(), lhsType.getAsString(),
582 Fn->getSourceRange(), argExpr->getSourceRange());
583 break;
584 case Incompatible:
585 return Diag(l, diag::err_typecheck_passing_incompatible,
586 rhsType.getAsString(), lhsType.getAsString(),
587 Fn->getSourceRange(), argExpr->getSourceRange());
588 }
589 }
590 // Even if the types checked, bail if we had the wrong number of arguments.
591 if (NumArgsInCall != NumArgsInProto && !proto->isVariadic())
592 return true;
593 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000594
595 // Do special checking on direct calls to functions.
596 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
597 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
598 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000599 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args, NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000600 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000601
Chris Lattner4b009652007-07-25 00:24:17 +0000602 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
603}
604
605Action::ExprResult Sema::
606ParseCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
607 SourceLocation RParenLoc, ExprTy *InitExpr) {
608 assert((Ty != 0) && "ParseCompoundLiteral(): missing type");
609 QualType literalType = QualType::getFromOpaquePtr(Ty);
610 // FIXME: put back this assert when initializers are worked out.
611 //assert((InitExpr != 0) && "ParseCompoundLiteral(): missing expression");
612 Expr *literalExpr = static_cast<Expr*>(InitExpr);
613
614 // FIXME: add semantic analysis (C99 6.5.2.5).
615 return new CompoundLiteralExpr(literalType, literalExpr);
616}
617
618Action::ExprResult Sema::
619ParseInitList(SourceLocation LParenLoc, ExprTy **InitList, unsigned NumInit,
620 SourceLocation RParenLoc) {
621 // FIXME: add semantic analysis (C99 6.7.8). This involves
622 // knowledge of the object being intialized. As a result, the code for
623 // doing the semantic analysis will likely be located elsewhere (i.e. in
624 // consumers of InitListExpr (e.g. ParseDeclarator, ParseCompoundLiteral).
625 return false; // FIXME instantiate an InitListExpr.
626}
627
628Action::ExprResult Sema::
629ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
630 SourceLocation RParenLoc, ExprTy *Op) {
631 assert((Ty != 0) && (Op != 0) && "ParseCastExpr(): missing type or expr");
632
633 Expr *castExpr = static_cast<Expr*>(Op);
634 QualType castType = QualType::getFromOpaquePtr(Ty);
635
636 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
637 // type needs to be scalar.
638 if (!castType->isScalarType() && !castType->isVoidType()) {
639 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
640 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
641 }
642 if (!castExpr->getType()->isScalarType()) {
643 return Diag(castExpr->getLocStart(),
644 diag::err_typecheck_expect_scalar_operand,
645 castExpr->getType().getAsString(), castExpr->getSourceRange());
646 }
647 return new CastExpr(castType, castExpr, LParenLoc);
648}
649
650inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
651 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
652 UsualUnaryConversions(cond);
653 UsualUnaryConversions(lex);
654 UsualUnaryConversions(rex);
655 QualType condT = cond->getType();
656 QualType lexT = lex->getType();
657 QualType rexT = rex->getType();
658
659 // first, check the condition.
660 if (!condT->isScalarType()) { // C99 6.5.15p2
661 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
662 condT.getAsString());
663 return QualType();
664 }
665 // now check the two expressions.
666 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
667 UsualArithmeticConversions(lex, rex);
668 return lex->getType();
669 }
Chris Lattner71225142007-07-31 21:27:01 +0000670 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
671 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
672
673 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
674 return lexT;
675
Chris Lattner4b009652007-07-25 00:24:17 +0000676 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
677 lexT.getAsString(), rexT.getAsString(),
678 lex->getSourceRange(), rex->getSourceRange());
679 return QualType();
680 }
681 }
682 // C99 6.5.15p3
683 if (lexT->isPointerType() && rex->isNullPointerConstant(Context))
684 return lexT;
685 if (rexT->isPointerType() && lex->isNullPointerConstant(Context))
686 return rexT;
687
Chris Lattner71225142007-07-31 21:27:01 +0000688 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
689 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
690 // get the "pointed to" types
691 QualType lhptee = LHSPT->getPointeeType();
692 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000693
Chris Lattner71225142007-07-31 21:27:01 +0000694 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
695 if (lhptee->isVoidType() &&
696 (rhptee->isObjectType() || rhptee->isIncompleteType()))
697 return lexT;
698 if (rhptee->isVoidType() &&
699 (lhptee->isObjectType() || lhptee->isIncompleteType()))
700 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000701
Chris Lattner71225142007-07-31 21:27:01 +0000702 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
703 rhptee.getUnqualifiedType())) {
704 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
705 lexT.getAsString(), rexT.getAsString(),
706 lex->getSourceRange(), rex->getSourceRange());
707 return lexT; // FIXME: this is an _ext - is this return o.k?
708 }
709 // The pointer types are compatible.
710 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
711 // differently qualified versions of compatible types, the result type is a
712 // pointer to an appropriately qualified version of the *composite* type.
713 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000714 }
Chris Lattner4b009652007-07-25 00:24:17 +0000715 }
Chris Lattner71225142007-07-31 21:27:01 +0000716
Chris Lattner4b009652007-07-25 00:24:17 +0000717 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
718 return lexT;
719
720 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
721 lexT.getAsString(), rexT.getAsString(),
722 lex->getSourceRange(), rex->getSourceRange());
723 return QualType();
724}
725
726/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
727/// in the case of a the GNU conditional expr extension.
728Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
729 SourceLocation ColonLoc,
730 ExprTy *Cond, ExprTy *LHS,
731 ExprTy *RHS) {
732 Expr *CondExpr = (Expr *) Cond;
733 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
734 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
735 RHSExpr, QuestionLoc);
736 if (result.isNull())
737 return true;
738 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
739}
740
741// promoteExprToType - a helper function to ensure we create exactly one
742// ImplicitCastExpr. As a convenience (to the caller), we return the type.
743static void promoteExprToType(Expr *&expr, QualType type) {
744 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
745 impCast->setType(type);
746 else
747 expr = new ImplicitCastExpr(type, expr);
748 return;
749}
750
751/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
752void Sema::DefaultFunctionArrayConversion(Expr *&e) {
753 QualType t = e->getType();
754 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
755
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000756 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000757 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
758 t = e->getType();
759 }
760 if (t->isFunctionType())
761 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000762 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000763 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
764}
765
766/// UsualUnaryConversion - Performs various conversions that are common to most
767/// operators (C99 6.3). The conversions of array and function types are
768/// sometimes surpressed. For example, the array->pointer conversion doesn't
769/// apply if the array is an argument to the sizeof or address (&) operators.
770/// In these instances, this routine should *not* be called.
771void Sema::UsualUnaryConversions(Expr *&expr) {
772 QualType t = expr->getType();
773 assert(!t.isNull() && "UsualUnaryConversions - missing type");
774
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000775 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000776 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
777 t = expr->getType();
778 }
779 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
780 promoteExprToType(expr, Context.IntTy);
781 else
782 DefaultFunctionArrayConversion(expr);
783}
784
785/// UsualArithmeticConversions - Performs various conversions that are common to
786/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
787/// routine returns the first non-arithmetic type found. The client is
788/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000789QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
790 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000791 if (!isCompAssign) {
792 UsualUnaryConversions(lhsExpr);
793 UsualUnaryConversions(rhsExpr);
794 }
Chris Lattner4b009652007-07-25 00:24:17 +0000795 QualType lhs = lhsExpr->getType();
796 QualType rhs = rhsExpr->getType();
797
798 // If both types are identical, no conversion is needed.
799 if (lhs == rhs)
Steve Naroff8f708362007-08-24 19:07:16 +0000800 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000801
802 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
803 // The caller can deal with this (e.g. pointer + int).
804 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000805 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000806
807 // At this point, we have two different arithmetic types.
808
809 // Handle complex types first (C99 6.3.1.8p1).
810 if (lhs->isComplexType() || rhs->isComplexType()) {
811 // if we have an integer operand, the result is the complex type.
812 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000813 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
814 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000815 }
816 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000817 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
818 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000819 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000820 // This handles complex/complex, complex/float, or float/complex.
821 // When both operands are complex, the shorter operand is converted to the
822 // type of the longer, and that is the type of the result. This corresponds
823 // to what is done when combining two real floating-point operands.
824 // The fun begins when size promotion occur across type domains.
825 // From H&S 6.3.4: When one operand is complex and the other is a real
826 // floating-point type, the less precise type is converted, within it's
827 // real or complex domain, to the precision of the other type. For example,
828 // when combining a "long double" with a "double _Complex", the
829 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000830 int result = Context.compareFloatingType(lhs, rhs);
831
832 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000833 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
834 if (!isCompAssign)
835 promoteExprToType(rhsExpr, rhs);
836 } else if (result < 0) { // The right side is bigger, convert lhs.
837 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
838 if (!isCompAssign)
839 promoteExprToType(lhsExpr, lhs);
840 }
841 // At this point, lhs and rhs have the same rank/size. Now, make sure the
842 // domains match. This is a requirement for our implementation, C99
843 // does not require this promotion.
844 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
845 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000846 if (!isCompAssign)
847 promoteExprToType(lhsExpr, rhs);
848 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000849 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000850 if (!isCompAssign)
851 promoteExprToType(rhsExpr, lhs);
852 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000853 }
Chris Lattner4b009652007-07-25 00:24:17 +0000854 }
Steve Naroff3b6157f2007-08-27 21:43:43 +0000855 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +0000856 }
857 // Now handle "real" floating types (i.e. float, double, long double).
858 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
859 // if we have an integer operand, the result is the real floating type.
860 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000861 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
862 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000863 }
864 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000865 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
866 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000867 }
868 // We have two real floating types, float/complex combos were handled above.
869 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +0000870 int result = Context.compareFloatingType(lhs, rhs);
871
872 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000873 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
874 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000875 }
Steve Naroff45fc9822007-08-27 15:30:22 +0000876 if (result < 0) { // convert the lhs
877 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
878 return rhs;
879 }
880 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +0000881 }
882 // Finally, we have two differing integer types.
883 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000884 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
885 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000886 }
Steve Naroff8f708362007-08-24 19:07:16 +0000887 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
888 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000889}
890
891// CheckPointerTypesForAssignment - This is a very tricky routine (despite
892// being closely modeled after the C99 spec:-). The odd characteristic of this
893// routine is it effectively iqnores the qualifiers on the top level pointee.
894// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
895// FIXME: add a couple examples in this comment.
896Sema::AssignmentCheckResult
897Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
898 QualType lhptee, rhptee;
899
900 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +0000901 lhptee = lhsType->getAsPointerType()->getPointeeType();
902 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000903
904 // make sure we operate on the canonical type
905 lhptee = lhptee.getCanonicalType();
906 rhptee = rhptee.getCanonicalType();
907
908 AssignmentCheckResult r = Compatible;
909
910 // C99 6.5.16.1p1: This following citation is common to constraints
911 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
912 // qualifiers of the type *pointed to* by the right;
913 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
914 rhptee.getQualifiers())
915 r = CompatiblePointerDiscardsQualifiers;
916
917 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
918 // incomplete type and the other is a pointer to a qualified or unqualified
919 // version of void...
920 if (lhptee.getUnqualifiedType()->isVoidType() &&
921 (rhptee->isObjectType() || rhptee->isIncompleteType()))
922 ;
923 else if (rhptee.getUnqualifiedType()->isVoidType() &&
924 (lhptee->isObjectType() || lhptee->isIncompleteType()))
925 ;
926 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
927 // unqualified versions of compatible types, ...
928 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
929 rhptee.getUnqualifiedType()))
930 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
931 return r;
932}
933
934/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
935/// has code to accommodate several GCC extensions when type checking
936/// pointers. Here are some objectionable examples that GCC considers warnings:
937///
938/// int a, *pint;
939/// short *pshort;
940/// struct foo *pfoo;
941///
942/// pint = pshort; // warning: assignment from incompatible pointer type
943/// a = pint; // warning: assignment makes integer from pointer without a cast
944/// pint = a; // warning: assignment makes pointer from integer without a cast
945/// pint = pfoo; // warning: assignment from incompatible pointer type
946///
947/// As a result, the code for dealing with pointers is more complex than the
948/// C99 spec dictates.
949/// Note: the warning above turn into errors when -pedantic-errors is enabled.
950///
951Sema::AssignmentCheckResult
952Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
953 if (lhsType == rhsType) // common case, fast path...
954 return Compatible;
955
956 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
957 if (lhsType->isVectorType() || rhsType->isVectorType()) {
958 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
959 return Incompatible;
960 }
961 return Compatible;
962 } else if (lhsType->isPointerType()) {
963 if (rhsType->isIntegerType())
964 return PointerFromInt;
965
966 if (rhsType->isPointerType())
967 return CheckPointerTypesForAssignment(lhsType, rhsType);
968 } else if (rhsType->isPointerType()) {
969 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
970 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
971 return IntFromPointer;
972
973 if (lhsType->isPointerType())
974 return CheckPointerTypesForAssignment(lhsType, rhsType);
975 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
976 if (Type::tagTypesAreCompatible(lhsType, rhsType))
977 return Compatible;
978 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
979 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
980 return Compatible;
981 }
982 return Incompatible;
983}
984
985Sema::AssignmentCheckResult
986Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
987 // This check seems unnatural, however it is necessary to insure the proper
988 // conversion of functions/arrays. If the conversion were done for all
989 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
990 // expressions that surpress this implicit conversion (&, sizeof).
991 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000992
993 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +0000994
Steve Naroff0f32f432007-08-24 22:33:52 +0000995 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
996
997 // C99 6.5.16.1p2: The value of the right operand is converted to the
998 // type of the assignment expression.
999 if (rExpr->getType() != lhsType)
1000 promoteExprToType(rExpr, lhsType);
1001 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001002}
1003
1004Sema::AssignmentCheckResult
1005Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1006 return CheckAssignmentConstraints(lhsType, rhsType);
1007}
1008
1009inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1010 Diag(loc, diag::err_typecheck_invalid_operands,
1011 lex->getType().getAsString(), rex->getType().getAsString(),
1012 lex->getSourceRange(), rex->getSourceRange());
1013}
1014
1015inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1016 Expr *&rex) {
1017 QualType lhsType = lex->getType(), rhsType = rex->getType();
1018
1019 // make sure the vector types are identical.
1020 if (lhsType == rhsType)
1021 return lhsType;
1022 // You cannot convert between vector values of different size.
1023 Diag(loc, diag::err_typecheck_vector_not_convertable,
1024 lex->getType().getAsString(), rex->getType().getAsString(),
1025 lex->getSourceRange(), rex->getSourceRange());
1026 return QualType();
1027}
1028
1029inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001030 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001031{
1032 QualType lhsType = lex->getType(), rhsType = rex->getType();
1033
1034 if (lhsType->isVectorType() || rhsType->isVectorType())
1035 return CheckVectorOperands(loc, lex, rex);
1036
Steve Naroff8f708362007-08-24 19:07:16 +00001037 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001038
Chris Lattner4b009652007-07-25 00:24:17 +00001039 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001040 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001041 InvalidOperands(loc, lex, rex);
1042 return QualType();
1043}
1044
1045inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001046 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001047{
1048 QualType lhsType = lex->getType(), rhsType = rex->getType();
1049
Steve Naroff8f708362007-08-24 19:07:16 +00001050 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001051
Chris Lattner4b009652007-07-25 00:24:17 +00001052 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001053 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001054 InvalidOperands(loc, lex, rex);
1055 return QualType();
1056}
1057
1058inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001059 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001060{
1061 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1062 return CheckVectorOperands(loc, lex, rex);
1063
Steve Naroff8f708362007-08-24 19:07:16 +00001064 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001065
1066 // handle the common case first (both operands are arithmetic).
1067 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001068 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001069
1070 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1071 return lex->getType();
1072 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1073 return rex->getType();
1074 InvalidOperands(loc, lex, rex);
1075 return QualType();
1076}
1077
1078inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001079 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001080{
1081 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1082 return CheckVectorOperands(loc, lex, rex);
1083
Steve Naroff8f708362007-08-24 19:07:16 +00001084 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001085
1086 // handle the common case first (both operands are arithmetic).
1087 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001088 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001089
1090 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001091 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001092 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1093 return Context.getPointerDiffType();
1094 InvalidOperands(loc, lex, rex);
1095 return QualType();
1096}
1097
1098inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001099 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001100{
1101 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1102 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001103 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001104
1105 // handle the common case first (both operands are arithmetic).
1106 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001107 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001108 InvalidOperands(loc, lex, rex);
1109 return QualType();
1110}
1111
Chris Lattner254f3bc2007-08-26 01:18:55 +00001112inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1113 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001114{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001115 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001116 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1117 UsualArithmeticConversions(lex, rex);
1118 else {
1119 UsualUnaryConversions(lex);
1120 UsualUnaryConversions(rex);
1121 }
Chris Lattner4b009652007-07-25 00:24:17 +00001122 QualType lType = lex->getType();
1123 QualType rType = rex->getType();
1124
Chris Lattner254f3bc2007-08-26 01:18:55 +00001125 if (isRelational) {
1126 if (lType->isRealType() && rType->isRealType())
1127 return Context.IntTy;
1128 } else {
1129 if (lType->isArithmeticType() && rType->isArithmeticType())
1130 return Context.IntTy;
1131 }
Chris Lattner4b009652007-07-25 00:24:17 +00001132
Chris Lattner22be8422007-08-26 01:10:14 +00001133 bool LHSIsNull = lex->isNullPointerConstant(Context);
1134 bool RHSIsNull = rex->isNullPointerConstant(Context);
1135
Chris Lattner254f3bc2007-08-26 01:18:55 +00001136 // All of the following pointer related warnings are GCC extensions, except
1137 // when handling null pointer constants. One day, we can consider making them
1138 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001139 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner22be8422007-08-26 01:10:14 +00001140 if (!LHSIsNull && !RHSIsNull &&
Steve Naroffc33c0602007-08-27 04:08:11 +00001141 !Type::pointerTypesAreCompatible(lType.getUnqualifiedType(),
1142 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001143 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1144 lType.getAsString(), rType.getAsString(),
1145 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001146 }
Chris Lattner22be8422007-08-26 01:10:14 +00001147 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001148 return Context.IntTy;
1149 }
1150 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001151 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001152 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1153 lType.getAsString(), rType.getAsString(),
1154 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001155 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001156 return Context.IntTy;
1157 }
1158 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001159 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001160 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1161 lType.getAsString(), rType.getAsString(),
1162 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001163 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001164 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001165 }
1166 InvalidOperands(loc, lex, rex);
1167 return QualType();
1168}
1169
Chris Lattner4b009652007-07-25 00:24:17 +00001170inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001171 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001172{
1173 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1174 return CheckVectorOperands(loc, lex, rex);
1175
Steve Naroff8f708362007-08-24 19:07:16 +00001176 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001177
1178 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001179 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001180 InvalidOperands(loc, lex, rex);
1181 return QualType();
1182}
1183
1184inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1185 Expr *&lex, Expr *&rex, SourceLocation loc)
1186{
1187 UsualUnaryConversions(lex);
1188 UsualUnaryConversions(rex);
1189
1190 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1191 return Context.IntTy;
1192 InvalidOperands(loc, lex, rex);
1193 return QualType();
1194}
1195
1196inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001197 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001198{
1199 QualType lhsType = lex->getType();
1200 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1201 bool hadError = false;
1202 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1203
1204 switch (mlval) { // C99 6.5.16p2
1205 case Expr::MLV_Valid:
1206 break;
1207 case Expr::MLV_ConstQualified:
1208 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1209 hadError = true;
1210 break;
1211 case Expr::MLV_ArrayType:
1212 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1213 lhsType.getAsString(), lex->getSourceRange());
1214 return QualType();
1215 case Expr::MLV_NotObjectType:
1216 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1217 lhsType.getAsString(), lex->getSourceRange());
1218 return QualType();
1219 case Expr::MLV_InvalidExpression:
1220 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1221 lex->getSourceRange());
1222 return QualType();
1223 case Expr::MLV_IncompleteType:
1224 case Expr::MLV_IncompleteVoidType:
1225 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1226 lhsType.getAsString(), lex->getSourceRange());
1227 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001228 case Expr::MLV_DuplicateVectorComponents:
1229 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1230 lex->getSourceRange());
1231 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001232 }
1233 AssignmentCheckResult result;
1234
1235 if (compoundType.isNull())
1236 result = CheckSingleAssignmentConstraints(lhsType, rex);
1237 else
1238 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001239
Chris Lattner4b009652007-07-25 00:24:17 +00001240 // decode the result (notice that extensions still return a type).
1241 switch (result) {
1242 case Compatible:
1243 break;
1244 case Incompatible:
1245 Diag(loc, diag::err_typecheck_assign_incompatible,
1246 lhsType.getAsString(), rhsType.getAsString(),
1247 lex->getSourceRange(), rex->getSourceRange());
1248 hadError = true;
1249 break;
1250 case PointerFromInt:
1251 // check for null pointer constant (C99 6.3.2.3p3)
1252 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1253 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1254 lhsType.getAsString(), rhsType.getAsString(),
1255 lex->getSourceRange(), rex->getSourceRange());
1256 }
1257 break;
1258 case IntFromPointer:
1259 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1260 lhsType.getAsString(), rhsType.getAsString(),
1261 lex->getSourceRange(), rex->getSourceRange());
1262 break;
1263 case IncompatiblePointer:
1264 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1265 lhsType.getAsString(), rhsType.getAsString(),
1266 lex->getSourceRange(), rex->getSourceRange());
1267 break;
1268 case CompatiblePointerDiscardsQualifiers:
1269 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1270 lhsType.getAsString(), rhsType.getAsString(),
1271 lex->getSourceRange(), rex->getSourceRange());
1272 break;
1273 }
1274 // C99 6.5.16p3: The type of an assignment expression is the type of the
1275 // left operand unless the left operand has qualified type, in which case
1276 // it is the unqualified version of the type of the left operand.
1277 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1278 // is converted to the type of the assignment expression (above).
1279 // C++ 5.17p1: the type of the assignment expression is that of its left oprdu.
1280 return hadError ? QualType() : lhsType.getUnqualifiedType();
1281}
1282
1283inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1284 Expr *&lex, Expr *&rex, SourceLocation loc) {
1285 UsualUnaryConversions(rex);
1286 return rex->getType();
1287}
1288
1289/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1290/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1291QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1292 QualType resType = op->getType();
1293 assert(!resType.isNull() && "no type for increment/decrement expression");
1294
Steve Naroffd30e1932007-08-24 17:20:07 +00001295 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattner4b009652007-07-25 00:24:17 +00001296 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1297 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1298 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1299 resType.getAsString(), op->getSourceRange());
1300 return QualType();
1301 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001302 } else if (!resType->isRealType()) {
1303 if (resType->isComplexType())
1304 // C99 does not support ++/-- on complex types.
1305 Diag(OpLoc, diag::ext_integer_increment_complex,
1306 resType.getAsString(), op->getSourceRange());
1307 else {
1308 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1309 resType.getAsString(), op->getSourceRange());
1310 return QualType();
1311 }
Chris Lattner4b009652007-07-25 00:24:17 +00001312 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001313 // At this point, we know we have a real, complex or pointer type.
1314 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001315 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1316 if (mlval != Expr::MLV_Valid) {
1317 // FIXME: emit a more precise diagnostic...
1318 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1319 op->getSourceRange());
1320 return QualType();
1321 }
1322 return resType;
1323}
1324
1325/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1326/// This routine allows us to typecheck complex/recursive expressions
1327/// where the declaration is needed for type checking. Here are some
1328/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1329static Decl *getPrimaryDeclaration(Expr *e) {
1330 switch (e->getStmtClass()) {
1331 case Stmt::DeclRefExprClass:
1332 return cast<DeclRefExpr>(e)->getDecl();
1333 case Stmt::MemberExprClass:
1334 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1335 case Stmt::ArraySubscriptExprClass:
1336 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1337 case Stmt::CallExprClass:
1338 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1339 case Stmt::UnaryOperatorClass:
1340 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1341 case Stmt::ParenExprClass:
1342 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1343 default:
1344 return 0;
1345 }
1346}
1347
1348/// CheckAddressOfOperand - The operand of & must be either a function
1349/// designator or an lvalue designating an object. If it is an lvalue, the
1350/// object cannot be declared with storage class register or be a bit field.
1351/// Note: The usual conversions are *not* applied to the operand of the &
1352/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1353QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1354 Decl *dcl = getPrimaryDeclaration(op);
1355 Expr::isLvalueResult lval = op->isLvalue();
1356
1357 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1358 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1359 ;
1360 else { // FIXME: emit more specific diag...
1361 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1362 op->getSourceRange());
1363 return QualType();
1364 }
1365 } else if (dcl) {
1366 // We have an lvalue with a decl. Make sure the decl is not declared
1367 // with the register storage-class specifier.
1368 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1369 if (vd->getStorageClass() == VarDecl::Register) {
1370 Diag(OpLoc, diag::err_typecheck_address_of_register,
1371 op->getSourceRange());
1372 return QualType();
1373 }
1374 } else
1375 assert(0 && "Unknown/unexpected decl type");
1376
1377 // FIXME: add check for bitfields!
1378 }
1379 // If the operand has type "type", the result has type "pointer to type".
1380 return Context.getPointerType(op->getType());
1381}
1382
1383QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1384 UsualUnaryConversions(op);
1385 QualType qType = op->getType();
1386
Chris Lattner7931f4a2007-07-31 16:53:04 +00001387 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001388 QualType ptype = PT->getPointeeType();
1389 // C99 6.5.3.2p4. "if it points to an object,...".
1390 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1391 // GCC compat: special case 'void *' (treat as warning).
1392 if (ptype->isVoidType()) {
1393 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1394 qType.getAsString(), op->getSourceRange());
1395 } else {
1396 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1397 ptype.getAsString(), op->getSourceRange());
1398 return QualType();
1399 }
1400 }
1401 return ptype;
1402 }
1403 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1404 qType.getAsString(), op->getSourceRange());
1405 return QualType();
1406}
1407
1408static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1409 tok::TokenKind Kind) {
1410 BinaryOperator::Opcode Opc;
1411 switch (Kind) {
1412 default: assert(0 && "Unknown binop!");
1413 case tok::star: Opc = BinaryOperator::Mul; break;
1414 case tok::slash: Opc = BinaryOperator::Div; break;
1415 case tok::percent: Opc = BinaryOperator::Rem; break;
1416 case tok::plus: Opc = BinaryOperator::Add; break;
1417 case tok::minus: Opc = BinaryOperator::Sub; break;
1418 case tok::lessless: Opc = BinaryOperator::Shl; break;
1419 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1420 case tok::lessequal: Opc = BinaryOperator::LE; break;
1421 case tok::less: Opc = BinaryOperator::LT; break;
1422 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1423 case tok::greater: Opc = BinaryOperator::GT; break;
1424 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1425 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1426 case tok::amp: Opc = BinaryOperator::And; break;
1427 case tok::caret: Opc = BinaryOperator::Xor; break;
1428 case tok::pipe: Opc = BinaryOperator::Or; break;
1429 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1430 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1431 case tok::equal: Opc = BinaryOperator::Assign; break;
1432 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1433 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1434 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1435 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1436 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1437 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1438 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1439 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1440 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1441 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1442 case tok::comma: Opc = BinaryOperator::Comma; break;
1443 }
1444 return Opc;
1445}
1446
1447static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1448 tok::TokenKind Kind) {
1449 UnaryOperator::Opcode Opc;
1450 switch (Kind) {
1451 default: assert(0 && "Unknown unary op!");
1452 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1453 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1454 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1455 case tok::star: Opc = UnaryOperator::Deref; break;
1456 case tok::plus: Opc = UnaryOperator::Plus; break;
1457 case tok::minus: Opc = UnaryOperator::Minus; break;
1458 case tok::tilde: Opc = UnaryOperator::Not; break;
1459 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1460 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1461 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1462 case tok::kw___real: Opc = UnaryOperator::Real; break;
1463 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1464 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1465 }
1466 return Opc;
1467}
1468
1469// Binary Operators. 'Tok' is the token for the operator.
1470Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1471 ExprTy *LHS, ExprTy *RHS) {
1472 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1473 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1474
1475 assert((lhs != 0) && "ParseBinOp(): missing left expression");
1476 assert((rhs != 0) && "ParseBinOp(): missing right expression");
1477
1478 QualType ResultTy; // Result type of the binary operator.
1479 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1480
1481 switch (Opc) {
1482 default:
1483 assert(0 && "Unknown binary expr!");
1484 case BinaryOperator::Assign:
1485 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1486 break;
1487 case BinaryOperator::Mul:
1488 case BinaryOperator::Div:
1489 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1490 break;
1491 case BinaryOperator::Rem:
1492 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1493 break;
1494 case BinaryOperator::Add:
1495 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1496 break;
1497 case BinaryOperator::Sub:
1498 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1499 break;
1500 case BinaryOperator::Shl:
1501 case BinaryOperator::Shr:
1502 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1503 break;
1504 case BinaryOperator::LE:
1505 case BinaryOperator::LT:
1506 case BinaryOperator::GE:
1507 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001508 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001509 break;
1510 case BinaryOperator::EQ:
1511 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001512 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001513 break;
1514 case BinaryOperator::And:
1515 case BinaryOperator::Xor:
1516 case BinaryOperator::Or:
1517 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1518 break;
1519 case BinaryOperator::LAnd:
1520 case BinaryOperator::LOr:
1521 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1522 break;
1523 case BinaryOperator::MulAssign:
1524 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001525 CompTy = CheckMultiplyDivideOperands(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::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001530 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001531 if (!CompTy.isNull())
1532 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1533 break;
1534 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001535 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001536 if (!CompTy.isNull())
1537 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1538 break;
1539 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001540 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001541 if (!CompTy.isNull())
1542 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1543 break;
1544 case BinaryOperator::ShlAssign:
1545 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001546 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001547 if (!CompTy.isNull())
1548 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1549 break;
1550 case BinaryOperator::AndAssign:
1551 case BinaryOperator::XorAssign:
1552 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001553 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001554 if (!CompTy.isNull())
1555 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1556 break;
1557 case BinaryOperator::Comma:
1558 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1559 break;
1560 }
1561 if (ResultTy.isNull())
1562 return true;
1563 if (CompTy.isNull())
1564 return new BinaryOperator(lhs, rhs, Opc, ResultTy);
1565 else
1566 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy);
1567}
1568
1569// Unary Operators. 'Tok' is the token for the operator.
1570Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1571 ExprTy *input) {
1572 Expr *Input = (Expr*)input;
1573 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1574 QualType resultType;
1575 switch (Opc) {
1576 default:
1577 assert(0 && "Unimplemented unary expr!");
1578 case UnaryOperator::PreInc:
1579 case UnaryOperator::PreDec:
1580 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1581 break;
1582 case UnaryOperator::AddrOf:
1583 resultType = CheckAddressOfOperand(Input, OpLoc);
1584 break;
1585 case UnaryOperator::Deref:
1586 resultType = CheckIndirectionOperand(Input, OpLoc);
1587 break;
1588 case UnaryOperator::Plus:
1589 case UnaryOperator::Minus:
1590 UsualUnaryConversions(Input);
1591 resultType = Input->getType();
1592 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1593 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1594 resultType.getAsString());
1595 break;
1596 case UnaryOperator::Not: // bitwise complement
1597 UsualUnaryConversions(Input);
1598 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001599 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1600 if (!resultType->isIntegerType()) {
1601 if (resultType->isComplexType())
1602 // C99 does not support '~' for complex conjugation.
1603 Diag(OpLoc, diag::ext_integer_complement_complex,
1604 resultType.getAsString());
1605 else
1606 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1607 resultType.getAsString());
1608 }
Chris Lattner4b009652007-07-25 00:24:17 +00001609 break;
1610 case UnaryOperator::LNot: // logical negation
1611 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1612 DefaultFunctionArrayConversion(Input);
1613 resultType = Input->getType();
1614 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1615 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1616 resultType.getAsString());
1617 // LNot always has type int. C99 6.5.3.3p5.
1618 resultType = Context.IntTy;
1619 break;
1620 case UnaryOperator::SizeOf:
1621 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1622 break;
1623 case UnaryOperator::AlignOf:
1624 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1625 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001626 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001627 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001628 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001629 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001630 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001631 resultType = Input->getType();
1632 break;
1633 }
1634 if (resultType.isNull())
1635 return true;
1636 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1637}
1638
1639/// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
1640Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
1641 SourceLocation LabLoc,
1642 IdentifierInfo *LabelII) {
1643 // Look up the record for this label identifier.
1644 LabelStmt *&LabelDecl = LabelMap[LabelII];
1645
1646 // If we haven't seen this label yet, create a forward reference.
1647 if (LabelDecl == 0)
1648 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1649
1650 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001651 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1652 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001653}
1654
1655Sema::ExprResult Sema::ParseStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
1656 SourceLocation RPLoc) { // "({..})"
1657 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1658 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1659 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1660
1661 // FIXME: there are a variety of strange constraints to enforce here, for
1662 // example, it is not possible to goto into a stmt expression apparently.
1663 // More semantic analysis is needed.
1664
1665 // FIXME: the last statement in the compount stmt has its value used. We
1666 // should not warn about it being unused.
1667
1668 // If there are sub stmts in the compound stmt, take the type of the last one
1669 // as the type of the stmtexpr.
1670 QualType Ty = Context.VoidTy;
1671
1672 if (!Compound->body_empty())
1673 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1674 Ty = LastExpr->getType();
1675
1676 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1677}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001678
Steve Naroff5b528922007-08-01 23:45:51 +00001679Sema::ExprResult Sema::ParseTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001680 TypeTy *arg1, TypeTy *arg2,
1681 SourceLocation RPLoc) {
1682 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1683 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1684
1685 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1686
Steve Naroff5b528922007-08-01 23:45:51 +00001687 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001688}
1689
Steve Naroff93c53012007-08-03 21:21:27 +00001690Sema::ExprResult Sema::ParseChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
1691 ExprTy *expr1, ExprTy *expr2,
1692 SourceLocation RPLoc) {
1693 Expr *CondExpr = static_cast<Expr*>(cond);
1694 Expr *LHSExpr = static_cast<Expr*>(expr1);
1695 Expr *RHSExpr = static_cast<Expr*>(expr2);
1696
1697 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1698
1699 // The conditional expression is required to be a constant expression.
1700 llvm::APSInt condEval(32);
1701 SourceLocation ExpLoc;
1702 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1703 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1704 CondExpr->getSourceRange());
1705
1706 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1707 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1708 RHSExpr->getType();
1709 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1710}
1711
Anders Carlssona66cad42007-08-21 17:43:55 +00001712// TODO: Move this to SemaObjC.cpp
Anders Carlsson8be1d402007-08-22 15:14:15 +00001713Sema::ExprResult Sema::ParseObjCStringLiteral(ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00001714 StringLiteral* S = static_cast<StringLiteral *>(string);
1715
1716 if (CheckBuiltinCFStringArgument(S))
1717 return true;
1718
1719 QualType t = Context.getCFConstantStringType();
1720 t = t.getQualifiedType(QualType::Const);
1721 t = Context.getPointerType(t);
1722
1723 return new ObjCStringLiteral(S, t);
1724}
Anders Carlsson8be1d402007-08-22 15:14:15 +00001725
1726Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1727 SourceLocation LParenLoc,
1728 TypeTy *Ty,
1729 SourceLocation RParenLoc) {
1730 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
1731
1732 QualType t = Context.getPointerType(Context.CharTy);
1733 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
1734}