blob: 0f5fe8ad0f26ae8120f5eb9115e38129d877d4fb [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"
Ted Kremenek30c66752007-11-25 00:58:00 +000015#include "SemaUtil.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
Steve Narofffa465d12007-10-02 20:01:56 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/AST/Expr.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000020#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Lex/Preprocessor.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Basic/SourceManager.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/TargetInfo.h"
27#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000028#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029using namespace clang;
30
Steve Naroff87d58b42007-09-16 03:34:24 +000031/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000032/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
33/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
34/// multiple tokens. However, the common case is that StringToks points to one
35/// string.
36///
37Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000038Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000039 assert(NumStringToks && "Must have at least one string!");
40
41 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
42 if (Literal.hadError)
43 return ExprResult(true);
44
45 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
46 for (unsigned i = 0; i != NumStringToks; ++i)
47 StringTokLocs.push_back(StringToks[i].getLocation());
48
49 // FIXME: handle wchar_t
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000050 QualType t;
51
52 if (Literal.Pascal)
53 t = Context.getPointerType(Context.UnsignedCharTy);
54 else
55 t = Context.getPointerType(Context.CharTy);
56
57 if (Literal.Pascal && Literal.GetStringLength() > 256)
58 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
59 SourceRange(StringToks[0].getLocation(),
60 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000061
62 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
63 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000064 Literal.AnyWide, t,
65 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000066 StringToks[NumStringToks-1].getLocation());
67}
68
69
Steve Naroff0acc9c92007-09-15 18:49:24 +000070/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000071/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
72/// identifier is used in an function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000073Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000074 IdentifierInfo &II,
75 bool HasTrailingLParen) {
76 // Could be enum-constant or decl.
Steve Narofff0c31dd2007-09-16 16:16:00 +000077 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Chris Lattner4b009652007-07-25 00:24:17 +000078 if (D == 0) {
79 // Otherwise, this could be an implicitly declared function reference (legal
80 // in C90, extension in C99).
81 if (HasTrailingLParen &&
82 // Not in C++.
83 !getLangOptions().CPlusPlus)
84 D = ImplicitlyDefineFunction(Loc, II, S);
85 else {
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000086 if (CurMethodDecl) {
87 ObjcInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
88 ObjcInterfaceDecl *clsDeclared;
Steve Naroff6b759ce2007-11-15 02:58:25 +000089 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
90 IdentifierInfo &II = Context.Idents.get("self");
91 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
92 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
93 static_cast<Expr*>(SelfExpr.Val), true, true);
94 }
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000095 }
Chris Lattner4b009652007-07-25 00:24:17 +000096 // If this name wasn't predeclared and if this is not a function call,
97 // diagnose the problem.
98 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
99 }
100 }
Steve Naroff91b03f72007-08-28 03:03:08 +0000101 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroffcae537d2007-08-28 18:45:29 +0000102 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000103 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000104 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000105 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000106 }
Chris Lattner4b009652007-07-25 00:24:17 +0000107 if (isa<TypedefDecl>(D))
108 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000109 if (isa<ObjcInterfaceDecl>(D))
110 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000111
112 assert(0 && "Invalid decl");
113 abort();
114}
115
Steve Naroff87d58b42007-09-16 03:34:24 +0000116Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000117 tok::TokenKind Kind) {
118 PreDefinedExpr::IdentType IT;
119
120 switch (Kind) {
121 default:
122 assert(0 && "Unknown simple primary expr!");
123 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
124 IT = PreDefinedExpr::Func;
125 break;
126 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
127 IT = PreDefinedExpr::Function;
128 break;
129 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
130 IT = PreDefinedExpr::PrettyFunction;
131 break;
132 }
133
134 // Pre-defined identifiers are always of type char *.
135 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
136}
137
Steve Naroff87d58b42007-09-16 03:34:24 +0000138Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000139 llvm::SmallString<16> CharBuffer;
140 CharBuffer.resize(Tok.getLength());
141 const char *ThisTokBegin = &CharBuffer[0];
142 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
143
144 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
145 Tok.getLocation(), PP);
146 if (Literal.hadError())
147 return ExprResult(true);
148 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
149 Tok.getLocation());
150}
151
Steve Naroff87d58b42007-09-16 03:34:24 +0000152Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000153 // fast path for a single digit (which is quite common). A single digit
154 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
155 if (Tok.getLength() == 1) {
156 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
157
Chris Lattner3496d522007-09-04 02:45:27 +0000158 unsigned IntSize = static_cast<unsigned>(
159 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000160 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
161 Context.IntTy,
162 Tok.getLocation()));
163 }
164 llvm::SmallString<512> IntegerBuffer;
165 IntegerBuffer.resize(Tok.getLength());
166 const char *ThisTokBegin = &IntegerBuffer[0];
167
168 // Get the spelling of the token, which eliminates trigraphs, etc.
169 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
170 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
171 Tok.getLocation(), PP);
172 if (Literal.hadError)
173 return ExprResult(true);
174
Chris Lattner1de66eb2007-08-26 03:42:43 +0000175 Expr *Res;
176
177 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000178 QualType Ty;
179 const llvm::fltSemantics *Format;
180 uint64_t Size; unsigned Align;
181
182 if (Literal.isFloat) {
183 Ty = Context.FloatTy;
184 Context.Target.getFloatInfo(Size, Align, Format, Tok.getLocation());
185 } else if (Literal.isLong) {
186 Ty = Context.LongDoubleTy;
187 Context.Target.getLongDoubleInfo(Size, Align, Format, Tok.getLocation());
188 } else {
189 Ty = Context.DoubleTy;
190 Context.Target.getDoubleInfo(Size, Align, Format, Tok.getLocation());
191 }
192
Ted Kremenekddedbe22007-11-29 00:56:49 +0000193 // isExact will be set by GetFloatValue().
194 bool isExact = false;
195
196 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
197 Ty, Tok.getLocation());
198
Chris Lattner1de66eb2007-08-26 03:42:43 +0000199 } else if (!Literal.isIntegerLiteral()) {
200 return ExprResult(true);
201 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000202 QualType t;
203
Neil Booth7421e9c2007-08-29 22:00:19 +0000204 // long long is a C99 feature.
205 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000206 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000207 Diag(Tok.getLocation(), diag::ext_longlong);
208
Chris Lattner4b009652007-07-25 00:24:17 +0000209 // Get the value in the widest-possible width.
210 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(Tok.getLocation()), 0);
211
212 if (Literal.GetIntegerValue(ResultVal)) {
213 // If this value didn't fit into uintmax_t, warn and force to ull.
214 Diag(Tok.getLocation(), diag::warn_integer_too_large);
215 t = Context.UnsignedLongLongTy;
216 assert(Context.getTypeSize(t, Tok.getLocation()) ==
217 ResultVal.getBitWidth() && "long long is not intmax_t?");
218 } else {
219 // If this value fits into a ULL, try to figure out what else it fits into
220 // according to the rules of C99 6.4.4.1p5.
221
222 // Octal, Hexadecimal, and integers with a U suffix are allowed to
223 // be an unsigned int.
224 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
225
226 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000227 if (!Literal.isLong && !Literal.isLongLong) {
228 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000229 unsigned IntSize = static_cast<unsigned>(
230 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000231 // Does it fit in a unsigned int?
232 if (ResultVal.isIntN(IntSize)) {
233 // Does it fit in a signed int?
234 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
235 t = Context.IntTy;
236 else if (AllowUnsigned)
237 t = Context.UnsignedIntTy;
238 }
239
240 if (!t.isNull())
241 ResultVal.trunc(IntSize);
242 }
243
244 // Are long/unsigned long possibilities?
245 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000246 unsigned LongSize = static_cast<unsigned>(
247 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000248
249 // Does it fit in a unsigned long?
250 if (ResultVal.isIntN(LongSize)) {
251 // Does it fit in a signed long?
252 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
253 t = Context.LongTy;
254 else if (AllowUnsigned)
255 t = Context.UnsignedLongTy;
256 }
257 if (!t.isNull())
258 ResultVal.trunc(LongSize);
259 }
260
261 // Finally, check long long if needed.
262 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000263 unsigned LongLongSize = static_cast<unsigned>(
264 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000265
266 // Does it fit in a unsigned long long?
267 if (ResultVal.isIntN(LongLongSize)) {
268 // Does it fit in a signed long long?
269 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
270 t = Context.LongLongTy;
271 else if (AllowUnsigned)
272 t = Context.UnsignedLongLongTy;
273 }
274 }
275
276 // If we still couldn't decide a type, we probably have something that
277 // does not fit in a signed long long, but has no U suffix.
278 if (t.isNull()) {
279 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
280 t = Context.UnsignedLongLongTy;
281 }
282 }
283
Chris Lattner1de66eb2007-08-26 03:42:43 +0000284 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000285 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000286
287 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
288 if (Literal.isImaginary)
289 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
290
291 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000292}
293
Steve Naroff87d58b42007-09-16 03:34:24 +0000294Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000295 ExprTy *Val) {
296 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000297 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000298 return new ParenExpr(L, R, e);
299}
300
301/// The UsualUnaryConversions() function is *not* called by this routine.
302/// See C99 6.3.2.1p[2-4] for more details.
303QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
304 SourceLocation OpLoc, bool isSizeof) {
305 // C99 6.5.3.4p1:
306 if (isa<FunctionType>(exprType) && isSizeof)
307 // alignof(function) is allowed.
308 Diag(OpLoc, diag::ext_sizeof_function_type);
309 else if (exprType->isVoidType())
310 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
311 else if (exprType->isIncompleteType()) {
312 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
313 diag::err_alignof_incomplete_type,
314 exprType.getAsString());
315 return QualType(); // error
316 }
317 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
318 return Context.getSizeType();
319}
320
321Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000322ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000323 SourceLocation LPLoc, TypeTy *Ty,
324 SourceLocation RPLoc) {
325 // If error parsing type, ignore.
326 if (Ty == 0) return true;
327
328 // Verify that this is a valid expression.
329 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
330
331 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
332
333 if (resultType.isNull())
334 return true;
335 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
336}
337
Chris Lattner5110ad52007-08-24 21:41:10 +0000338QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000339 DefaultFunctionArrayConversion(V);
340
Chris Lattnera16e42d2007-08-26 05:39:26 +0000341 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000342 if (const ComplexType *CT = V->getType()->getAsComplexType())
343 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000344
345 // Otherwise they pass through real integer and floating point types here.
346 if (V->getType()->isArithmeticType())
347 return V->getType();
348
349 // Reject anything else.
350 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
351 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000352}
353
354
Chris Lattner4b009652007-07-25 00:24:17 +0000355
Steve Naroff87d58b42007-09-16 03:34:24 +0000356Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000357 tok::TokenKind Kind,
358 ExprTy *Input) {
359 UnaryOperator::Opcode Opc;
360 switch (Kind) {
361 default: assert(0 && "Unknown unary op!");
362 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
363 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
364 }
365 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
366 if (result.isNull())
367 return true;
368 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
369}
370
371Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000372ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000373 ExprTy *Idx, SourceLocation RLoc) {
374 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
375
376 // Perform default conversions.
377 DefaultFunctionArrayConversion(LHSExp);
378 DefaultFunctionArrayConversion(RHSExp);
379
380 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
381
382 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000383 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000384 // in the subscript position. As a result, we need to derive the array base
385 // and index from the expression types.
386 Expr *BaseExpr, *IndexExpr;
387 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000388 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000389 BaseExpr = LHSExp;
390 IndexExpr = RHSExp;
391 // FIXME: need to deal with const...
392 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000393 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000394 // Handle the uncommon case of "123[Ptr]".
395 BaseExpr = RHSExp;
396 IndexExpr = LHSExp;
397 // FIXME: need to deal with const...
398 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000399 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
400 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000401 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000402
403 // Component access limited to variables (reject vec4.rg[1]).
404 if (!isa<DeclRefExpr>(BaseExpr))
405 return Diag(LLoc, diag::err_ocuvector_component_access,
406 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000407 // FIXME: need to deal with const...
408 ResultType = VTy->getElementType();
409 } else {
410 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
411 RHSExp->getSourceRange());
412 }
413 // C99 6.5.2.1p1
414 if (!IndexExpr->getType()->isIntegerType())
415 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
416 IndexExpr->getSourceRange());
417
418 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
419 // the following check catches trying to index a pointer to a function (e.g.
420 // void (*)(int)). Functions are not objects in C99.
421 if (!ResultType->isObjectType())
422 return Diag(BaseExpr->getLocStart(),
423 diag::err_typecheck_subscript_not_object,
424 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
425
426 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
427}
428
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000429QualType Sema::
430CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
431 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000432 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000433
434 // The vector accessor can't exceed the number of elements.
435 const char *compStr = CompName.getName();
436 if (strlen(compStr) > vecType->getNumElements()) {
437 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
438 baseType.getAsString(), SourceRange(CompLoc));
439 return QualType();
440 }
441 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000442 if (vecType->getPointAccessorIdx(*compStr) != -1) {
443 do
444 compStr++;
445 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
446 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
447 do
448 compStr++;
449 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
450 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
451 do
452 compStr++;
453 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
454 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000455
456 if (*compStr) {
457 // We didn't get to the end of the string. This means the component names
458 // didn't come from the same set *or* we encountered an illegal name.
459 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
460 std::string(compStr,compStr+1), SourceRange(CompLoc));
461 return QualType();
462 }
463 // Each component accessor can't exceed the vector type.
464 compStr = CompName.getName();
465 while (*compStr) {
466 if (vecType->isAccessorWithinNumElements(*compStr))
467 compStr++;
468 else
469 break;
470 }
471 if (*compStr) {
472 // We didn't get to the end of the string. This means a component accessor
473 // exceeds the number of elements in the vector.
474 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
475 baseType.getAsString(), SourceRange(CompLoc));
476 return QualType();
477 }
478 // The component accessor looks fine - now we need to compute the actual type.
479 // The vector type is implied by the component accessor. For example,
480 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
481 unsigned CompSize = strlen(CompName.getName());
482 if (CompSize == 1)
483 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000484
485 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
486 // Now look up the TypeDefDecl from the vector type. Without this,
487 // diagostics look bad. We want OCU vector types to appear built-in.
488 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
489 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
490 return Context.getTypedefType(OCUVectorDecls[i]);
491 }
492 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000493}
494
Chris Lattner4b009652007-07-25 00:24:17 +0000495Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000496ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000497 tok::TokenKind OpKind, SourceLocation MemberLoc,
498 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000499 Expr *BaseExpr = static_cast<Expr *>(Base);
500 assert(BaseExpr && "no record expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000501
Steve Naroff2cb66382007-07-26 03:11:44 +0000502 QualType BaseType = BaseExpr->getType();
503 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000504
Chris Lattner4b009652007-07-25 00:24:17 +0000505 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000506 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000507 BaseType = PT->getPointeeType();
508 else
509 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
510 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000511 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000512 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000513 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000514 RecordDecl *RDecl = RTy->getDecl();
515 if (RTy->isIncompleteType())
516 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
517 BaseExpr->getSourceRange());
518 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000519 FieldDecl *MemberDecl = RDecl->getMember(&Member);
520 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000521 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
522 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000523 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
524 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000525 // Component access limited to variables (reject vec4.rg.g).
526 if (!isa<DeclRefExpr>(BaseExpr))
527 return Diag(OpLoc, diag::err_ocuvector_component_access,
528 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000529 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
530 if (ret.isNull())
531 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000532 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000533 } else if (BaseType->isObjcInterfaceType()) {
534 ObjcInterfaceDecl *IFace;
535 if (isa<ObjcInterfaceType>(BaseType.getCanonicalType()))
536 IFace = dyn_cast<ObjcInterfaceType>(BaseType)->getDecl();
537 else
538 IFace = dyn_cast<ObjcQualifiedInterfaceType>(BaseType)
539 ->getInterfaceType()->getDecl();
540 ObjcInterfaceDecl *clsDeclared;
541 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
542 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
543 OpKind==tok::arrow);
544 }
545 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
546 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000547}
548
Steve Naroff87d58b42007-09-16 03:34:24 +0000549/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000550/// This provides the location of the left/right parens and a list of comma
551/// locations.
552Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000553ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000554 ExprTy **args, unsigned NumArgsInCall,
555 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
556 Expr *Fn = static_cast<Expr *>(fn);
557 Expr **Args = reinterpret_cast<Expr**>(args);
558 assert(Fn && "no function call expression");
559
560 UsualUnaryConversions(Fn);
561 QualType funcType = Fn->getType();
562
563 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
564 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000565 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000566 if (PT == 0)
567 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
568 SourceRange(Fn->getLocStart(), RParenLoc));
569
Chris Lattner71225142007-07-31 21:27:01 +0000570 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000571 if (funcT == 0)
572 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
573 SourceRange(Fn->getLocStart(), RParenLoc));
574
575 // If a prototype isn't declared, the parser implicitly defines a func decl
576 QualType resultType = funcT->getResultType();
577
578 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
579 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
580 // assignment, to the types of the corresponding parameter, ...
581
582 unsigned NumArgsInProto = proto->getNumArgs();
583 unsigned NumArgsToCheck = NumArgsInCall;
584
585 if (NumArgsInCall < NumArgsInProto)
586 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
587 Fn->getSourceRange());
588 else if (NumArgsInCall > NumArgsInProto) {
589 if (!proto->isVariadic()) {
590 Diag(Args[NumArgsInProto]->getLocStart(),
591 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
592 SourceRange(Args[NumArgsInProto]->getLocStart(),
593 Args[NumArgsInCall-1]->getLocEnd()));
594 }
595 NumArgsToCheck = NumArgsInProto;
596 }
597 // Continue to check argument types (even if we have too few/many args).
598 for (unsigned i = 0; i < NumArgsToCheck; i++) {
599 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000600 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000601
602 QualType lhsType = proto->getArgType(i);
603 QualType rhsType = argExpr->getType();
604
Steve Naroff75644062007-07-25 20:45:33 +0000605 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000606 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000607 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000608 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000609 lhsType = Context.getPointerType(lhsType);
610
611 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
612 argExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000613 if (Args[i] != argExpr) // The expression was converted.
614 Args[i] = argExpr; // Make sure we store the converted expression.
Chris Lattner4b009652007-07-25 00:24:17 +0000615 SourceLocation l = argExpr->getLocStart();
616
617 // decode the result (notice that AST's are still created for extensions).
618 switch (result) {
619 case Compatible:
620 break;
621 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +0000622 Diag(l, diag::ext_typecheck_passing_pointer_int,
623 lhsType.getAsString(), rhsType.getAsString(),
624 Fn->getSourceRange(), argExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000625 break;
626 case IntFromPointer:
627 Diag(l, diag::ext_typecheck_passing_pointer_int,
628 lhsType.getAsString(), rhsType.getAsString(),
629 Fn->getSourceRange(), argExpr->getSourceRange());
630 break;
631 case IncompatiblePointer:
632 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
633 rhsType.getAsString(), lhsType.getAsString(),
634 Fn->getSourceRange(), argExpr->getSourceRange());
635 break;
636 case CompatiblePointerDiscardsQualifiers:
637 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
638 rhsType.getAsString(), lhsType.getAsString(),
639 Fn->getSourceRange(), argExpr->getSourceRange());
640 break;
641 case Incompatible:
642 return Diag(l, diag::err_typecheck_passing_incompatible,
643 rhsType.getAsString(), lhsType.getAsString(),
644 Fn->getSourceRange(), argExpr->getSourceRange());
645 }
646 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000647 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
648 // Promote the arguments (C99 6.5.2.2p7).
649 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
650 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000651 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000652
653 DefaultArgumentPromotion(argExpr);
654 if (Args[i] != argExpr) // The expression was converted.
655 Args[i] = argExpr; // Make sure we store the converted expression.
656 }
657 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
658 // Even if the types checked, bail if the number of arguments don't match.
Chris Lattner4b009652007-07-25 00:24:17 +0000659 return true;
Steve Naroffdb65e052007-08-28 23:30:39 +0000660 }
661 } else if (isa<FunctionTypeNoProto>(funcT)) {
662 // Promote the arguments (C99 6.5.2.2p6).
663 for (unsigned i = 0; i < NumArgsInCall; i++) {
664 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000665 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000666
667 DefaultArgumentPromotion(argExpr);
668 if (Args[i] != argExpr) // The expression was converted.
669 Args[i] = argExpr; // Make sure we store the converted expression.
670 }
Chris Lattner4b009652007-07-25 00:24:17 +0000671 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000672 // Do special checking on direct calls to functions.
673 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
674 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
675 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000676 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
677 NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000678 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000679
Chris Lattner4b009652007-07-25 00:24:17 +0000680 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
681}
682
683Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000684ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000685 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000686 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000687 QualType literalType = QualType::getFromOpaquePtr(Ty);
688 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000689 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000690 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000691
Steve Naroffcb69fb72007-12-10 22:44:33 +0000692 // FIXME: add more semantic analysis (C99 6.5.2.5).
693 if (CheckInitializer(literalExpr, literalType, false))
694 return 0;
Anders Carlsson9374b852007-12-05 07:24:19 +0000695
Chris Lattner4b009652007-07-25 00:24:17 +0000696 return new CompoundLiteralExpr(literalType, literalExpr);
697}
698
699Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000700ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000701 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000702 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000703
Steve Naroff0acc9c92007-09-15 18:49:24 +0000704 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000705 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000706
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000707 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
708 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
709 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000710}
711
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000712bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty)
713{
714 assert(VectorTy->isVectorType() && "Not a vector type!");
715
716 if (Ty->isVectorType() || Ty->isIntegerType()) {
717 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
718 Context.getTypeSize(Ty, SourceLocation()))
719 return Diag(R.getBegin(),
720 Ty->isVectorType() ?
721 diag::err_invalid_conversion_between_vectors :
722 diag::err_invalid_conversion_between_vector_and_integer,
723 VectorTy.getAsString().c_str(),
724 Ty.getAsString().c_str(), R);
725 } else
726 return Diag(R.getBegin(),
727 diag::err_invalid_conversion_between_vector_and_scalar,
728 VectorTy.getAsString().c_str(),
729 Ty.getAsString().c_str(), R);
730
731 return false;
732}
733
Chris Lattner4b009652007-07-25 00:24:17 +0000734Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000735ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000736 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000737 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000738
739 Expr *castExpr = static_cast<Expr*>(Op);
740 QualType castType = QualType::getFromOpaquePtr(Ty);
741
Steve Naroff68adb482007-08-31 00:32:44 +0000742 UsualUnaryConversions(castExpr);
743
Chris Lattner4b009652007-07-25 00:24:17 +0000744 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
745 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000746 if (!castType->isVoidType()) { // Cast to void allows any expr type.
747 if (!castType->isScalarType())
748 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
749 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000750 if (!castExpr->getType()->isScalarType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000751 return Diag(castExpr->getLocStart(),
752 diag::err_typecheck_expect_scalar_operand,
753 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000754
755 if (castExpr->getType()->isVectorType()) {
756 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
757 castExpr->getType(), castType))
758 return true;
759 } else if (castType->isVectorType()) {
760 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
761 castType, castExpr->getType()))
762 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000763 }
Chris Lattner4b009652007-07-25 00:24:17 +0000764 }
765 return new CastExpr(castType, castExpr, LParenLoc);
766}
767
Steve Naroff144667e2007-10-18 05:13:08 +0000768// promoteExprToType - a helper function to ensure we create exactly one
769// ImplicitCastExpr.
770static void promoteExprToType(Expr *&expr, QualType type) {
771 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
772 impCast->setType(type);
773 else
774 expr = new ImplicitCastExpr(type, expr);
775 return;
776}
777
Chris Lattner98a425c2007-11-26 01:40:58 +0000778/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
779/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000780inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
781 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
782 UsualUnaryConversions(cond);
783 UsualUnaryConversions(lex);
784 UsualUnaryConversions(rex);
785 QualType condT = cond->getType();
786 QualType lexT = lex->getType();
787 QualType rexT = rex->getType();
788
789 // first, check the condition.
790 if (!condT->isScalarType()) { // C99 6.5.15p2
791 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
792 condT.getAsString());
793 return QualType();
794 }
795 // now check the two expressions.
796 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
797 UsualArithmeticConversions(lex, rex);
798 return lex->getType();
799 }
Chris Lattner71225142007-07-31 21:27:01 +0000800 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
801 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
Chris Lattner98a425c2007-11-26 01:40:58 +0000802 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner71225142007-07-31 21:27:01 +0000803 return lexT;
804
Chris Lattner4b009652007-07-25 00:24:17 +0000805 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
806 lexT.getAsString(), rexT.getAsString(),
807 lex->getSourceRange(), rex->getSourceRange());
808 return QualType();
809 }
810 }
811 // C99 6.5.15p3
Steve Naroff144667e2007-10-18 05:13:08 +0000812 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
813 promoteExprToType(rex, lexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000814 return lexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000815 }
816 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
817 promoteExprToType(lex, rexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000818 return rexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000819 }
Chris Lattner71225142007-07-31 21:27:01 +0000820 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
821 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
822 // get the "pointed to" types
823 QualType lhptee = LHSPT->getPointeeType();
824 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000825
Chris Lattner71225142007-07-31 21:27:01 +0000826 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
827 if (lhptee->isVoidType() &&
828 (rhptee->isObjectType() || rhptee->isIncompleteType()))
829 return lexT;
830 if (rhptee->isVoidType() &&
831 (lhptee->isObjectType() || lhptee->isIncompleteType()))
832 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000833
Steve Naroff85f0dc52007-10-15 20:41:53 +0000834 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
835 rhptee.getUnqualifiedType())) {
Chris Lattner71225142007-07-31 21:27:01 +0000836 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
837 lexT.getAsString(), rexT.getAsString(),
838 lex->getSourceRange(), rex->getSourceRange());
839 return lexT; // FIXME: this is an _ext - is this return o.k?
840 }
841 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000842 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
843 // differently qualified versions of compatible types, the result type is
844 // a pointer to an appropriately qualified version of the *composite*
845 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000846 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000847 }
Chris Lattner4b009652007-07-25 00:24:17 +0000848 }
Chris Lattner71225142007-07-31 21:27:01 +0000849
Chris Lattner4b009652007-07-25 00:24:17 +0000850 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
851 return lexT;
852
853 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
854 lexT.getAsString(), rexT.getAsString(),
855 lex->getSourceRange(), rex->getSourceRange());
856 return QualType();
857}
858
Steve Naroff87d58b42007-09-16 03:34:24 +0000859/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000860/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000861Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000862 SourceLocation ColonLoc,
863 ExprTy *Cond, ExprTy *LHS,
864 ExprTy *RHS) {
865 Expr *CondExpr = (Expr *) Cond;
866 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000867
868 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
869 // was the condition.
870 bool isLHSNull = LHSExpr == 0;
871 if (isLHSNull)
872 LHSExpr = CondExpr;
873
Chris Lattner4b009652007-07-25 00:24:17 +0000874 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
875 RHSExpr, QuestionLoc);
876 if (result.isNull())
877 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000878 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
879 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000880}
881
Steve Naroffdb65e052007-08-28 23:30:39 +0000882/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
883/// do not have a prototype. Integer promotions are performed on each
884/// argument, and arguments that have type float are promoted to double.
885void Sema::DefaultArgumentPromotion(Expr *&expr) {
886 QualType t = expr->getType();
887 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
888
889 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
890 promoteExprToType(expr, Context.IntTy);
891 if (t == Context.FloatTy)
892 promoteExprToType(expr, Context.DoubleTy);
893}
894
Chris Lattner4b009652007-07-25 00:24:17 +0000895/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
896void Sema::DefaultFunctionArrayConversion(Expr *&e) {
897 QualType t = e->getType();
898 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
899
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000900 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000901 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
902 t = e->getType();
903 }
904 if (t->isFunctionType())
905 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000906 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000907 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
908}
909
910/// UsualUnaryConversion - Performs various conversions that are common to most
911/// operators (C99 6.3). The conversions of array and function types are
912/// sometimes surpressed. For example, the array->pointer conversion doesn't
913/// apply if the array is an argument to the sizeof or address (&) operators.
914/// In these instances, this routine should *not* be called.
915void Sema::UsualUnaryConversions(Expr *&expr) {
916 QualType t = expr->getType();
917 assert(!t.isNull() && "UsualUnaryConversions - missing type");
918
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000919 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000920 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
921 t = expr->getType();
922 }
923 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
924 promoteExprToType(expr, Context.IntTy);
925 else
926 DefaultFunctionArrayConversion(expr);
927}
928
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000929/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000930/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
931/// routine returns the first non-arithmetic type found. The client is
932/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000933QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
934 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000935 if (!isCompAssign) {
936 UsualUnaryConversions(lhsExpr);
937 UsualUnaryConversions(rhsExpr);
938 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000939 // For conversion purposes, we ignore any qualifiers.
940 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000941 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
942 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000943
944 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000945 if (lhs == rhs)
946 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000947
948 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
949 // The caller can deal with this (e.g. pointer + int).
950 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000951 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000952
953 // At this point, we have two different arithmetic types.
954
955 // Handle complex types first (C99 6.3.1.8p1).
956 if (lhs->isComplexType() || rhs->isComplexType()) {
957 // if we have an integer operand, the result is the complex type.
958 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000959 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
960 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000961 }
962 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000963 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
964 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000965 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000966 // This handles complex/complex, complex/float, or float/complex.
967 // When both operands are complex, the shorter operand is converted to the
968 // type of the longer, and that is the type of the result. This corresponds
969 // to what is done when combining two real floating-point operands.
970 // The fun begins when size promotion occur across type domains.
971 // From H&S 6.3.4: When one operand is complex and the other is a real
972 // floating-point type, the less precise type is converted, within it's
973 // real or complex domain, to the precision of the other type. For example,
974 // when combining a "long double" with a "double _Complex", the
975 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000976 int result = Context.compareFloatingType(lhs, rhs);
977
978 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000979 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
980 if (!isCompAssign)
981 promoteExprToType(rhsExpr, rhs);
982 } else if (result < 0) { // The right side is bigger, convert lhs.
983 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
984 if (!isCompAssign)
985 promoteExprToType(lhsExpr, lhs);
986 }
987 // At this point, lhs and rhs have the same rank/size. Now, make sure the
988 // domains match. This is a requirement for our implementation, C99
989 // does not require this promotion.
990 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
991 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000992 if (!isCompAssign)
993 promoteExprToType(lhsExpr, rhs);
994 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000995 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000996 if (!isCompAssign)
997 promoteExprToType(rhsExpr, lhs);
998 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +0000999 }
Chris Lattner4b009652007-07-25 00:24:17 +00001000 }
Steve Naroff3b6157f2007-08-27 21:43:43 +00001001 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +00001002 }
1003 // Now handle "real" floating types (i.e. float, double, long double).
1004 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1005 // if we have an integer operand, the result is the real floating type.
1006 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001007 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1008 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001009 }
1010 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001011 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
1012 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001013 }
1014 // We have two real floating types, float/complex combos were handled above.
1015 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +00001016 int result = Context.compareFloatingType(lhs, rhs);
1017
1018 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001019 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1020 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001021 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001022 if (result < 0) { // convert the lhs
1023 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1024 return rhs;
1025 }
1026 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001027 }
1028 // Finally, we have two differing integer types.
1029 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001030 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1031 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001032 }
Steve Naroff8f708362007-08-24 19:07:16 +00001033 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1034 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001035}
1036
1037// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1038// being closely modeled after the C99 spec:-). The odd characteristic of this
1039// routine is it effectively iqnores the qualifiers on the top level pointee.
1040// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1041// FIXME: add a couple examples in this comment.
1042Sema::AssignmentCheckResult
1043Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1044 QualType lhptee, rhptee;
1045
1046 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001047 lhptee = lhsType->getAsPointerType()->getPointeeType();
1048 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001049
1050 // make sure we operate on the canonical type
1051 lhptee = lhptee.getCanonicalType();
1052 rhptee = rhptee.getCanonicalType();
1053
1054 AssignmentCheckResult r = Compatible;
1055
1056 // C99 6.5.16.1p1: This following citation is common to constraints
1057 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1058 // qualifiers of the type *pointed to* by the right;
1059 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1060 rhptee.getQualifiers())
1061 r = CompatiblePointerDiscardsQualifiers;
1062
1063 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1064 // incomplete type and the other is a pointer to a qualified or unqualified
1065 // version of void...
1066 if (lhptee.getUnqualifiedType()->isVoidType() &&
1067 (rhptee->isObjectType() || rhptee->isIncompleteType()))
1068 ;
1069 else if (rhptee.getUnqualifiedType()->isVoidType() &&
1070 (lhptee->isObjectType() || lhptee->isIncompleteType()))
1071 ;
1072 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1073 // unqualified versions of compatible types, ...
Steve Naroff85f0dc52007-10-15 20:41:53 +00001074 else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1075 rhptee.getUnqualifiedType()))
Chris Lattner4b009652007-07-25 00:24:17 +00001076 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1077 return r;
1078}
1079
1080/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1081/// has code to accommodate several GCC extensions when type checking
1082/// pointers. Here are some objectionable examples that GCC considers warnings:
1083///
1084/// int a, *pint;
1085/// short *pshort;
1086/// struct foo *pfoo;
1087///
1088/// pint = pshort; // warning: assignment from incompatible pointer type
1089/// a = pint; // warning: assignment makes integer from pointer without a cast
1090/// pint = a; // warning: assignment makes pointer from integer without a cast
1091/// pint = pfoo; // warning: assignment from incompatible pointer type
1092///
1093/// As a result, the code for dealing with pointers is more complex than the
1094/// C99 spec dictates.
1095/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1096///
1097Sema::AssignmentCheckResult
1098Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Steve Naroffeed76842007-11-13 00:31:42 +00001099 if (lhsType.getCanonicalType().getUnqualifiedType() ==
1100 rhsType.getCanonicalType().getUnqualifiedType())
Chris Lattnera703c2e2007-10-29 05:15:40 +00001101 return Compatible; // common case, fast path...
Chris Lattner4b009652007-07-25 00:24:17 +00001102
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001103 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001104 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001105 return Compatible;
1106 } else if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001107 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Anders Carlssone87cd982007-11-30 04:21:22 +00001108 if (!getLangOptions().LaxVectorConversions) {
1109 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1110 return Incompatible;
1111 } else {
1112 if (lhsType->isVectorType() && rhsType->isVectorType()) {
1113 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1114 (lhsType->isRealFloatingType() &&
1115 rhsType->isRealFloatingType())) {
1116 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1117 Context.getTypeSize(rhsType, SourceLocation()))
1118 return Compatible;
1119 }
1120 }
Chris Lattner4b009652007-07-25 00:24:17 +00001121 return Incompatible;
Anders Carlssone87cd982007-11-30 04:21:22 +00001122 }
1123 }
Chris Lattner4b009652007-07-25 00:24:17 +00001124 return Compatible;
1125 } else if (lhsType->isPointerType()) {
1126 if (rhsType->isIntegerType())
1127 return PointerFromInt;
1128
1129 if (rhsType->isPointerType())
1130 return CheckPointerTypesForAssignment(lhsType, rhsType);
1131 } else if (rhsType->isPointerType()) {
1132 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1133 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1134 return IntFromPointer;
1135
1136 if (lhsType->isPointerType())
1137 return CheckPointerTypesForAssignment(lhsType, rhsType);
1138 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001139 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001140 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001141 }
1142 return Incompatible;
1143}
1144
1145Sema::AssignmentCheckResult
1146Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001147 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1148 // a null pointer constant.
1149 if (lhsType->isPointerType() && rExpr->isNullPointerConstant(Context)) {
1150 promoteExprToType(rExpr, lhsType);
1151 return Compatible;
1152 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001153 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001154 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001155 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001156 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001157 //
1158 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1159 // are better understood.
1160 if (!lhsType->isReferenceType())
1161 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001162
1163 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +00001164
Steve Naroff0f32f432007-08-24 22:33:52 +00001165 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1166
1167 // C99 6.5.16.1p2: The value of the right operand is converted to the
1168 // type of the assignment expression.
1169 if (rExpr->getType() != lhsType)
1170 promoteExprToType(rExpr, lhsType);
1171 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001172}
1173
1174Sema::AssignmentCheckResult
1175Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1176 return CheckAssignmentConstraints(lhsType, rhsType);
1177}
1178
1179inline void Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1180 Diag(loc, diag::err_typecheck_invalid_operands,
1181 lex->getType().getAsString(), rex->getType().getAsString(),
1182 lex->getSourceRange(), rex->getSourceRange());
1183}
1184
1185inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1186 Expr *&rex) {
1187 QualType lhsType = lex->getType(), rhsType = rex->getType();
1188
1189 // make sure the vector types are identical.
1190 if (lhsType == rhsType)
1191 return lhsType;
1192 // You cannot convert between vector values of different size.
1193 Diag(loc, diag::err_typecheck_vector_not_convertable,
1194 lex->getType().getAsString(), rex->getType().getAsString(),
1195 lex->getSourceRange(), rex->getSourceRange());
1196 return QualType();
1197}
1198
1199inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001200 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001201{
1202 QualType lhsType = lex->getType(), rhsType = rex->getType();
1203
1204 if (lhsType->isVectorType() || rhsType->isVectorType())
1205 return CheckVectorOperands(loc, lex, rex);
1206
Steve Naroff8f708362007-08-24 19:07:16 +00001207 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001208
Chris Lattner4b009652007-07-25 00:24:17 +00001209 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001210 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001211 InvalidOperands(loc, lex, rex);
1212 return QualType();
1213}
1214
1215inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001216 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001217{
1218 QualType lhsType = lex->getType(), rhsType = rex->getType();
1219
Steve Naroff8f708362007-08-24 19:07:16 +00001220 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001221
Chris Lattner4b009652007-07-25 00:24:17 +00001222 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001223 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001224 InvalidOperands(loc, lex, rex);
1225 return QualType();
1226}
1227
1228inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001229 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001230{
1231 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1232 return CheckVectorOperands(loc, lex, rex);
1233
Steve Naroff8f708362007-08-24 19:07:16 +00001234 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001235
1236 // handle the common case first (both operands are arithmetic).
1237 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001238 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001239
1240 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1241 return lex->getType();
1242 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1243 return rex->getType();
1244 InvalidOperands(loc, lex, rex);
1245 return QualType();
1246}
1247
1248inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001249 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001250{
1251 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1252 return CheckVectorOperands(loc, lex, rex);
1253
Steve Naroff8f708362007-08-24 19:07:16 +00001254 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001255
Chris Lattnerf6da2912007-12-09 21:53:25 +00001256 // Enforce type constraints: C99 6.5.6p3.
1257
1258 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001259 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001260 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001261
1262 // Either ptr - int or ptr - ptr.
1263 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1264 // The LHS must be an object type, not incomplete, function, etc.
1265 if (!LHSPTy->getPointeeType()->isObjectType()) {
1266 // Handle the GNU void* extension.
1267 if (LHSPTy->getPointeeType()->isVoidType()) {
1268 Diag(loc, diag::ext_gnu_void_ptr,
1269 lex->getSourceRange(), rex->getSourceRange());
1270 } else {
1271 Diag(loc, diag::err_typecheck_sub_ptr_object,
1272 lex->getType().getAsString(), lex->getSourceRange());
1273 return QualType();
1274 }
1275 }
1276
1277 // The result type of a pointer-int computation is the pointer type.
1278 if (rex->getType()->isIntegerType())
1279 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001280
Chris Lattnerf6da2912007-12-09 21:53:25 +00001281 // Handle pointer-pointer subtractions.
1282 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1283 // RHS must be an object type, unless void (GNU).
1284 if (!RHSPTy->getPointeeType()->isObjectType()) {
1285 // Handle the GNU void* extension.
1286 if (RHSPTy->getPointeeType()->isVoidType()) {
1287 if (!LHSPTy->getPointeeType()->isVoidType())
1288 Diag(loc, diag::ext_gnu_void_ptr,
1289 lex->getSourceRange(), rex->getSourceRange());
1290 } else {
1291 Diag(loc, diag::err_typecheck_sub_ptr_object,
1292 rex->getType().getAsString(), rex->getSourceRange());
1293 return QualType();
1294 }
1295 }
1296
1297 // Pointee types must be compatible.
1298 if (!Context.typesAreCompatible(LHSPTy->getPointeeType(),
1299 RHSPTy->getPointeeType())) {
1300 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1301 lex->getType().getAsString(), rex->getType().getAsString(),
1302 lex->getSourceRange(), rex->getSourceRange());
1303 return QualType();
1304 }
1305
1306 return Context.getPointerDiffType();
1307 }
1308 }
1309
Chris Lattner4b009652007-07-25 00:24:17 +00001310 InvalidOperands(loc, lex, rex);
1311 return QualType();
1312}
1313
1314inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Steve Naroff8f708362007-08-24 19:07:16 +00001315 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001316{
1317 // FIXME: Shifts don't perform usual arithmetic conversions. This is wrong
1318 // for int << longlong -> the result type should be int, not long long.
Steve Naroff8f708362007-08-24 19:07:16 +00001319 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001320
1321 // handle the common case first (both operands are arithmetic).
1322 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001323 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001324 InvalidOperands(loc, lex, rex);
1325 return QualType();
1326}
1327
Chris Lattner254f3bc2007-08-26 01:18:55 +00001328inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1329 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001330{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001331 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001332 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1333 UsualArithmeticConversions(lex, rex);
1334 else {
1335 UsualUnaryConversions(lex);
1336 UsualUnaryConversions(rex);
1337 }
Chris Lattner4b009652007-07-25 00:24:17 +00001338 QualType lType = lex->getType();
1339 QualType rType = rex->getType();
1340
Ted Kremenek486509e2007-10-29 17:13:39 +00001341 // For non-floating point types, check for self-comparisons of the form
1342 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1343 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001344 if (!lType->isFloatingType()) {
1345 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1346 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1347 if (DRL->getDecl() == DRR->getDecl())
1348 Diag(loc, diag::warn_selfcomparison);
1349 }
1350
Chris Lattner254f3bc2007-08-26 01:18:55 +00001351 if (isRelational) {
1352 if (lType->isRealType() && rType->isRealType())
1353 return Context.IntTy;
1354 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001355 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001356 if (lType->isFloatingType()) {
1357 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001358 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001359 }
1360
Chris Lattner254f3bc2007-08-26 01:18:55 +00001361 if (lType->isArithmeticType() && rType->isArithmeticType())
1362 return Context.IntTy;
1363 }
Chris Lattner4b009652007-07-25 00:24:17 +00001364
Chris Lattner22be8422007-08-26 01:10:14 +00001365 bool LHSIsNull = lex->isNullPointerConstant(Context);
1366 bool RHSIsNull = rex->isNullPointerConstant(Context);
1367
Chris Lattner254f3bc2007-08-26 01:18:55 +00001368 // All of the following pointer related warnings are GCC extensions, except
1369 // when handling null pointer constants. One day, we can consider making them
1370 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001371 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff3b435622007-11-13 14:57:38 +00001372
1373 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1374 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1375 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroff85f0dc52007-10-15 20:41:53 +00001376 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1377 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001378 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1379 lType.getAsString(), rType.getAsString(),
1380 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001381 }
Chris Lattner22be8422007-08-26 01:10:14 +00001382 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001383 return Context.IntTy;
1384 }
1385 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001386 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001387 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1388 lType.getAsString(), rType.getAsString(),
1389 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001390 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001391 return Context.IntTy;
1392 }
1393 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001394 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001395 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1396 lType.getAsString(), rType.getAsString(),
1397 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001398 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001399 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001400 }
1401 InvalidOperands(loc, lex, rex);
1402 return QualType();
1403}
1404
Chris Lattner4b009652007-07-25 00:24:17 +00001405inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001406 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001407{
1408 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1409 return CheckVectorOperands(loc, lex, rex);
1410
Steve Naroff8f708362007-08-24 19:07:16 +00001411 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001412
1413 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001414 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001415 InvalidOperands(loc, lex, rex);
1416 return QualType();
1417}
1418
1419inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1420 Expr *&lex, Expr *&rex, SourceLocation loc)
1421{
1422 UsualUnaryConversions(lex);
1423 UsualUnaryConversions(rex);
1424
1425 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1426 return Context.IntTy;
1427 InvalidOperands(loc, lex, rex);
1428 return QualType();
1429}
1430
1431inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001432 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001433{
1434 QualType lhsType = lex->getType();
1435 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1436 bool hadError = false;
1437 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1438
1439 switch (mlval) { // C99 6.5.16p2
1440 case Expr::MLV_Valid:
1441 break;
1442 case Expr::MLV_ConstQualified:
1443 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1444 hadError = true;
1445 break;
1446 case Expr::MLV_ArrayType:
1447 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1448 lhsType.getAsString(), lex->getSourceRange());
1449 return QualType();
1450 case Expr::MLV_NotObjectType:
1451 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1452 lhsType.getAsString(), lex->getSourceRange());
1453 return QualType();
1454 case Expr::MLV_InvalidExpression:
1455 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1456 lex->getSourceRange());
1457 return QualType();
1458 case Expr::MLV_IncompleteType:
1459 case Expr::MLV_IncompleteVoidType:
1460 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1461 lhsType.getAsString(), lex->getSourceRange());
1462 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001463 case Expr::MLV_DuplicateVectorComponents:
1464 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1465 lex->getSourceRange());
1466 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001467 }
1468 AssignmentCheckResult result;
1469
1470 if (compoundType.isNull())
1471 result = CheckSingleAssignmentConstraints(lhsType, rex);
1472 else
1473 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001474
Chris Lattner4b009652007-07-25 00:24:17 +00001475 // decode the result (notice that extensions still return a type).
1476 switch (result) {
1477 case Compatible:
1478 break;
1479 case Incompatible:
1480 Diag(loc, diag::err_typecheck_assign_incompatible,
1481 lhsType.getAsString(), rhsType.getAsString(),
1482 lex->getSourceRange(), rex->getSourceRange());
1483 hadError = true;
1484 break;
1485 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +00001486 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1487 lhsType.getAsString(), rhsType.getAsString(),
1488 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001489 break;
1490 case IntFromPointer:
1491 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1492 lhsType.getAsString(), rhsType.getAsString(),
1493 lex->getSourceRange(), rex->getSourceRange());
1494 break;
1495 case IncompatiblePointer:
1496 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1497 lhsType.getAsString(), rhsType.getAsString(),
1498 lex->getSourceRange(), rex->getSourceRange());
1499 break;
1500 case CompatiblePointerDiscardsQualifiers:
1501 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1502 lhsType.getAsString(), rhsType.getAsString(),
1503 lex->getSourceRange(), rex->getSourceRange());
1504 break;
1505 }
1506 // C99 6.5.16p3: The type of an assignment expression is the type of the
1507 // left operand unless the left operand has qualified type, in which case
1508 // it is the unqualified version of the type of the left operand.
1509 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1510 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001511 // C++ 5.17p1: the type of the assignment expression is that of its left
1512 // oprdu.
Chris Lattner4b009652007-07-25 00:24:17 +00001513 return hadError ? QualType() : lhsType.getUnqualifiedType();
1514}
1515
1516inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1517 Expr *&lex, Expr *&rex, SourceLocation loc) {
1518 UsualUnaryConversions(rex);
1519 return rex->getType();
1520}
1521
1522/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1523/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1524QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1525 QualType resType = op->getType();
1526 assert(!resType.isNull() && "no type for increment/decrement expression");
1527
Steve Naroffd30e1932007-08-24 17:20:07 +00001528 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001529 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001530 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1531 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1532 resType.getAsString(), op->getSourceRange());
1533 return QualType();
1534 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001535 } else if (!resType->isRealType()) {
1536 if (resType->isComplexType())
1537 // C99 does not support ++/-- on complex types.
1538 Diag(OpLoc, diag::ext_integer_increment_complex,
1539 resType.getAsString(), op->getSourceRange());
1540 else {
1541 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1542 resType.getAsString(), op->getSourceRange());
1543 return QualType();
1544 }
Chris Lattner4b009652007-07-25 00:24:17 +00001545 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001546 // At this point, we know we have a real, complex or pointer type.
1547 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001548 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1549 if (mlval != Expr::MLV_Valid) {
1550 // FIXME: emit a more precise diagnostic...
1551 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1552 op->getSourceRange());
1553 return QualType();
1554 }
1555 return resType;
1556}
1557
1558/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1559/// This routine allows us to typecheck complex/recursive expressions
1560/// where the declaration is needed for type checking. Here are some
1561/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1562static Decl *getPrimaryDeclaration(Expr *e) {
1563 switch (e->getStmtClass()) {
1564 case Stmt::DeclRefExprClass:
1565 return cast<DeclRefExpr>(e)->getDecl();
1566 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001567 // Fields cannot be declared with a 'register' storage class.
1568 // &X->f is always ok, even if X is declared register.
1569 if (cast<MemberExpr>(e)->isArrow())
1570 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001571 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1572 case Stmt::ArraySubscriptExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001573 // &X[4] and &4[X] is invalid if X is invalid.
Chris Lattner4b009652007-07-25 00:24:17 +00001574 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +00001575 case Stmt::UnaryOperatorClass:
1576 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1577 case Stmt::ParenExprClass:
1578 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001579 case Stmt::ImplicitCastExprClass:
1580 // &X[4] when X is an array, has an implicit cast from array to pointer.
1581 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001582 default:
1583 return 0;
1584 }
1585}
1586
1587/// CheckAddressOfOperand - The operand of & must be either a function
1588/// designator or an lvalue designating an object. If it is an lvalue, the
1589/// object cannot be declared with storage class register or be a bit field.
1590/// Note: The usual conversions are *not* applied to the operand of the &
1591/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1592QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1593 Decl *dcl = getPrimaryDeclaration(op);
1594 Expr::isLvalueResult lval = op->isLvalue();
1595
1596 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001597 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1598 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001599 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1600 op->getSourceRange());
1601 return QualType();
1602 }
1603 } else if (dcl) {
1604 // We have an lvalue with a decl. Make sure the decl is not declared
1605 // with the register storage-class specifier.
1606 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1607 if (vd->getStorageClass() == VarDecl::Register) {
1608 Diag(OpLoc, diag::err_typecheck_address_of_register,
1609 op->getSourceRange());
1610 return QualType();
1611 }
1612 } else
1613 assert(0 && "Unknown/unexpected decl type");
1614
1615 // FIXME: add check for bitfields!
1616 }
1617 // If the operand has type "type", the result has type "pointer to type".
1618 return Context.getPointerType(op->getType());
1619}
1620
1621QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1622 UsualUnaryConversions(op);
1623 QualType qType = op->getType();
1624
Chris Lattner7931f4a2007-07-31 16:53:04 +00001625 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001626 QualType ptype = PT->getPointeeType();
1627 // C99 6.5.3.2p4. "if it points to an object,...".
1628 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1629 // GCC compat: special case 'void *' (treat as warning).
1630 if (ptype->isVoidType()) {
1631 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1632 qType.getAsString(), op->getSourceRange());
1633 } else {
1634 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1635 ptype.getAsString(), op->getSourceRange());
1636 return QualType();
1637 }
1638 }
1639 return ptype;
1640 }
1641 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1642 qType.getAsString(), op->getSourceRange());
1643 return QualType();
1644}
1645
1646static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1647 tok::TokenKind Kind) {
1648 BinaryOperator::Opcode Opc;
1649 switch (Kind) {
1650 default: assert(0 && "Unknown binop!");
1651 case tok::star: Opc = BinaryOperator::Mul; break;
1652 case tok::slash: Opc = BinaryOperator::Div; break;
1653 case tok::percent: Opc = BinaryOperator::Rem; break;
1654 case tok::plus: Opc = BinaryOperator::Add; break;
1655 case tok::minus: Opc = BinaryOperator::Sub; break;
1656 case tok::lessless: Opc = BinaryOperator::Shl; break;
1657 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1658 case tok::lessequal: Opc = BinaryOperator::LE; break;
1659 case tok::less: Opc = BinaryOperator::LT; break;
1660 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1661 case tok::greater: Opc = BinaryOperator::GT; break;
1662 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1663 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1664 case tok::amp: Opc = BinaryOperator::And; break;
1665 case tok::caret: Opc = BinaryOperator::Xor; break;
1666 case tok::pipe: Opc = BinaryOperator::Or; break;
1667 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1668 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1669 case tok::equal: Opc = BinaryOperator::Assign; break;
1670 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1671 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1672 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1673 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1674 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1675 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1676 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1677 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1678 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1679 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1680 case tok::comma: Opc = BinaryOperator::Comma; break;
1681 }
1682 return Opc;
1683}
1684
1685static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1686 tok::TokenKind Kind) {
1687 UnaryOperator::Opcode Opc;
1688 switch (Kind) {
1689 default: assert(0 && "Unknown unary op!");
1690 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1691 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1692 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1693 case tok::star: Opc = UnaryOperator::Deref; break;
1694 case tok::plus: Opc = UnaryOperator::Plus; break;
1695 case tok::minus: Opc = UnaryOperator::Minus; break;
1696 case tok::tilde: Opc = UnaryOperator::Not; break;
1697 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1698 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1699 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1700 case tok::kw___real: Opc = UnaryOperator::Real; break;
1701 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1702 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1703 }
1704 return Opc;
1705}
1706
1707// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001708Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001709 ExprTy *LHS, ExprTy *RHS) {
1710 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1711 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1712
Steve Naroff87d58b42007-09-16 03:34:24 +00001713 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1714 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001715
1716 QualType ResultTy; // Result type of the binary operator.
1717 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1718
1719 switch (Opc) {
1720 default:
1721 assert(0 && "Unknown binary expr!");
1722 case BinaryOperator::Assign:
1723 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1724 break;
1725 case BinaryOperator::Mul:
1726 case BinaryOperator::Div:
1727 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1728 break;
1729 case BinaryOperator::Rem:
1730 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1731 break;
1732 case BinaryOperator::Add:
1733 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1734 break;
1735 case BinaryOperator::Sub:
1736 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1737 break;
1738 case BinaryOperator::Shl:
1739 case BinaryOperator::Shr:
1740 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1741 break;
1742 case BinaryOperator::LE:
1743 case BinaryOperator::LT:
1744 case BinaryOperator::GE:
1745 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001746 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001747 break;
1748 case BinaryOperator::EQ:
1749 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001750 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001751 break;
1752 case BinaryOperator::And:
1753 case BinaryOperator::Xor:
1754 case BinaryOperator::Or:
1755 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1756 break;
1757 case BinaryOperator::LAnd:
1758 case BinaryOperator::LOr:
1759 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1760 break;
1761 case BinaryOperator::MulAssign:
1762 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001763 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001764 if (!CompTy.isNull())
1765 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1766 break;
1767 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001768 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001769 if (!CompTy.isNull())
1770 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1771 break;
1772 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001773 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001774 if (!CompTy.isNull())
1775 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1776 break;
1777 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001778 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001779 if (!CompTy.isNull())
1780 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1781 break;
1782 case BinaryOperator::ShlAssign:
1783 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001784 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001785 if (!CompTy.isNull())
1786 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1787 break;
1788 case BinaryOperator::AndAssign:
1789 case BinaryOperator::XorAssign:
1790 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001791 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001792 if (!CompTy.isNull())
1793 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1794 break;
1795 case BinaryOperator::Comma:
1796 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1797 break;
1798 }
1799 if (ResultTy.isNull())
1800 return true;
1801 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001802 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001803 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001804 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001805}
1806
1807// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001808Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001809 ExprTy *input) {
1810 Expr *Input = (Expr*)input;
1811 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1812 QualType resultType;
1813 switch (Opc) {
1814 default:
1815 assert(0 && "Unimplemented unary expr!");
1816 case UnaryOperator::PreInc:
1817 case UnaryOperator::PreDec:
1818 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1819 break;
1820 case UnaryOperator::AddrOf:
1821 resultType = CheckAddressOfOperand(Input, OpLoc);
1822 break;
1823 case UnaryOperator::Deref:
1824 resultType = CheckIndirectionOperand(Input, OpLoc);
1825 break;
1826 case UnaryOperator::Plus:
1827 case UnaryOperator::Minus:
1828 UsualUnaryConversions(Input);
1829 resultType = Input->getType();
1830 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1831 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1832 resultType.getAsString());
1833 break;
1834 case UnaryOperator::Not: // bitwise complement
1835 UsualUnaryConversions(Input);
1836 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001837 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1838 if (!resultType->isIntegerType()) {
1839 if (resultType->isComplexType())
1840 // C99 does not support '~' for complex conjugation.
1841 Diag(OpLoc, diag::ext_integer_complement_complex,
1842 resultType.getAsString());
1843 else
1844 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1845 resultType.getAsString());
1846 }
Chris Lattner4b009652007-07-25 00:24:17 +00001847 break;
1848 case UnaryOperator::LNot: // logical negation
1849 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1850 DefaultFunctionArrayConversion(Input);
1851 resultType = Input->getType();
1852 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1853 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1854 resultType.getAsString());
1855 // LNot always has type int. C99 6.5.3.3p5.
1856 resultType = Context.IntTy;
1857 break;
1858 case UnaryOperator::SizeOf:
1859 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1860 break;
1861 case UnaryOperator::AlignOf:
1862 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1863 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001864 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001865 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001866 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001867 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001868 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001869 resultType = Input->getType();
1870 break;
1871 }
1872 if (resultType.isNull())
1873 return true;
1874 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1875}
1876
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001877/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1878Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001879 SourceLocation LabLoc,
1880 IdentifierInfo *LabelII) {
1881 // Look up the record for this label identifier.
1882 LabelStmt *&LabelDecl = LabelMap[LabelII];
1883
1884 // If we haven't seen this label yet, create a forward reference.
1885 if (LabelDecl == 0)
1886 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1887
1888 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001889 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1890 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001891}
1892
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001893Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00001894 SourceLocation RPLoc) { // "({..})"
1895 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1896 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1897 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1898
1899 // FIXME: there are a variety of strange constraints to enforce here, for
1900 // example, it is not possible to goto into a stmt expression apparently.
1901 // More semantic analysis is needed.
1902
1903 // FIXME: the last statement in the compount stmt has its value used. We
1904 // should not warn about it being unused.
1905
1906 // If there are sub stmts in the compound stmt, take the type of the last one
1907 // as the type of the stmtexpr.
1908 QualType Ty = Context.VoidTy;
1909
1910 if (!Compound->body_empty())
1911 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1912 Ty = LastExpr->getType();
1913
1914 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1915}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001916
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001917Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001918 SourceLocation TypeLoc,
1919 TypeTy *argty,
1920 OffsetOfComponent *CompPtr,
1921 unsigned NumComponents,
1922 SourceLocation RPLoc) {
1923 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1924 assert(!ArgTy.isNull() && "Missing type argument!");
1925
1926 // We must have at least one component that refers to the type, and the first
1927 // one is known to be a field designator. Verify that the ArgTy represents
1928 // a struct/union/class.
1929 if (!ArgTy->isRecordType())
1930 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1931
1932 // Otherwise, create a compound literal expression as the base, and
1933 // iteratively process the offsetof designators.
1934 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1935
Chris Lattnerb37522e2007-08-31 21:49:13 +00001936 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1937 // GCC extension, diagnose them.
1938 if (NumComponents != 1)
1939 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1940 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1941
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001942 for (unsigned i = 0; i != NumComponents; ++i) {
1943 const OffsetOfComponent &OC = CompPtr[i];
1944 if (OC.isBrackets) {
1945 // Offset of an array sub-field. TODO: Should we allow vector elements?
1946 const ArrayType *AT = Res->getType()->getAsArrayType();
1947 if (!AT) {
1948 delete Res;
1949 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1950 Res->getType().getAsString());
1951 }
1952
Chris Lattner2af6a802007-08-30 17:59:59 +00001953 // FIXME: C++: Verify that operator[] isn't overloaded.
1954
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001955 // C99 6.5.2.1p1
1956 Expr *Idx = static_cast<Expr*>(OC.U.E);
1957 if (!Idx->getType()->isIntegerType())
1958 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1959 Idx->getSourceRange());
1960
1961 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1962 continue;
1963 }
1964
1965 const RecordType *RC = Res->getType()->getAsRecordType();
1966 if (!RC) {
1967 delete Res;
1968 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1969 Res->getType().getAsString());
1970 }
1971
1972 // Get the decl corresponding to this.
1973 RecordDecl *RD = RC->getDecl();
1974 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1975 if (!MemberDecl)
1976 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1977 OC.U.IdentInfo->getName(),
1978 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00001979
1980 // FIXME: C++: Verify that MemberDecl isn't a static field.
1981 // FIXME: Verify that MemberDecl isn't a bitfield.
1982
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001983 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1984 }
1985
1986 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1987 BuiltinLoc);
1988}
1989
1990
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001991Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00001992 TypeTy *arg1, TypeTy *arg2,
1993 SourceLocation RPLoc) {
1994 QualType argT1 = QualType::getFromOpaquePtr(arg1);
1995 QualType argT2 = QualType::getFromOpaquePtr(arg2);
1996
1997 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
1998
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001999 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002000}
2001
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002002Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002003 ExprTy *expr1, ExprTy *expr2,
2004 SourceLocation RPLoc) {
2005 Expr *CondExpr = static_cast<Expr*>(cond);
2006 Expr *LHSExpr = static_cast<Expr*>(expr1);
2007 Expr *RHSExpr = static_cast<Expr*>(expr2);
2008
2009 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2010
2011 // The conditional expression is required to be a constant expression.
2012 llvm::APSInt condEval(32);
2013 SourceLocation ExpLoc;
2014 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2015 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2016 CondExpr->getSourceRange());
2017
2018 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2019 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2020 RHSExpr->getType();
2021 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2022}
2023
Anders Carlsson36760332007-10-15 20:28:48 +00002024Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2025 ExprTy *expr, TypeTy *type,
2026 SourceLocation RPLoc)
2027{
2028 Expr *E = static_cast<Expr*>(expr);
2029 QualType T = QualType::getFromOpaquePtr(type);
2030
2031 InitBuiltinVaListType();
2032
2033 Sema::AssignmentCheckResult result;
2034
2035 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
2036 E->getType());
2037 if (result != Compatible)
2038 return Diag(E->getLocStart(),
2039 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2040 E->getType().getAsString(),
2041 E->getSourceRange());
2042
2043 // FIXME: Warn if a non-POD type is passed in.
2044
2045 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2046}
2047
Anders Carlssona66cad42007-08-21 17:43:55 +00002048// TODO: Move this to SemaObjC.cpp
Chris Lattnerddd3e632007-12-12 01:04:12 +00002049Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
2050 ExprTy **Strings,
2051 unsigned NumStrings) {
2052
2053 // FIXME: This is passed in an ARRAY of strings which need to be concatenated.
2054 // Handle this case here. For now we just ignore all but the first one.
2055 SourceLocation AtLoc = AtLocs[0];
2056 StringLiteral* S = static_cast<StringLiteral *>(Strings[0]);
Anders Carlssona66cad42007-08-21 17:43:55 +00002057
2058 if (CheckBuiltinCFStringArgument(S))
2059 return true;
2060
Steve Narofff2e30312007-10-15 23:35:17 +00002061 if (Context.getObjcConstantStringInterface().isNull()) {
2062 // Initialize the constant string interface lazily. This assumes
2063 // the NSConstantString interface is seen in this translation unit.
2064 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
2065 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
2066 SourceLocation(), TUScope);
Steve Naroff134c3502007-10-16 00:00:18 +00002067 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff96f136d2007-10-18 23:53:51 +00002068 if (!strIFace)
2069 return Diag(S->getLocStart(), diag::err_undef_interface,
2070 NSIdent->getName());
Steve Naroff134c3502007-10-16 00:00:18 +00002071 Context.setObjcConstantStringInterface(strIFace);
Steve Narofff2e30312007-10-15 23:35:17 +00002072 }
2073 QualType t = Context.getObjcConstantStringInterface();
Anders Carlssona66cad42007-08-21 17:43:55 +00002074 t = Context.getPointerType(t);
Steve Naroff0add5d22007-11-03 11:27:19 +00002075 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlssona66cad42007-08-21 17:43:55 +00002076}
Anders Carlsson8be1d402007-08-22 15:14:15 +00002077
2078Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattnercfd61c82007-10-16 22:51:17 +00002079 SourceLocation EncodeLoc,
Anders Carlsson8be1d402007-08-22 15:14:15 +00002080 SourceLocation LParenLoc,
2081 TypeTy *Ty,
2082 SourceLocation RParenLoc) {
2083 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
2084
2085 QualType t = Context.getPointerType(Context.CharTy);
2086 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
2087}
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002088
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002089Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
2090 SourceLocation AtLoc,
Fariborz Jahanian957448a2007-10-16 23:21:02 +00002091 SourceLocation SelLoc,
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002092 SourceLocation LParenLoc,
2093 SourceLocation RParenLoc) {
Steve Naroffae84af82007-10-31 18:42:27 +00002094 QualType t = Context.getObjcSelType();
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002095 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
2096}
2097
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002098Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
2099 SourceLocation AtLoc,
2100 SourceLocation ProtoLoc,
2101 SourceLocation LParenLoc,
2102 SourceLocation RParenLoc) {
2103 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
2104 if (!PDecl) {
2105 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
2106 return true;
2107 }
2108
Fariborz Jahanianb4452ed2007-12-07 00:18:54 +00002109 QualType t = Context.getObjcProtoType();
Fariborz Jahanian20b40e42007-10-18 22:59:23 +00002110 if (t.isNull())
2111 return true;
Fariborz Jahanianb4452ed2007-12-07 00:18:54 +00002112 t = Context.getPointerType(t);
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002113 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
2114}
Steve Naroff52664182007-10-16 23:12:48 +00002115
2116bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2117 ObjcMethodDecl *Method) {
2118 bool anyIncompatibleArgs = false;
2119
2120 for (unsigned i = 0; i < NumArgs; i++) {
2121 Expr *argExpr = Args[i];
2122 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2123
2124 QualType lhsType = Method->getParamDecl(i)->getType();
2125 QualType rhsType = argExpr->getType();
2126
2127 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2128 if (const ArrayType *ary = lhsType->getAsArrayType())
2129 lhsType = Context.getPointerType(ary->getElementType());
2130 else if (lhsType->isFunctionType())
2131 lhsType = Context.getPointerType(lhsType);
2132
2133 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2134 argExpr);
2135 if (Args[i] != argExpr) // The expression was converted.
2136 Args[i] = argExpr; // Make sure we store the converted expression.
2137 SourceLocation l = argExpr->getLocStart();
2138
2139 // decode the result (notice that AST's are still created for extensions).
2140 switch (result) {
2141 case Compatible:
2142 break;
2143 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +00002144 Diag(l, diag::ext_typecheck_sending_pointer_int,
2145 lhsType.getAsString(), rhsType.getAsString(),
2146 argExpr->getSourceRange());
Steve Naroff52664182007-10-16 23:12:48 +00002147 break;
2148 case IntFromPointer:
2149 Diag(l, diag::ext_typecheck_sending_pointer_int,
2150 lhsType.getAsString(), rhsType.getAsString(),
2151 argExpr->getSourceRange());
2152 break;
2153 case IncompatiblePointer:
2154 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2155 rhsType.getAsString(), lhsType.getAsString(),
2156 argExpr->getSourceRange());
2157 break;
2158 case CompatiblePointerDiscardsQualifiers:
2159 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2160 rhsType.getAsString(), lhsType.getAsString(),
2161 argExpr->getSourceRange());
2162 break;
2163 case Incompatible:
2164 Diag(l, diag::err_typecheck_sending_incompatible,
2165 rhsType.getAsString(), lhsType.getAsString(),
2166 argExpr->getSourceRange());
2167 anyIncompatibleArgs = true;
2168 }
2169 }
2170 return anyIncompatibleArgs;
2171}
2172
Steve Naroff4ed9d662007-09-27 14:38:14 +00002173// ActOnClassMessage - used for both unary and keyword messages.
2174// ArgExprs is optional - if it is present, the number of expressions
2175// is obtained from Sel.getNumArgs().
2176Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002177 Scope *S,
Steve Narofffa465d12007-10-02 20:01:56 +00002178 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002179 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002180{
Steve Narofffa465d12007-10-02 20:01:56 +00002181 assert(receiverName && "missing receiver class name");
Steve Naroffc39ca262007-09-18 23:55:05 +00002182
Steve Naroff52664182007-10-16 23:12:48 +00002183 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002184 ObjcInterfaceDecl* ClassDecl = 0;
2185 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2186 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahanian342f3602007-11-12 20:20:37 +00002187 if (ClassDecl && CurMethodDecl->isInstance()) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002188 // Synthesize a cast to the super class. This hack allows us to loosely
2189 // represent super without creating a special expression node.
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002190 IdentifierInfo &II = Context.Idents.get("self");
Steve Naroff3b1caac2007-12-07 03:50:46 +00002191 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II, false);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002192 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2193 superTy = Context.getPointerType(superTy);
2194 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2195 SourceLocation(), ReceiverExpr.Val);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002196 // We are really in an instance method, redirect.
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002197 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002198 Args, NumArgs);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002199 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00002200 // We are sending a message to 'super' within a class method. Do nothing,
2201 // the receiver will pass through as 'super' (how convenient:-).
2202 } else
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002203 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002204
2205 // FIXME: can ClassDecl ever be null?
Steve Narofffa465d12007-10-02 20:01:56 +00002206 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002207 QualType returnType;
Steve Naroff75c4baf2007-11-05 15:27:52 +00002208
2209 // Before we give up, check if the selector is an instance method.
2210 if (!Method)
2211 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002212 if (!Method) {
2213 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2214 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002215 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002216 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002217 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002218 if (Sel.getNumArgs()) {
2219 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2220 return true;
2221 }
Steve Naroff7e461452007-10-16 20:39:36 +00002222 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002223 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
Steve Naroff9f176d12007-11-15 13:05:42 +00002224 lbrac, rbrac, ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002225}
2226
Steve Naroff4ed9d662007-09-27 14:38:14 +00002227// ActOnInstanceMessage - used for both unary and keyword messages.
2228// ArgExprs is optional - if it is present, the number of expressions
2229// is obtained from Sel.getNumArgs().
2230Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroff6cb1d362007-09-28 22:22:11 +00002231 ExprTy *receiver, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002232 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff4ed9d662007-09-27 14:38:14 +00002233{
Steve Naroffc39ca262007-09-18 23:55:05 +00002234 assert(receiver && "missing receiver expression");
2235
Steve Naroff52664182007-10-16 23:12:48 +00002236 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroffc39ca262007-09-18 23:55:05 +00002237 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Narofffa465d12007-10-02 20:01:56 +00002238 QualType receiverType = RExpr->getType();
Steve Naroffee1de132007-10-10 21:53:07 +00002239 QualType returnType;
Steve Naroff1e1c3912007-11-03 16:37:59 +00002240 ObjcMethodDecl *Method;
Steve Naroffee1de132007-10-10 21:53:07 +00002241
Steve Naroff0091d142007-11-11 17:52:25 +00002242 if (receiverType == Context.getObjcIdType() ||
2243 receiverType == Context.getObjcClassType()) {
Steve Naroff1e1c3912007-11-03 16:37:59 +00002244 Method = InstanceMethodPool[Sel].Method;
Steve Naroffd0cfcd02007-11-13 04:10:18 +00002245 // If we didn't find an public method, look for a private one.
2246 if (!Method && CurMethodDecl) {
2247 NamedDecl *impCxt = CurMethodDecl->getMethodContext();
2248 if (ObjcImplementationDecl *IMD =
2249 dyn_cast<ObjcImplementationDecl>(impCxt)) {
2250 if (receiverType == Context.getObjcIdType())
2251 Method = IMD->lookupInstanceMethod(Sel);
2252 else
2253 Method = IMD->lookupClassMethod(Sel);
2254 } else if (ObjcCategoryImplDecl *CID =
2255 dyn_cast<ObjcCategoryImplDecl>(impCxt)) {
2256 if (receiverType == Context.getObjcIdType())
2257 Method = CID->lookupInstanceMethod(Sel);
2258 else
2259 Method = CID->lookupClassMethod(Sel);
2260 }
2261 }
Steve Naroff7e461452007-10-16 20:39:36 +00002262 if (!Method) {
2263 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2264 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002265 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002266 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002267 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002268 if (Sel.getNumArgs())
2269 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2270 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002271 }
Steve Naroffee1de132007-10-10 21:53:07 +00002272 } else {
Chris Lattner71c01112007-10-10 23:42:28 +00002273 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2274 // revisited. how do we get the ClassDecl from the receiver expression?
Steve Naroffee1de132007-10-10 21:53:07 +00002275 while (receiverType->isPointerType()) {
Chris Lattner71c01112007-10-10 23:42:28 +00002276 PointerType *pointerType =
2277 static_cast<PointerType*>(receiverType.getTypePtr());
Steve Naroffee1de132007-10-10 21:53:07 +00002278 receiverType = pointerType->getPointeeType();
2279 }
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002280 ObjcInterfaceDecl* ClassDecl;
2281 if (ObjcQualifiedInterfaceType *QIT =
2282 dyn_cast<ObjcQualifiedInterfaceType>(receiverType)) {
2283 ObjcInterfaceType * OITypePtr = QIT->getInterfaceType();
2284
2285 ClassDecl = OITypePtr->getDecl();
2286 Method = ClassDecl->lookupInstanceMethod(Sel);
2287 if (!Method) {
2288 // search protocols
2289 for (unsigned i = 0; i < QIT->getNumProtocols(); i++) {
2290 ObjcProtocolDecl *PDecl = QIT->getProtocols(i);
2291 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
2292 break;
2293 }
2294 }
2295 }
2296 else {
2297 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2298 "bad receiver type");
2299 ClassDecl = static_cast<ObjcInterfaceType*>(
2300 receiverType.getTypePtr())->getDecl();
2301 // FIXME: consider using InstanceMethodPool, since it will be faster
2302 // than the following method (which can do *many* linear searches). The
2303 // idea is to add class info to InstanceMethodPool...
2304 Method = ClassDecl->lookupInstanceMethod(Sel);
2305 }
Steve Naroff7e461452007-10-16 20:39:36 +00002306 if (!Method) {
Steve Naroffb1c7ad92007-11-11 00:10:47 +00002307 // If we have an implementation in scope, check "private" methods.
2308 if (ObjcImplementationDecl *ImpDecl =
2309 ObjcImplementations[ClassDecl->getIdentifier()])
2310 Method = ImpDecl->lookupInstanceMethod(Sel);
Steve Naroff20255552007-12-11 03:38:03 +00002311 // If we still haven't found a method, look in the global pool. This
2312 // behavior isn't very desirable, however we need it for GCC compatibility.
Steve Naroffc4793582007-12-07 20:41:14 +00002313 if (!Method)
2314 Method = InstanceMethodPool[Sel].Method;
Steve Naroffb1c7ad92007-11-11 00:10:47 +00002315 }
2316 if (!Method) {
Steve Naroff7e461452007-10-16 20:39:36 +00002317 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2318 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002319 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002320 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002321 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002322 if (Sel.getNumArgs())
2323 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2324 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002325 }
Steve Narofffa465d12007-10-02 20:01:56 +00002326 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002327 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002328 ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002329}