blob: d2d1f9567c24c476cf8413501c13bb9825c604b7 [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)) {
Steve Naroffcae537d2007-08-28 18:45:29 +000078 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +000079 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +000080 return true;
Chris Lattner4b009652007-07-25 00:24:17 +000081 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +000082 }
Chris Lattner4b009652007-07-25 00:24:17 +000083 if (isa<TypedefDecl>(D))
84 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
85
86 assert(0 && "Invalid decl");
87 abort();
88}
89
90Sema::ExprResult Sema::ParsePreDefinedExpr(SourceLocation Loc,
91 tok::TokenKind Kind) {
92 PreDefinedExpr::IdentType IT;
93
94 switch (Kind) {
95 default:
96 assert(0 && "Unknown simple primary expr!");
97 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
98 IT = PreDefinedExpr::Func;
99 break;
100 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
101 IT = PreDefinedExpr::Function;
102 break;
103 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
104 IT = PreDefinedExpr::PrettyFunction;
105 break;
106 }
107
108 // Pre-defined identifiers are always of type char *.
109 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
110}
111
112Sema::ExprResult Sema::ParseCharacterConstant(const Token &Tok) {
113 llvm::SmallString<16> CharBuffer;
114 CharBuffer.resize(Tok.getLength());
115 const char *ThisTokBegin = &CharBuffer[0];
116 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
117
118 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
119 Tok.getLocation(), PP);
120 if (Literal.hadError())
121 return ExprResult(true);
122 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
123 Tok.getLocation());
124}
125
126Action::ExprResult Sema::ParseNumericConstant(const Token &Tok) {
127 // fast path for a single digit (which is quite common). A single digit
128 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
129 if (Tok.getLength() == 1) {
130 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
131
Chris Lattner3496d522007-09-04 02:45:27 +0000132 unsigned IntSize = static_cast<unsigned>(
133 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000134 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
135 Context.IntTy,
136 Tok.getLocation()));
137 }
138 llvm::SmallString<512> IntegerBuffer;
139 IntegerBuffer.resize(Tok.getLength());
140 const char *ThisTokBegin = &IntegerBuffer[0];
141
142 // Get the spelling of the token, which eliminates trigraphs, etc.
143 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
144 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
145 Tok.getLocation(), PP);
146 if (Literal.hadError)
147 return ExprResult(true);
148
Chris Lattner1de66eb2007-08-26 03:42:43 +0000149 Expr *Res;
150
151 if (Literal.isFloatingLiteral()) {
152 // FIXME: handle float values > 32 (including compute the real type...).
153 QualType Ty = Literal.isFloat ? Context.FloatTy : Context.DoubleTy;
154 Res = new FloatingLiteral(Literal.GetFloatValue(), Ty, Tok.getLocation());
155 } else if (!Literal.isIntegerLiteral()) {
156 return ExprResult(true);
157 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000158 QualType t;
159
Neil Booth7421e9c2007-08-29 22:00:19 +0000160 // long long is a C99 feature.
161 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000162 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000163 Diag(Tok.getLocation(), diag::ext_longlong);
164
Chris Lattner4b009652007-07-25 00:24:17 +0000165 // Get the value in the widest-possible width.
166 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
167
168 if (Literal.GetIntegerValue(ResultVal)) {
169 // If this value didn't fit into uintmax_t, warn and force to ull.
170 Diag(Tok.getLocation(), diag::warn_integer_too_large);
171 t = Context.UnsignedLongLongTy;
172 assert(Context.getTypeSize(t, Tok.getLocation()) ==
173 ResultVal.getBitWidth() && "long long is not intmax_t?");
174 } else {
175 // If this value fits into a ULL, try to figure out what else it fits into
176 // according to the rules of C99 6.4.4.1p5.
177
178 // Octal, Hexadecimal, and integers with a U suffix are allowed to
179 // be an unsigned int.
180 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
181
182 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000183 if (!Literal.isLong && !Literal.isLongLong) {
184 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000185 unsigned IntSize = static_cast<unsigned>(
186 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000187 // Does it fit in a unsigned int?
188 if (ResultVal.isIntN(IntSize)) {
189 // Does it fit in a signed int?
190 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
191 t = Context.IntTy;
192 else if (AllowUnsigned)
193 t = Context.UnsignedIntTy;
194 }
195
196 if (!t.isNull())
197 ResultVal.trunc(IntSize);
198 }
199
200 // Are long/unsigned long possibilities?
201 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000202 unsigned LongSize = static_cast<unsigned>(
203 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000204
205 // Does it fit in a unsigned long?
206 if (ResultVal.isIntN(LongSize)) {
207 // Does it fit in a signed long?
208 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
209 t = Context.LongTy;
210 else if (AllowUnsigned)
211 t = Context.UnsignedLongTy;
212 }
213 if (!t.isNull())
214 ResultVal.trunc(LongSize);
215 }
216
217 // Finally, check long long if needed.
218 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000219 unsigned LongLongSize = static_cast<unsigned>(
220 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000221
222 // Does it fit in a unsigned long long?
223 if (ResultVal.isIntN(LongLongSize)) {
224 // Does it fit in a signed long long?
225 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
226 t = Context.LongLongTy;
227 else if (AllowUnsigned)
228 t = Context.UnsignedLongLongTy;
229 }
230 }
231
232 // If we still couldn't decide a type, we probably have something that
233 // does not fit in a signed long long, but has no U suffix.
234 if (t.isNull()) {
235 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
236 t = Context.UnsignedLongLongTy;
237 }
238 }
239
Chris Lattner1de66eb2007-08-26 03:42:43 +0000240 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000241 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000242
243 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
244 if (Literal.isImaginary)
245 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
246
247 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000248}
249
250Action::ExprResult Sema::ParseParenExpr(SourceLocation L, SourceLocation R,
251 ExprTy *Val) {
252 Expr *e = (Expr *)Val;
253 assert((e != 0) && "ParseParenExpr() missing expr");
254 return new ParenExpr(L, R, e);
255}
256
257/// The UsualUnaryConversions() function is *not* called by this routine.
258/// See C99 6.3.2.1p[2-4] for more details.
259QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
260 SourceLocation OpLoc, bool isSizeof) {
261 // C99 6.5.3.4p1:
262 if (isa<FunctionType>(exprType) && isSizeof)
263 // alignof(function) is allowed.
264 Diag(OpLoc, diag::ext_sizeof_function_type);
265 else if (exprType->isVoidType())
266 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
267 else if (exprType->isIncompleteType()) {
268 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
269 diag::err_alignof_incomplete_type,
270 exprType.getAsString());
271 return QualType(); // error
272 }
273 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
274 return Context.getSizeType();
275}
276
277Action::ExprResult Sema::
278ParseSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
279 SourceLocation LPLoc, TypeTy *Ty,
280 SourceLocation RPLoc) {
281 // If error parsing type, ignore.
282 if (Ty == 0) return true;
283
284 // Verify that this is a valid expression.
285 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
286
287 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
288
289 if (resultType.isNull())
290 return true;
291 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
292}
293
Chris Lattner5110ad52007-08-24 21:41:10 +0000294QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000295 DefaultFunctionArrayConversion(V);
296
Chris Lattnera16e42d2007-08-26 05:39:26 +0000297 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000298 if (const ComplexType *CT = V->getType()->getAsComplexType())
299 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000300
301 // Otherwise they pass through real integer and floating point types here.
302 if (V->getType()->isArithmeticType())
303 return V->getType();
304
305 // Reject anything else.
306 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
307 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000308}
309
310
Chris Lattner4b009652007-07-25 00:24:17 +0000311
312Action::ExprResult Sema::ParsePostfixUnaryOp(SourceLocation OpLoc,
313 tok::TokenKind Kind,
314 ExprTy *Input) {
315 UnaryOperator::Opcode Opc;
316 switch (Kind) {
317 default: assert(0 && "Unknown unary op!");
318 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
319 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
320 }
321 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
322 if (result.isNull())
323 return true;
324 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
325}
326
327Action::ExprResult Sema::
328ParseArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
329 ExprTy *Idx, SourceLocation RLoc) {
330 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
331
332 // Perform default conversions.
333 DefaultFunctionArrayConversion(LHSExp);
334 DefaultFunctionArrayConversion(RHSExp);
335
336 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
337
338 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000339 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000340 // in the subscript position. As a result, we need to derive the array base
341 // and index from the expression types.
342 Expr *BaseExpr, *IndexExpr;
343 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000344 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000345 BaseExpr = LHSExp;
346 IndexExpr = RHSExp;
347 // FIXME: need to deal with const...
348 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000349 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000350 // Handle the uncommon case of "123[Ptr]".
351 BaseExpr = RHSExp;
352 IndexExpr = LHSExp;
353 // FIXME: need to deal with const...
354 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000355 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
356 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000357 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000358
359 // Component access limited to variables (reject vec4.rg[1]).
360 if (!isa<DeclRefExpr>(BaseExpr))
361 return Diag(LLoc, diag::err_ocuvector_component_access,
362 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000363 // FIXME: need to deal with const...
364 ResultType = VTy->getElementType();
365 } else {
366 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
367 RHSExp->getSourceRange());
368 }
369 // C99 6.5.2.1p1
370 if (!IndexExpr->getType()->isIntegerType())
371 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
372 IndexExpr->getSourceRange());
373
374 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
375 // the following check catches trying to index a pointer to a function (e.g.
376 // void (*)(int)). Functions are not objects in C99.
377 if (!ResultType->isObjectType())
378 return Diag(BaseExpr->getLocStart(),
379 diag::err_typecheck_subscript_not_object,
380 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
381
382 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
383}
384
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000385QualType Sema::
386CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
387 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000388 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000389
390 // The vector accessor can't exceed the number of elements.
391 const char *compStr = CompName.getName();
392 if (strlen(compStr) > vecType->getNumElements()) {
393 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
394 baseType.getAsString(), SourceRange(CompLoc));
395 return QualType();
396 }
397 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000398 if (vecType->getPointAccessorIdx(*compStr) != -1) {
399 do
400 compStr++;
401 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
402 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
403 do
404 compStr++;
405 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
406 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
407 do
408 compStr++;
409 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
410 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000411
412 if (*compStr) {
413 // We didn't get to the end of the string. This means the component names
414 // didn't come from the same set *or* we encountered an illegal name.
415 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
416 std::string(compStr,compStr+1), SourceRange(CompLoc));
417 return QualType();
418 }
419 // Each component accessor can't exceed the vector type.
420 compStr = CompName.getName();
421 while (*compStr) {
422 if (vecType->isAccessorWithinNumElements(*compStr))
423 compStr++;
424 else
425 break;
426 }
427 if (*compStr) {
428 // We didn't get to the end of the string. This means a component accessor
429 // exceeds the number of elements in the vector.
430 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
431 baseType.getAsString(), SourceRange(CompLoc));
432 return QualType();
433 }
434 // The component accessor looks fine - now we need to compute the actual type.
435 // The vector type is implied by the component accessor. For example,
436 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
437 unsigned CompSize = strlen(CompName.getName());
438 if (CompSize == 1)
439 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000440
441 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
442 // Now look up the TypeDefDecl from the vector type. Without this,
443 // diagostics look bad. We want OCU vector types to appear built-in.
444 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
445 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
446 return Context.getTypedefType(OCUVectorDecls[i]);
447 }
448 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000449}
450
Chris Lattner4b009652007-07-25 00:24:17 +0000451Action::ExprResult Sema::
452ParseMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
453 tok::TokenKind OpKind, SourceLocation MemberLoc,
454 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000455 Expr *BaseExpr = static_cast<Expr *>(Base);
456 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000457
Steve Naroff2cb66382007-07-26 03:11:44 +0000458 QualType BaseType = BaseExpr->getType();
459 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000460
Chris Lattner4b009652007-07-25 00:24:17 +0000461 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000462 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000463 BaseType = PT->getPointeeType();
464 else
465 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
466 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000467 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000468 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000469 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000470 RecordDecl *RDecl = RTy->getDecl();
471 if (RTy->isIncompleteType())
472 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
473 BaseExpr->getSourceRange());
474 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000475 FieldDecl *MemberDecl = RDecl->getMember(&Member);
476 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000477 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
478 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000479 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
480 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000481 // Component access limited to variables (reject vec4.rg.g).
482 if (!isa<DeclRefExpr>(BaseExpr))
483 return Diag(OpLoc, diag::err_ocuvector_component_access,
484 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000485 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
486 if (ret.isNull())
487 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000488 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Steve Naroff2cb66382007-07-26 03:11:44 +0000489 } else
490 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
491 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000492}
493
494/// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
495/// This provides the location of the left/right parens and a list of comma
496/// locations.
497Action::ExprResult Sema::
498ParseCallExpr(ExprTy *fn, SourceLocation LParenLoc,
499 ExprTy **args, unsigned NumArgsInCall,
500 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
501 Expr *Fn = static_cast<Expr *>(fn);
502 Expr **Args = reinterpret_cast<Expr**>(args);
503 assert(Fn && "no function call expression");
504
505 UsualUnaryConversions(Fn);
506 QualType funcType = Fn->getType();
507
508 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
509 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000510 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000511 if (PT == 0)
512 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
513 SourceRange(Fn->getLocStart(), RParenLoc));
514
Chris Lattner71225142007-07-31 21:27:01 +0000515 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000516 if (funcT == 0)
517 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
518 SourceRange(Fn->getLocStart(), RParenLoc));
519
520 // If a prototype isn't declared, the parser implicitly defines a func decl
521 QualType resultType = funcT->getResultType();
522
523 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
524 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
525 // assignment, to the types of the corresponding parameter, ...
526
527 unsigned NumArgsInProto = proto->getNumArgs();
528 unsigned NumArgsToCheck = NumArgsInCall;
529
530 if (NumArgsInCall < NumArgsInProto)
531 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
532 Fn->getSourceRange());
533 else if (NumArgsInCall > NumArgsInProto) {
534 if (!proto->isVariadic()) {
535 Diag(Args[NumArgsInProto]->getLocStart(),
536 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
537 SourceRange(Args[NumArgsInProto]->getLocStart(),
538 Args[NumArgsInCall-1]->getLocEnd()));
539 }
540 NumArgsToCheck = NumArgsInProto;
541 }
542 // Continue to check argument types (even if we have too few/many args).
543 for (unsigned i = 0; i < NumArgsToCheck; i++) {
544 Expr *argExpr = Args[i];
545 assert(argExpr && "ParseCallExpr(): missing argument expression");
546
547 QualType lhsType = proto->getArgType(i);
548 QualType rhsType = argExpr->getType();
549
Steve Naroff75644062007-07-25 20:45:33 +0000550 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000551 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000552 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000553 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000554 lhsType = Context.getPointerType(lhsType);
555
556 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
557 argExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000558 if (Args[i] != argExpr) // The expression was converted.
559 Args[i] = argExpr; // Make sure we store the converted expression.
Chris Lattner4b009652007-07-25 00:24:17 +0000560 SourceLocation l = argExpr->getLocStart();
561
562 // decode the result (notice that AST's are still created for extensions).
563 switch (result) {
564 case Compatible:
565 break;
566 case PointerFromInt:
567 // check for null pointer constant (C99 6.3.2.3p3)
568 if (!argExpr->isNullPointerConstant(Context)) {
569 Diag(l, diag::ext_typecheck_passing_pointer_int,
570 lhsType.getAsString(), rhsType.getAsString(),
571 Fn->getSourceRange(), argExpr->getSourceRange());
572 }
573 break;
574 case IntFromPointer:
575 Diag(l, diag::ext_typecheck_passing_pointer_int,
576 lhsType.getAsString(), rhsType.getAsString(),
577 Fn->getSourceRange(), argExpr->getSourceRange());
578 break;
579 case IncompatiblePointer:
580 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
581 rhsType.getAsString(), lhsType.getAsString(),
582 Fn->getSourceRange(), argExpr->getSourceRange());
583 break;
584 case CompatiblePointerDiscardsQualifiers:
585 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
586 rhsType.getAsString(), lhsType.getAsString(),
587 Fn->getSourceRange(), argExpr->getSourceRange());
588 break;
589 case Incompatible:
590 return Diag(l, diag::err_typecheck_passing_incompatible,
591 rhsType.getAsString(), lhsType.getAsString(),
592 Fn->getSourceRange(), argExpr->getSourceRange());
593 }
594 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000595 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
596 // Promote the arguments (C99 6.5.2.2p7).
597 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
598 Expr *argExpr = Args[i];
599 assert(argExpr && "ParseCallExpr(): missing argument expression");
600
601 DefaultArgumentPromotion(argExpr);
602 if (Args[i] != argExpr) // The expression was converted.
603 Args[i] = argExpr; // Make sure we store the converted expression.
604 }
605 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
606 // Even if the types checked, bail if the number of arguments don't match.
Chris Lattner4b009652007-07-25 00:24:17 +0000607 return true;
Steve Naroffdb65e052007-08-28 23:30:39 +0000608 }
609 } else if (isa<FunctionTypeNoProto>(funcT)) {
610 // Promote the arguments (C99 6.5.2.2p6).
611 for (unsigned i = 0; i < NumArgsInCall; i++) {
612 Expr *argExpr = Args[i];
613 assert(argExpr && "ParseCallExpr(): missing argument expression");
614
615 DefaultArgumentPromotion(argExpr);
616 if (Args[i] != argExpr) // The expression was converted.
617 Args[i] = argExpr; // Make sure we store the converted expression.
618 }
Chris Lattner4b009652007-07-25 00:24:17 +0000619 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000620 // Do special checking on direct calls to functions.
621 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
622 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
623 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000624 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
625 NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000626 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000627
Chris Lattner4b009652007-07-25 00:24:17 +0000628 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
629}
630
631Action::ExprResult Sema::
632ParseCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
633 SourceLocation RParenLoc, ExprTy *InitExpr) {
634 assert((Ty != 0) && "ParseCompoundLiteral(): missing type");
635 QualType literalType = QualType::getFromOpaquePtr(Ty);
636 // FIXME: put back this assert when initializers are worked out.
637 //assert((InitExpr != 0) && "ParseCompoundLiteral(): missing expression");
638 Expr *literalExpr = static_cast<Expr*>(InitExpr);
639
640 // FIXME: add semantic analysis (C99 6.5.2.5).
641 return new CompoundLiteralExpr(literalType, literalExpr);
642}
643
644Action::ExprResult Sema::
Anders Carlsson762b7c72007-08-31 04:56:16 +0000645ParseInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
646 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000647 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000648
Steve Naroff1c9de712007-09-03 01:24:23 +0000649 // Semantic analysis for initializers is done by ParseDeclarator() and
650 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000651
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000652 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
653 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
654 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000655}
656
657Action::ExprResult Sema::
658ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
659 SourceLocation RParenLoc, ExprTy *Op) {
660 assert((Ty != 0) && (Op != 0) && "ParseCastExpr(): missing type or expr");
661
662 Expr *castExpr = static_cast<Expr*>(Op);
663 QualType castType = QualType::getFromOpaquePtr(Ty);
664
Steve Naroff68adb482007-08-31 00:32:44 +0000665 UsualUnaryConversions(castExpr);
666
Chris Lattner4b009652007-07-25 00:24:17 +0000667 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
668 // type needs to be scalar.
669 if (!castType->isScalarType() && !castType->isVoidType()) {
670 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
671 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
672 }
673 if (!castExpr->getType()->isScalarType()) {
674 return Diag(castExpr->getLocStart(),
675 diag::err_typecheck_expect_scalar_operand,
676 castExpr->getType().getAsString(), castExpr->getSourceRange());
677 }
678 return new CastExpr(castType, castExpr, LParenLoc);
679}
680
681inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
682 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
683 UsualUnaryConversions(cond);
684 UsualUnaryConversions(lex);
685 UsualUnaryConversions(rex);
686 QualType condT = cond->getType();
687 QualType lexT = lex->getType();
688 QualType rexT = rex->getType();
689
690 // first, check the condition.
691 if (!condT->isScalarType()) { // C99 6.5.15p2
692 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
693 condT.getAsString());
694 return QualType();
695 }
696 // now check the two expressions.
697 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
698 UsualArithmeticConversions(lex, rex);
699 return lex->getType();
700 }
Chris Lattner71225142007-07-31 21:27:01 +0000701 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
702 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
703
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000704 if (LHSRT->getDecl()->getIdentifier() ==RHSRT->getDecl()->getIdentifier())
Chris Lattner71225142007-07-31 21:27:01 +0000705 return lexT;
706
Chris Lattner4b009652007-07-25 00:24:17 +0000707 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
708 lexT.getAsString(), rexT.getAsString(),
709 lex->getSourceRange(), rex->getSourceRange());
710 return QualType();
711 }
712 }
713 // C99 6.5.15p3
714 if (lexT->isPointerType() && rex->isNullPointerConstant(Context))
715 return lexT;
716 if (rexT->isPointerType() && lex->isNullPointerConstant(Context))
717 return rexT;
718
Chris Lattner71225142007-07-31 21:27:01 +0000719 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
720 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
721 // get the "pointed to" types
722 QualType lhptee = LHSPT->getPointeeType();
723 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000724
Chris Lattner71225142007-07-31 21:27:01 +0000725 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
726 if (lhptee->isVoidType() &&
727 (rhptee->isObjectType() || rhptee->isIncompleteType()))
728 return lexT;
729 if (rhptee->isVoidType() &&
730 (lhptee->isObjectType() || lhptee->isIncompleteType()))
731 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000732
Chris Lattner71225142007-07-31 21:27:01 +0000733 if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
734 rhptee.getUnqualifiedType())) {
735 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
736 lexT.getAsString(), rexT.getAsString(),
737 lex->getSourceRange(), rex->getSourceRange());
738 return lexT; // FIXME: this is an _ext - is this return o.k?
739 }
740 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000741 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
742 // differently qualified versions of compatible types, the result type is
743 // a pointer to an appropriately qualified version of the *composite*
744 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000745 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000746 }
Chris Lattner4b009652007-07-25 00:24:17 +0000747 }
Chris Lattner71225142007-07-31 21:27:01 +0000748
Chris Lattner4b009652007-07-25 00:24:17 +0000749 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
750 return lexT;
751
752 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
753 lexT.getAsString(), rexT.getAsString(),
754 lex->getSourceRange(), rex->getSourceRange());
755 return QualType();
756}
757
758/// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
759/// in the case of a the GNU conditional expr extension.
760Action::ExprResult Sema::ParseConditionalOp(SourceLocation QuestionLoc,
761 SourceLocation ColonLoc,
762 ExprTy *Cond, ExprTy *LHS,
763 ExprTy *RHS) {
764 Expr *CondExpr = (Expr *) Cond;
765 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
766 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
767 RHSExpr, QuestionLoc);
768 if (result.isNull())
769 return true;
770 return new ConditionalOperator(CondExpr, LHSExpr, RHSExpr, result);
771}
772
773// promoteExprToType - a helper function to ensure we create exactly one
774// ImplicitCastExpr. As a convenience (to the caller), we return the type.
775static void promoteExprToType(Expr *&expr, QualType type) {
776 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
777 impCast->setType(type);
778 else
779 expr = new ImplicitCastExpr(type, expr);
780 return;
781}
782
Steve Naroffdb65e052007-08-28 23:30:39 +0000783/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
784/// do not have a prototype. Integer promotions are performed on each
785/// argument, and arguments that have type float are promoted to double.
786void Sema::DefaultArgumentPromotion(Expr *&expr) {
787 QualType t = expr->getType();
788 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
789
790 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
791 promoteExprToType(expr, Context.IntTy);
792 if (t == Context.FloatTy)
793 promoteExprToType(expr, Context.DoubleTy);
794}
795
Chris Lattner4b009652007-07-25 00:24:17 +0000796/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
797void Sema::DefaultFunctionArrayConversion(Expr *&e) {
798 QualType t = e->getType();
799 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
800
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000801 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000802 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
803 t = e->getType();
804 }
805 if (t->isFunctionType())
806 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000807 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000808 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
809}
810
811/// UsualUnaryConversion - Performs various conversions that are common to most
812/// operators (C99 6.3). The conversions of array and function types are
813/// sometimes surpressed. For example, the array->pointer conversion doesn't
814/// apply if the array is an argument to the sizeof or address (&) operators.
815/// In these instances, this routine should *not* be called.
816void Sema::UsualUnaryConversions(Expr *&expr) {
817 QualType t = expr->getType();
818 assert(!t.isNull() && "UsualUnaryConversions - missing type");
819
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000820 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000821 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
822 t = expr->getType();
823 }
824 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
825 promoteExprToType(expr, Context.IntTy);
826 else
827 DefaultFunctionArrayConversion(expr);
828}
829
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000830/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000831/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
832/// routine returns the first non-arithmetic type found. The client is
833/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000834QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
835 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000836 if (!isCompAssign) {
837 UsualUnaryConversions(lhsExpr);
838 UsualUnaryConversions(rhsExpr);
839 }
Chris Lattner4b009652007-07-25 00:24:17 +0000840 QualType lhs = lhsExpr->getType();
841 QualType rhs = rhsExpr->getType();
842
843 // If both types are identical, no conversion is needed.
844 if (lhs == rhs)
Steve Naroff8f708362007-08-24 19:07:16 +0000845 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000846
847 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
848 // The caller can deal with this (e.g. pointer + int).
849 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000850 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000851
852 // At this point, we have two different arithmetic types.
853
854 // Handle complex types first (C99 6.3.1.8p1).
855 if (lhs->isComplexType() || rhs->isComplexType()) {
856 // if we have an integer operand, the result is the complex type.
857 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000858 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
859 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000860 }
861 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000862 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
863 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000864 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000865 // This handles complex/complex, complex/float, or float/complex.
866 // When both operands are complex, the shorter operand is converted to the
867 // type of the longer, and that is the type of the result. This corresponds
868 // to what is done when combining two real floating-point operands.
869 // The fun begins when size promotion occur across type domains.
870 // From H&S 6.3.4: When one operand is complex and the other is a real
871 // floating-point type, the less precise type is converted, within it's
872 // real or complex domain, to the precision of the other type. For example,
873 // when combining a "long double" with a "double _Complex", the
874 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000875 int result = Context.compareFloatingType(lhs, rhs);
876
877 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000878 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
879 if (!isCompAssign)
880 promoteExprToType(rhsExpr, rhs);
881 } else if (result < 0) { // The right side is bigger, convert lhs.
882 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
883 if (!isCompAssign)
884 promoteExprToType(lhsExpr, lhs);
885 }
886 // At this point, lhs and rhs have the same rank/size. Now, make sure the
887 // domains match. This is a requirement for our implementation, C99
888 // does not require this promotion.
889 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
890 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000891 if (!isCompAssign)
892 promoteExprToType(lhsExpr, rhs);
893 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000894 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000895 if (!isCompAssign)
896 promoteExprToType(rhsExpr, lhs);
897 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000898 }
Chris Lattner4b009652007-07-25 00:24:17 +0000899 }
Steve Naroff3b6157f2007-08-27 21:43:43 +0000900 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +0000901 }
902 // Now handle "real" floating types (i.e. float, double, long double).
903 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
904 // if we have an integer operand, the result is the real floating type.
905 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000906 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
907 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000908 }
909 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +0000910 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
911 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000912 }
913 // We have two real floating types, float/complex combos were handled above.
914 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +0000915 int result = Context.compareFloatingType(lhs, rhs);
916
917 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000918 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
919 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000920 }
Steve Naroff45fc9822007-08-27 15:30:22 +0000921 if (result < 0) { // convert the lhs
922 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
923 return rhs;
924 }
925 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +0000926 }
927 // Finally, we have two differing integer types.
928 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +0000929 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
930 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000931 }
Steve Naroff8f708362007-08-24 19:07:16 +0000932 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
933 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000934}
935
936// CheckPointerTypesForAssignment - This is a very tricky routine (despite
937// being closely modeled after the C99 spec:-). The odd characteristic of this
938// routine is it effectively iqnores the qualifiers on the top level pointee.
939// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
940// FIXME: add a couple examples in this comment.
941Sema::AssignmentCheckResult
942Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
943 QualType lhptee, rhptee;
944
945 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +0000946 lhptee = lhsType->getAsPointerType()->getPointeeType();
947 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000948
949 // make sure we operate on the canonical type
950 lhptee = lhptee.getCanonicalType();
951 rhptee = rhptee.getCanonicalType();
952
953 AssignmentCheckResult r = Compatible;
954
955 // C99 6.5.16.1p1: This following citation is common to constraints
956 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
957 // qualifiers of the type *pointed to* by the right;
958 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
959 rhptee.getQualifiers())
960 r = CompatiblePointerDiscardsQualifiers;
961
962 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
963 // incomplete type and the other is a pointer to a qualified or unqualified
964 // version of void...
965 if (lhptee.getUnqualifiedType()->isVoidType() &&
966 (rhptee->isObjectType() || rhptee->isIncompleteType()))
967 ;
968 else if (rhptee.getUnqualifiedType()->isVoidType() &&
969 (lhptee->isObjectType() || lhptee->isIncompleteType()))
970 ;
971 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
972 // unqualified versions of compatible types, ...
973 else if (!Type::typesAreCompatible(lhptee.getUnqualifiedType(),
974 rhptee.getUnqualifiedType()))
975 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
976 return r;
977}
978
979/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
980/// has code to accommodate several GCC extensions when type checking
981/// pointers. Here are some objectionable examples that GCC considers warnings:
982///
983/// int a, *pint;
984/// short *pshort;
985/// struct foo *pfoo;
986///
987/// pint = pshort; // warning: assignment from incompatible pointer type
988/// a = pint; // warning: assignment makes integer from pointer without a cast
989/// pint = a; // warning: assignment makes pointer from integer without a cast
990/// pint = pfoo; // warning: assignment from incompatible pointer type
991///
992/// As a result, the code for dealing with pointers is more complex than the
993/// C99 spec dictates.
994/// Note: the warning above turn into errors when -pedantic-errors is enabled.
995///
996Sema::AssignmentCheckResult
997Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
998 if (lhsType == rhsType) // common case, fast path...
999 return Compatible;
1000
1001 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
1002 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1003 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1004 return Incompatible;
1005 }
1006 return Compatible;
1007 } else if (lhsType->isPointerType()) {
1008 if (rhsType->isIntegerType())
1009 return PointerFromInt;
1010
1011 if (rhsType->isPointerType())
1012 return CheckPointerTypesForAssignment(lhsType, rhsType);
1013 } else if (rhsType->isPointerType()) {
1014 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1015 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1016 return IntFromPointer;
1017
1018 if (lhsType->isPointerType())
1019 return CheckPointerTypesForAssignment(lhsType, rhsType);
1020 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
1021 if (Type::tagTypesAreCompatible(lhsType, rhsType))
1022 return Compatible;
1023 } else if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
1024 if (Type::referenceTypesAreCompatible(lhsType, rhsType))
1025 return Compatible;
1026 }
1027 return Incompatible;
1028}
1029
1030Sema::AssignmentCheckResult
1031Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
1032 // This check seems unnatural, however it is necessary to insure the proper
1033 // conversion of functions/arrays. If the conversion were done for all
1034 // DeclExpr's (created by ParseIdentifierExpr), it would mess up the unary
1035 // expressions that surpress this implicit conversion (&, sizeof).
1036 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001037
1038 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +00001039
Steve Naroff0f32f432007-08-24 22:33:52 +00001040 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1041
1042 // C99 6.5.16.1p2: The value of the right operand is converted to the
1043 // type of the assignment expression.
1044 if (rExpr->getType() != lhsType)
1045 promoteExprToType(rExpr, lhsType);
1046 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001047}
1048
1049Sema::AssignmentCheckResult
1050Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1051 return CheckAssignmentConstraints(lhsType, rhsType);
1052}
1053
1054inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1055 Diag(loc, diag::err_typecheck_invalid_operands,
1056 lex->getType().getAsString(), rex->getType().getAsString(),
1057 lex->getSourceRange(), rex->getSourceRange());
1058}
1059
1060inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1061 Expr *&rex) {
1062 QualType lhsType = lex->getType(), rhsType = rex->getType();
1063
1064 // make sure the vector types are identical.
1065 if (lhsType == rhsType)
1066 return lhsType;
1067 // You cannot convert between vector values of different size.
1068 Diag(loc, diag::err_typecheck_vector_not_convertable,
1069 lex->getType().getAsString(), rex->getType().getAsString(),
1070 lex->getSourceRange(), rex->getSourceRange());
1071 return QualType();
1072}
1073
1074inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001075 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001076{
1077 QualType lhsType = lex->getType(), rhsType = rex->getType();
1078
1079 if (lhsType->isVectorType() || rhsType->isVectorType())
1080 return CheckVectorOperands(loc, lex, rex);
1081
Steve Naroff8f708362007-08-24 19:07:16 +00001082 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001083
Chris Lattner4b009652007-07-25 00:24:17 +00001084 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001085 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001086 InvalidOperands(loc, lex, rex);
1087 return QualType();
1088}
1089
1090inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001091 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001092{
1093 QualType lhsType = lex->getType(), rhsType = rex->getType();
1094
Steve Naroff8f708362007-08-24 19:07:16 +00001095 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001096
Chris Lattner4b009652007-07-25 00:24:17 +00001097 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001098 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001099 InvalidOperands(loc, lex, rex);
1100 return QualType();
1101}
1102
1103inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001104 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001105{
1106 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1107 return CheckVectorOperands(loc, lex, rex);
1108
Steve Naroff8f708362007-08-24 19:07:16 +00001109 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001110
1111 // handle the common case first (both operands are arithmetic).
1112 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001113 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001114
1115 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1116 return lex->getType();
1117 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1118 return rex->getType();
1119 InvalidOperands(loc, lex, rex);
1120 return QualType();
1121}
1122
1123inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001124 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001125{
1126 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1127 return CheckVectorOperands(loc, lex, rex);
1128
Steve Naroff8f708362007-08-24 19:07:16 +00001129 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001130
1131 // handle the common case first (both operands are arithmetic).
1132 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001133 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001134
1135 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001136 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001137 if (lex->getType()->isPointerType() && rex->getType()->isPointerType())
1138 return Context.getPointerDiffType();
1139 InvalidOperands(loc, lex, rex);
1140 return QualType();
1141}
1142
1143inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001144 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001145{
1146 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1147 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001148 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001149
1150 // handle the common case first (both operands are arithmetic).
1151 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001152 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001153 InvalidOperands(loc, lex, rex);
1154 return QualType();
1155}
1156
Chris Lattner254f3bc2007-08-26 01:18:55 +00001157inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1158 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001159{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001160 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001161 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1162 UsualArithmeticConversions(lex, rex);
1163 else {
1164 UsualUnaryConversions(lex);
1165 UsualUnaryConversions(rex);
1166 }
Chris Lattner4b009652007-07-25 00:24:17 +00001167 QualType lType = lex->getType();
1168 QualType rType = rex->getType();
1169
Chris Lattner254f3bc2007-08-26 01:18:55 +00001170 if (isRelational) {
1171 if (lType->isRealType() && rType->isRealType())
1172 return Context.IntTy;
1173 } else {
Chris Lattnerbd3cc222007-08-30 06:10:41 +00001174 if (lType->isFloatingType() && rType->isFloatingType())
Ted Kremenekec761af2007-08-29 18:06:12 +00001175 Diag(loc, diag::warn_floatingpoint_eq);
1176
Chris Lattner254f3bc2007-08-26 01:18:55 +00001177 if (lType->isArithmeticType() && rType->isArithmeticType())
1178 return Context.IntTy;
1179 }
Chris Lattner4b009652007-07-25 00:24:17 +00001180
Chris Lattner22be8422007-08-26 01:10:14 +00001181 bool LHSIsNull = lex->isNullPointerConstant(Context);
1182 bool RHSIsNull = rex->isNullPointerConstant(Context);
1183
Chris Lattner254f3bc2007-08-26 01:18:55 +00001184 // All of the following pointer related warnings are GCC extensions, except
1185 // when handling null pointer constants. One day, we can consider making them
1186 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001187 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner22be8422007-08-26 01:10:14 +00001188 if (!LHSIsNull && !RHSIsNull &&
Steve Naroffc33c0602007-08-27 04:08:11 +00001189 !Type::pointerTypesAreCompatible(lType.getUnqualifiedType(),
1190 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001191 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1192 lType.getAsString(), rType.getAsString(),
1193 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001194 }
Chris Lattner22be8422007-08-26 01:10:14 +00001195 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001196 return Context.IntTy;
1197 }
1198 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001199 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001200 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1201 lType.getAsString(), rType.getAsString(),
1202 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001203 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001204 return Context.IntTy;
1205 }
1206 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001207 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001208 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1209 lType.getAsString(), rType.getAsString(),
1210 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001211 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001212 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001213 }
1214 InvalidOperands(loc, lex, rex);
1215 return QualType();
1216}
1217
Chris Lattner4b009652007-07-25 00:24:17 +00001218inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001219 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001220{
1221 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1222 return CheckVectorOperands(loc, lex, rex);
1223
Steve Naroff8f708362007-08-24 19:07:16 +00001224 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001225
1226 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001227 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001228 InvalidOperands(loc, lex, rex);
1229 return QualType();
1230}
1231
1232inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1233 Expr *&lex, Expr *&rex, SourceLocation loc)
1234{
1235 UsualUnaryConversions(lex);
1236 UsualUnaryConversions(rex);
1237
1238 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1239 return Context.IntTy;
1240 InvalidOperands(loc, lex, rex);
1241 return QualType();
1242}
1243
1244inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001245 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001246{
1247 QualType lhsType = lex->getType();
1248 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1249 bool hadError = false;
1250 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1251
1252 switch (mlval) { // C99 6.5.16p2
1253 case Expr::MLV_Valid:
1254 break;
1255 case Expr::MLV_ConstQualified:
1256 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1257 hadError = true;
1258 break;
1259 case Expr::MLV_ArrayType:
1260 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1261 lhsType.getAsString(), lex->getSourceRange());
1262 return QualType();
1263 case Expr::MLV_NotObjectType:
1264 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1265 lhsType.getAsString(), lex->getSourceRange());
1266 return QualType();
1267 case Expr::MLV_InvalidExpression:
1268 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1269 lex->getSourceRange());
1270 return QualType();
1271 case Expr::MLV_IncompleteType:
1272 case Expr::MLV_IncompleteVoidType:
1273 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1274 lhsType.getAsString(), lex->getSourceRange());
1275 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001276 case Expr::MLV_DuplicateVectorComponents:
1277 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1278 lex->getSourceRange());
1279 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001280 }
1281 AssignmentCheckResult result;
1282
1283 if (compoundType.isNull())
1284 result = CheckSingleAssignmentConstraints(lhsType, rex);
1285 else
1286 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001287
Chris Lattner4b009652007-07-25 00:24:17 +00001288 // decode the result (notice that extensions still return a type).
1289 switch (result) {
1290 case Compatible:
1291 break;
1292 case Incompatible:
1293 Diag(loc, diag::err_typecheck_assign_incompatible,
1294 lhsType.getAsString(), rhsType.getAsString(),
1295 lex->getSourceRange(), rex->getSourceRange());
1296 hadError = true;
1297 break;
1298 case PointerFromInt:
1299 // check for null pointer constant (C99 6.3.2.3p3)
1300 if (compoundType.isNull() && !rex->isNullPointerConstant(Context)) {
1301 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1302 lhsType.getAsString(), rhsType.getAsString(),
1303 lex->getSourceRange(), rex->getSourceRange());
1304 }
1305 break;
1306 case IntFromPointer:
1307 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1308 lhsType.getAsString(), rhsType.getAsString(),
1309 lex->getSourceRange(), rex->getSourceRange());
1310 break;
1311 case IncompatiblePointer:
1312 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1313 lhsType.getAsString(), rhsType.getAsString(),
1314 lex->getSourceRange(), rex->getSourceRange());
1315 break;
1316 case CompatiblePointerDiscardsQualifiers:
1317 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1318 lhsType.getAsString(), rhsType.getAsString(),
1319 lex->getSourceRange(), rex->getSourceRange());
1320 break;
1321 }
1322 // C99 6.5.16p3: The type of an assignment expression is the type of the
1323 // left operand unless the left operand has qualified type, in which case
1324 // it is the unqualified version of the type of the left operand.
1325 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1326 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001327 // C++ 5.17p1: the type of the assignment expression is that of its left
1328 // oprdu.
Chris Lattner4b009652007-07-25 00:24:17 +00001329 return hadError ? QualType() : lhsType.getUnqualifiedType();
1330}
1331
1332inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1333 Expr *&lex, Expr *&rex, SourceLocation loc) {
1334 UsualUnaryConversions(rex);
1335 return rex->getType();
1336}
1337
1338/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1339/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1340QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1341 QualType resType = op->getType();
1342 assert(!resType.isNull() && "no type for increment/decrement expression");
1343
Steve Naroffd30e1932007-08-24 17:20:07 +00001344 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattner4b009652007-07-25 00:24:17 +00001345 if (const PointerType *pt = dyn_cast<PointerType>(resType)) {
1346 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1347 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1348 resType.getAsString(), op->getSourceRange());
1349 return QualType();
1350 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001351 } else if (!resType->isRealType()) {
1352 if (resType->isComplexType())
1353 // C99 does not support ++/-- on complex types.
1354 Diag(OpLoc, diag::ext_integer_increment_complex,
1355 resType.getAsString(), op->getSourceRange());
1356 else {
1357 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1358 resType.getAsString(), op->getSourceRange());
1359 return QualType();
1360 }
Chris Lattner4b009652007-07-25 00:24:17 +00001361 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001362 // At this point, we know we have a real, complex or pointer type.
1363 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001364 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1365 if (mlval != Expr::MLV_Valid) {
1366 // FIXME: emit a more precise diagnostic...
1367 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1368 op->getSourceRange());
1369 return QualType();
1370 }
1371 return resType;
1372}
1373
1374/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1375/// This routine allows us to typecheck complex/recursive expressions
1376/// where the declaration is needed for type checking. Here are some
1377/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1378static Decl *getPrimaryDeclaration(Expr *e) {
1379 switch (e->getStmtClass()) {
1380 case Stmt::DeclRefExprClass:
1381 return cast<DeclRefExpr>(e)->getDecl();
1382 case Stmt::MemberExprClass:
1383 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1384 case Stmt::ArraySubscriptExprClass:
1385 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
1386 case Stmt::CallExprClass:
1387 return getPrimaryDeclaration(cast<CallExpr>(e)->getCallee());
1388 case Stmt::UnaryOperatorClass:
1389 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1390 case Stmt::ParenExprClass:
1391 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
1392 default:
1393 return 0;
1394 }
1395}
1396
1397/// CheckAddressOfOperand - The operand of & must be either a function
1398/// designator or an lvalue designating an object. If it is an lvalue, the
1399/// object cannot be declared with storage class register or be a bit field.
1400/// Note: The usual conversions are *not* applied to the operand of the &
1401/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1402QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1403 Decl *dcl = getPrimaryDeclaration(op);
1404 Expr::isLvalueResult lval = op->isLvalue();
1405
1406 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1407 if (dcl && isa<FunctionDecl>(dcl)) // allow function designators
1408 ;
1409 else { // FIXME: emit more specific diag...
1410 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1411 op->getSourceRange());
1412 return QualType();
1413 }
1414 } else if (dcl) {
1415 // We have an lvalue with a decl. Make sure the decl is not declared
1416 // with the register storage-class specifier.
1417 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1418 if (vd->getStorageClass() == VarDecl::Register) {
1419 Diag(OpLoc, diag::err_typecheck_address_of_register,
1420 op->getSourceRange());
1421 return QualType();
1422 }
1423 } else
1424 assert(0 && "Unknown/unexpected decl type");
1425
1426 // FIXME: add check for bitfields!
1427 }
1428 // If the operand has type "type", the result has type "pointer to type".
1429 return Context.getPointerType(op->getType());
1430}
1431
1432QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1433 UsualUnaryConversions(op);
1434 QualType qType = op->getType();
1435
Chris Lattner7931f4a2007-07-31 16:53:04 +00001436 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001437 QualType ptype = PT->getPointeeType();
1438 // C99 6.5.3.2p4. "if it points to an object,...".
1439 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1440 // GCC compat: special case 'void *' (treat as warning).
1441 if (ptype->isVoidType()) {
1442 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1443 qType.getAsString(), op->getSourceRange());
1444 } else {
1445 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1446 ptype.getAsString(), op->getSourceRange());
1447 return QualType();
1448 }
1449 }
1450 return ptype;
1451 }
1452 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1453 qType.getAsString(), op->getSourceRange());
1454 return QualType();
1455}
1456
1457static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1458 tok::TokenKind Kind) {
1459 BinaryOperator::Opcode Opc;
1460 switch (Kind) {
1461 default: assert(0 && "Unknown binop!");
1462 case tok::star: Opc = BinaryOperator::Mul; break;
1463 case tok::slash: Opc = BinaryOperator::Div; break;
1464 case tok::percent: Opc = BinaryOperator::Rem; break;
1465 case tok::plus: Opc = BinaryOperator::Add; break;
1466 case tok::minus: Opc = BinaryOperator::Sub; break;
1467 case tok::lessless: Opc = BinaryOperator::Shl; break;
1468 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1469 case tok::lessequal: Opc = BinaryOperator::LE; break;
1470 case tok::less: Opc = BinaryOperator::LT; break;
1471 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1472 case tok::greater: Opc = BinaryOperator::GT; break;
1473 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1474 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1475 case tok::amp: Opc = BinaryOperator::And; break;
1476 case tok::caret: Opc = BinaryOperator::Xor; break;
1477 case tok::pipe: Opc = BinaryOperator::Or; break;
1478 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1479 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1480 case tok::equal: Opc = BinaryOperator::Assign; break;
1481 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1482 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1483 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1484 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1485 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1486 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1487 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1488 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1489 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1490 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1491 case tok::comma: Opc = BinaryOperator::Comma; break;
1492 }
1493 return Opc;
1494}
1495
1496static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1497 tok::TokenKind Kind) {
1498 UnaryOperator::Opcode Opc;
1499 switch (Kind) {
1500 default: assert(0 && "Unknown unary op!");
1501 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1502 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1503 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1504 case tok::star: Opc = UnaryOperator::Deref; break;
1505 case tok::plus: Opc = UnaryOperator::Plus; break;
1506 case tok::minus: Opc = UnaryOperator::Minus; break;
1507 case tok::tilde: Opc = UnaryOperator::Not; break;
1508 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1509 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1510 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1511 case tok::kw___real: Opc = UnaryOperator::Real; break;
1512 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1513 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1514 }
1515 return Opc;
1516}
1517
1518// Binary Operators. 'Tok' is the token for the operator.
1519Action::ExprResult Sema::ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1520 ExprTy *LHS, ExprTy *RHS) {
1521 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1522 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1523
1524 assert((lhs != 0) && "ParseBinOp(): missing left expression");
1525 assert((rhs != 0) && "ParseBinOp(): missing right expression");
1526
1527 QualType ResultTy; // Result type of the binary operator.
1528 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1529
1530 switch (Opc) {
1531 default:
1532 assert(0 && "Unknown binary expr!");
1533 case BinaryOperator::Assign:
1534 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1535 break;
1536 case BinaryOperator::Mul:
1537 case BinaryOperator::Div:
1538 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1539 break;
1540 case BinaryOperator::Rem:
1541 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1542 break;
1543 case BinaryOperator::Add:
1544 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1545 break;
1546 case BinaryOperator::Sub:
1547 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1548 break;
1549 case BinaryOperator::Shl:
1550 case BinaryOperator::Shr:
1551 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1552 break;
1553 case BinaryOperator::LE:
1554 case BinaryOperator::LT:
1555 case BinaryOperator::GE:
1556 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001557 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001558 break;
1559 case BinaryOperator::EQ:
1560 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001561 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001562 break;
1563 case BinaryOperator::And:
1564 case BinaryOperator::Xor:
1565 case BinaryOperator::Or:
1566 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1567 break;
1568 case BinaryOperator::LAnd:
1569 case BinaryOperator::LOr:
1570 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1571 break;
1572 case BinaryOperator::MulAssign:
1573 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001574 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001575 if (!CompTy.isNull())
1576 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1577 break;
1578 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001579 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001580 if (!CompTy.isNull())
1581 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1582 break;
1583 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001584 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001585 if (!CompTy.isNull())
1586 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1587 break;
1588 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001589 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001590 if (!CompTy.isNull())
1591 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1592 break;
1593 case BinaryOperator::ShlAssign:
1594 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001595 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001596 if (!CompTy.isNull())
1597 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1598 break;
1599 case BinaryOperator::AndAssign:
1600 case BinaryOperator::XorAssign:
1601 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001602 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001603 if (!CompTy.isNull())
1604 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1605 break;
1606 case BinaryOperator::Comma:
1607 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1608 break;
1609 }
1610 if (ResultTy.isNull())
1611 return true;
1612 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001613 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001614 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001615 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001616}
1617
1618// Unary Operators. 'Tok' is the token for the operator.
1619Action::ExprResult Sema::ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
1620 ExprTy *input) {
1621 Expr *Input = (Expr*)input;
1622 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1623 QualType resultType;
1624 switch (Opc) {
1625 default:
1626 assert(0 && "Unimplemented unary expr!");
1627 case UnaryOperator::PreInc:
1628 case UnaryOperator::PreDec:
1629 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1630 break;
1631 case UnaryOperator::AddrOf:
1632 resultType = CheckAddressOfOperand(Input, OpLoc);
1633 break;
1634 case UnaryOperator::Deref:
1635 resultType = CheckIndirectionOperand(Input, OpLoc);
1636 break;
1637 case UnaryOperator::Plus:
1638 case UnaryOperator::Minus:
1639 UsualUnaryConversions(Input);
1640 resultType = Input->getType();
1641 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1642 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1643 resultType.getAsString());
1644 break;
1645 case UnaryOperator::Not: // bitwise complement
1646 UsualUnaryConversions(Input);
1647 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001648 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1649 if (!resultType->isIntegerType()) {
1650 if (resultType->isComplexType())
1651 // C99 does not support '~' for complex conjugation.
1652 Diag(OpLoc, diag::ext_integer_complement_complex,
1653 resultType.getAsString());
1654 else
1655 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1656 resultType.getAsString());
1657 }
Chris Lattner4b009652007-07-25 00:24:17 +00001658 break;
1659 case UnaryOperator::LNot: // logical negation
1660 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1661 DefaultFunctionArrayConversion(Input);
1662 resultType = Input->getType();
1663 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1664 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1665 resultType.getAsString());
1666 // LNot always has type int. C99 6.5.3.3p5.
1667 resultType = Context.IntTy;
1668 break;
1669 case UnaryOperator::SizeOf:
1670 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1671 break;
1672 case UnaryOperator::AlignOf:
1673 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1674 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001675 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001676 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001677 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001678 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001679 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001680 resultType = Input->getType();
1681 break;
1682 }
1683 if (resultType.isNull())
1684 return true;
1685 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1686}
1687
1688/// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
1689Sema::ExprResult Sema::ParseAddrLabel(SourceLocation OpLoc,
1690 SourceLocation LabLoc,
1691 IdentifierInfo *LabelII) {
1692 // Look up the record for this label identifier.
1693 LabelStmt *&LabelDecl = LabelMap[LabelII];
1694
1695 // If we haven't seen this label yet, create a forward reference.
1696 if (LabelDecl == 0)
1697 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1698
1699 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001700 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1701 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001702}
1703
1704Sema::ExprResult Sema::ParseStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
1705 SourceLocation RPLoc) { // "({..})"
1706 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1707 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1708 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1709
1710 // FIXME: there are a variety of strange constraints to enforce here, for
1711 // example, it is not possible to goto into a stmt expression apparently.
1712 // More semantic analysis is needed.
1713
1714 // FIXME: the last statement in the compount stmt has its value used. We
1715 // should not warn about it being unused.
1716
1717 // If there are sub stmts in the compound stmt, take the type of the last one
1718 // as the type of the stmtexpr.
1719 QualType Ty = Context.VoidTy;
1720
1721 if (!Compound->body_empty())
1722 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1723 Ty = LastExpr->getType();
1724
1725 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1726}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001727
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001728Sema::ExprResult Sema::ParseBuiltinOffsetOf(SourceLocation BuiltinLoc,
1729 SourceLocation TypeLoc,
1730 TypeTy *argty,
1731 OffsetOfComponent *CompPtr,
1732 unsigned NumComponents,
1733 SourceLocation RPLoc) {
1734 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1735 assert(!ArgTy.isNull() && "Missing type argument!");
1736
1737 // We must have at least one component that refers to the type, and the first
1738 // one is known to be a field designator. Verify that the ArgTy represents
1739 // a struct/union/class.
1740 if (!ArgTy->isRecordType())
1741 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1742
1743 // Otherwise, create a compound literal expression as the base, and
1744 // iteratively process the offsetof designators.
1745 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1746
Chris Lattnerb37522e2007-08-31 21:49:13 +00001747 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1748 // GCC extension, diagnose them.
1749 if (NumComponents != 1)
1750 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1751 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1752
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001753 for (unsigned i = 0; i != NumComponents; ++i) {
1754 const OffsetOfComponent &OC = CompPtr[i];
1755 if (OC.isBrackets) {
1756 // Offset of an array sub-field. TODO: Should we allow vector elements?
1757 const ArrayType *AT = Res->getType()->getAsArrayType();
1758 if (!AT) {
1759 delete Res;
1760 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1761 Res->getType().getAsString());
1762 }
1763
Chris Lattner2af6a802007-08-30 17:59:59 +00001764 // FIXME: C++: Verify that operator[] isn't overloaded.
1765
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001766 // C99 6.5.2.1p1
1767 Expr *Idx = static_cast<Expr*>(OC.U.E);
1768 if (!Idx->getType()->isIntegerType())
1769 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1770 Idx->getSourceRange());
1771
1772 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1773 continue;
1774 }
1775
1776 const RecordType *RC = Res->getType()->getAsRecordType();
1777 if (!RC) {
1778 delete Res;
1779 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1780 Res->getType().getAsString());
1781 }
1782
1783 // Get the decl corresponding to this.
1784 RecordDecl *RD = RC->getDecl();
1785 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1786 if (!MemberDecl)
1787 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1788 OC.U.IdentInfo->getName(),
1789 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00001790
1791 // FIXME: C++: Verify that MemberDecl isn't a static field.
1792 // FIXME: Verify that MemberDecl isn't a bitfield.
1793
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001794 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1795 }
1796
1797 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1798 BuiltinLoc);
1799}
1800
1801
Steve Naroff5b528922007-08-01 23:45:51 +00001802Sema::ExprResult Sema::ParseTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001803 TypeTy *arg1, TypeTy *arg2,
1804 SourceLocation RPLoc) {
1805 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1806 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1807
1808 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1809
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001810 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00001811}
1812
Steve Naroff93c53012007-08-03 21:21:27 +00001813Sema::ExprResult Sema::ParseChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
1814 ExprTy *expr1, ExprTy *expr2,
1815 SourceLocation RPLoc) {
1816 Expr *CondExpr = static_cast<Expr*>(cond);
1817 Expr *LHSExpr = static_cast<Expr*>(expr1);
1818 Expr *RHSExpr = static_cast<Expr*>(expr2);
1819
1820 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
1821
1822 // The conditional expression is required to be a constant expression.
1823 llvm::APSInt condEval(32);
1824 SourceLocation ExpLoc;
1825 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
1826 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
1827 CondExpr->getSourceRange());
1828
1829 // If the condition is > zero, then the AST type is the same as the LSHExpr.
1830 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
1831 RHSExpr->getType();
1832 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
1833}
1834
Anders Carlssona66cad42007-08-21 17:43:55 +00001835// TODO: Move this to SemaObjC.cpp
Anders Carlsson8be1d402007-08-22 15:14:15 +00001836Sema::ExprResult Sema::ParseObjCStringLiteral(ExprTy *string) {
Anders Carlssona66cad42007-08-21 17:43:55 +00001837 StringLiteral* S = static_cast<StringLiteral *>(string);
1838
1839 if (CheckBuiltinCFStringArgument(S))
1840 return true;
1841
1842 QualType t = Context.getCFConstantStringType();
1843 t = t.getQualifiedType(QualType::Const);
1844 t = Context.getPointerType(t);
1845
1846 return new ObjCStringLiteral(S, t);
1847}
Anders Carlsson8be1d402007-08-22 15:14:15 +00001848
1849Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1850 SourceLocation LParenLoc,
1851 TypeTy *Ty,
1852 SourceLocation RParenLoc) {
1853 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
1854
1855 QualType t = Context.getPointerType(Context.CharTy);
1856 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
1857}