blob: c815b5486897dd639c9d2dff681b697aa8308768 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
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"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/Expr.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000018#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Chris Lattner83bd5eb2007-12-28 05:29:59 +000023#include "llvm/ADT/OwningPtr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000025#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026using namespace clang;
27
Steve Naroff87d58b42007-09-16 03:34:24 +000028/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000029/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
30/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
31/// multiple tokens. However, the common case is that StringToks points to one
32/// string.
33///
34Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000035Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000036 assert(NumStringToks && "Must have at least one string!");
37
38 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
39 if (Literal.hadError)
40 return ExprResult(true);
41
42 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
43 for (unsigned i = 0; i != NumStringToks; ++i)
44 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +000045
46 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000047 if (Literal.Pascal && Literal.GetStringLength() > 256)
48 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
49 SourceRange(StringToks[0].getLocation(),
50 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000051
Chris Lattnera6dcce32008-02-11 00:02:17 +000052 QualType StrTy = Context.CharTy;
53 // FIXME: handle wchar_t
54 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
55
56 // Get an array type for the string, according to C99 6.4.5. This includes
57 // the nul terminator character as well as the string length for pascal
58 // strings.
59 StrTy = Context.getConstantArrayType(StrTy,
60 llvm::APInt(32, Literal.GetStringLength()+1),
61 ArrayType::Normal, 0);
62
Chris Lattner4b009652007-07-25 00:24:17 +000063 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
64 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +000065 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000066 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000067 StringToks[NumStringToks-1].getLocation());
68}
69
70
Steve Naroff0acc9c92007-09-15 18:49:24 +000071/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000072/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +000073/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000074Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000075 IdentifierInfo &II,
76 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +000077 // Could be enum-constant, value decl, instance variable, etc.
Steve Narofff0c31dd2007-09-16 16:16:00 +000078 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +000079
80 // If this reference is in an Objective-C method, then ivar lookup happens as
81 // well.
82 if (CurMethodDecl) {
83 // There are two cases to handle here. 1) scoped lookup could have failed,
84 // in which case we should look for an ivar. 2) scoped lookup could have
85 // found a decl, but that decl is outside the current method (i.e. a global
86 // variable). In these two cases, we do a lookup for an ivar with this
87 // name, if the lookup suceeds, we replace it our current decl.
88 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
89 ObjCInterfaceDecl *IFace = CurMethodDecl->getClassInterface(), *DeclClass;
90 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II, DeclClass)) {
91 // FIXME: This should use a new expr for a direct reference, don't turn
92 // this into Self->ivar, just return a BareIVarExpr or something.
93 IdentifierInfo &II = Context.Idents.get("self");
94 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
95 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
96 static_cast<Expr*>(SelfExpr.Val), true, true);
97 }
98 }
99 }
100
Chris Lattner4b009652007-07-25 00:24:17 +0000101 if (D == 0) {
102 // Otherwise, this could be an implicitly declared function reference (legal
103 // in C90, extension in C99).
104 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000105 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000106 D = ImplicitlyDefineFunction(Loc, II, S);
107 else {
108 // If this name wasn't predeclared and if this is not a function call,
109 // diagnose the problem.
110 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
111 }
112 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000113
Steve Naroff91b03f72007-08-28 03:03:08 +0000114 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneree4c3bf2008-02-29 16:48:43 +0000115 // check if referencing an identifier with __attribute__((deprecated)).
116 if (VD->getAttr<DeprecatedAttr>())
117 Diag(Loc, diag::warn_deprecated, VD->getName());
118
Steve Naroffcae537d2007-08-28 18:45:29 +0000119 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000120 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000121 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000122 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000123 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000124
Chris Lattner4b009652007-07-25 00:24:17 +0000125 if (isa<TypedefDecl>(D))
126 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000127 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000128 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000129
130 assert(0 && "Invalid decl");
131 abort();
132}
133
Steve Naroff87d58b42007-09-16 03:34:24 +0000134Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000135 tok::TokenKind Kind) {
136 PreDefinedExpr::IdentType IT;
137
138 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000139 default: assert(0 && "Unknown simple primary expr!");
140 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
141 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
142 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000143 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000144
145 // Verify that this is in a function context.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000146 if (CurFunctionDecl == 0 && CurMethodDecl == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000147 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000148
Chris Lattner7e637512008-01-12 08:14:25 +0000149 // Pre-defined identifiers are of type char[x], where x is the length of the
150 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000151 unsigned Length;
152 if (CurFunctionDecl)
153 Length = CurFunctionDecl->getIdentifier()->getLength();
154 else
Fariborz Jahaniandcecd5c2008-01-17 17:37:26 +0000155 Length = CurMethodDecl->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000156
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000157 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000158 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000159 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner7e637512008-01-12 08:14:25 +0000160 return new PreDefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000161}
162
Steve Naroff87d58b42007-09-16 03:34:24 +0000163Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000164 llvm::SmallString<16> CharBuffer;
165 CharBuffer.resize(Tok.getLength());
166 const char *ThisTokBegin = &CharBuffer[0];
167 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
168
169 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
170 Tok.getLocation(), PP);
171 if (Literal.hadError())
172 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000173
174 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
175
176 return new CharacterLiteral(Literal.getValue(), type, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000177}
178
Steve Naroff87d58b42007-09-16 03:34:24 +0000179Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000180 // fast path for a single digit (which is quite common). A single digit
181 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
182 if (Tok.getLength() == 1) {
183 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
184
Chris Lattner8cd0e932008-03-05 18:54:05 +0000185 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner4b009652007-07-25 00:24:17 +0000186 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
187 Context.IntTy,
188 Tok.getLocation()));
189 }
190 llvm::SmallString<512> IntegerBuffer;
191 IntegerBuffer.resize(Tok.getLength());
192 const char *ThisTokBegin = &IntegerBuffer[0];
193
194 // Get the spelling of the token, which eliminates trigraphs, etc.
195 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
196 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
197 Tok.getLocation(), PP);
198 if (Literal.hadError)
199 return ExprResult(true);
200
Chris Lattner1de66eb2007-08-26 03:42:43 +0000201 Expr *Res;
202
203 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000204 QualType Ty;
205 const llvm::fltSemantics *Format;
Chris Lattner858eece2007-09-22 18:29:59 +0000206
207 if (Literal.isFloat) {
208 Ty = Context.FloatTy;
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000209 Format = Context.Target.getFloatFormat();
210 } else if (!Literal.isLong) {
Chris Lattner858eece2007-09-22 18:29:59 +0000211 Ty = Context.DoubleTy;
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000212 Format = Context.Target.getDoubleFormat();
213 } else {
214 Ty = Context.LongDoubleTy;
215 Format = Context.Target.getLongDoubleFormat();
Chris Lattner858eece2007-09-22 18:29:59 +0000216 }
217
Ted Kremenekddedbe22007-11-29 00:56:49 +0000218 // isExact will be set by GetFloatValue().
219 bool isExact = false;
220
221 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
222 Ty, Tok.getLocation());
223
Chris Lattner1de66eb2007-08-26 03:42:43 +0000224 } else if (!Literal.isIntegerLiteral()) {
225 return ExprResult(true);
226 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000227 QualType t;
228
Neil Booth7421e9c2007-08-29 22:00:19 +0000229 // long long is a C99 feature.
230 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000231 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000232 Diag(Tok.getLocation(), diag::ext_longlong);
233
Chris Lattner4b009652007-07-25 00:24:17 +0000234 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000235 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000236
237 if (Literal.GetIntegerValue(ResultVal)) {
238 // If this value didn't fit into uintmax_t, warn and force to ull.
239 Diag(Tok.getLocation(), diag::warn_integer_too_large);
240 t = Context.UnsignedLongLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +0000241 assert(Context.getTypeSize(t) == ResultVal.getBitWidth() &&
242 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000243 } else {
244 // If this value fits into a ULL, try to figure out what else it fits into
245 // according to the rules of C99 6.4.4.1p5.
246
247 // Octal, Hexadecimal, and integers with a U suffix are allowed to
248 // be an unsigned int.
249 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
250
251 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000252 if (!Literal.isLong && !Literal.isLongLong) {
253 // Are int/unsigned possibilities?
Chris Lattner8cd0e932008-03-05 18:54:05 +0000254 unsigned IntSize =
255 static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner4b009652007-07-25 00:24:17 +0000256 // Does it fit in a unsigned int?
257 if (ResultVal.isIntN(IntSize)) {
258 // Does it fit in a signed int?
259 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
260 t = Context.IntTy;
261 else if (AllowUnsigned)
262 t = Context.UnsignedIntTy;
263 }
264
265 if (!t.isNull())
266 ResultVal.trunc(IntSize);
267 }
268
269 // Are long/unsigned long possibilities?
270 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000271 unsigned LongSize =
272 static_cast<unsigned>(Context.getTypeSize(Context.LongTy));
Chris Lattner4b009652007-07-25 00:24:17 +0000273
274 // Does it fit in a unsigned long?
275 if (ResultVal.isIntN(LongSize)) {
276 // Does it fit in a signed long?
277 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
278 t = Context.LongTy;
279 else if (AllowUnsigned)
280 t = Context.UnsignedLongTy;
281 }
282 if (!t.isNull())
283 ResultVal.trunc(LongSize);
284 }
285
286 // Finally, check long long if needed.
287 if (t.isNull()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000288 unsigned LongLongSize =
289 static_cast<unsigned>(Context.getTypeSize(Context.LongLongTy));
Chris Lattner4b009652007-07-25 00:24:17 +0000290
291 // Does it fit in a unsigned long long?
292 if (ResultVal.isIntN(LongLongSize)) {
293 // Does it fit in a signed long long?
294 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
295 t = Context.LongLongTy;
296 else if (AllowUnsigned)
297 t = Context.UnsignedLongLongTy;
298 }
299 }
300
301 // If we still couldn't decide a type, we probably have something that
302 // does not fit in a signed long long, but has no U suffix.
303 if (t.isNull()) {
304 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
305 t = Context.UnsignedLongLongTy;
306 }
307 }
308
Chris Lattner1de66eb2007-08-26 03:42:43 +0000309 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000310 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000311
312 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
313 if (Literal.isImaginary)
314 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
315
316 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000317}
318
Steve Naroff87d58b42007-09-16 03:34:24 +0000319Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000320 ExprTy *Val) {
321 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000322 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000323 return new ParenExpr(L, R, e);
324}
325
326/// The UsualUnaryConversions() function is *not* called by this routine.
327/// See C99 6.3.2.1p[2-4] for more details.
328QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
329 SourceLocation OpLoc, bool isSizeof) {
330 // C99 6.5.3.4p1:
331 if (isa<FunctionType>(exprType) && isSizeof)
332 // alignof(function) is allowed.
333 Diag(OpLoc, diag::ext_sizeof_function_type);
334 else if (exprType->isVoidType())
335 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
336 else if (exprType->isIncompleteType()) {
337 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
338 diag::err_alignof_incomplete_type,
339 exprType.getAsString());
340 return QualType(); // error
341 }
342 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
343 return Context.getSizeType();
344}
345
346Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000347ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000348 SourceLocation LPLoc, TypeTy *Ty,
349 SourceLocation RPLoc) {
350 // If error parsing type, ignore.
351 if (Ty == 0) return true;
352
353 // Verify that this is a valid expression.
354 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
355
356 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
357
358 if (resultType.isNull())
359 return true;
360 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
361}
362
Chris Lattner5110ad52007-08-24 21:41:10 +0000363QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000364 DefaultFunctionArrayConversion(V);
365
Chris Lattnera16e42d2007-08-26 05:39:26 +0000366 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000367 if (const ComplexType *CT = V->getType()->getAsComplexType())
368 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000369
370 // Otherwise they pass through real integer and floating point types here.
371 if (V->getType()->isArithmeticType())
372 return V->getType();
373
374 // Reject anything else.
375 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
376 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000377}
378
379
Chris Lattner4b009652007-07-25 00:24:17 +0000380
Steve Naroff87d58b42007-09-16 03:34:24 +0000381Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000382 tok::TokenKind Kind,
383 ExprTy *Input) {
384 UnaryOperator::Opcode Opc;
385 switch (Kind) {
386 default: assert(0 && "Unknown unary op!");
387 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
388 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
389 }
390 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
391 if (result.isNull())
392 return true;
393 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
394}
395
396Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000397ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000398 ExprTy *Idx, SourceLocation RLoc) {
399 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
400
401 // Perform default conversions.
402 DefaultFunctionArrayConversion(LHSExp);
403 DefaultFunctionArrayConversion(RHSExp);
404
405 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
406
407 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000408 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000409 // in the subscript position. As a result, we need to derive the array base
410 // and index from the expression types.
411 Expr *BaseExpr, *IndexExpr;
412 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000413 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000414 BaseExpr = LHSExp;
415 IndexExpr = RHSExp;
416 // FIXME: need to deal with const...
417 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000418 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000419 // Handle the uncommon case of "123[Ptr]".
420 BaseExpr = RHSExp;
421 IndexExpr = LHSExp;
422 // FIXME: need to deal with const...
423 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000424 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
425 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000426 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000427
428 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman506806b2008-02-19 01:11:03 +0000429 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr))
Steve Naroff89345522007-08-03 22:40:33 +0000430 return Diag(LLoc, diag::err_ocuvector_component_access,
431 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000432 // FIXME: need to deal with const...
433 ResultType = VTy->getElementType();
434 } else {
435 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
436 RHSExp->getSourceRange());
437 }
438 // C99 6.5.2.1p1
439 if (!IndexExpr->getType()->isIntegerType())
440 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
441 IndexExpr->getSourceRange());
442
443 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
444 // the following check catches trying to index a pointer to a function (e.g.
445 // void (*)(int)). Functions are not objects in C99.
446 if (!ResultType->isObjectType())
447 return Diag(BaseExpr->getLocStart(),
448 diag::err_typecheck_subscript_not_object,
449 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
450
451 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
452}
453
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000454QualType Sema::
455CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
456 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000457 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000458
459 // The vector accessor can't exceed the number of elements.
460 const char *compStr = CompName.getName();
461 if (strlen(compStr) > vecType->getNumElements()) {
462 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
463 baseType.getAsString(), SourceRange(CompLoc));
464 return QualType();
465 }
466 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000467 if (vecType->getPointAccessorIdx(*compStr) != -1) {
468 do
469 compStr++;
470 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
471 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
472 do
473 compStr++;
474 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
475 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
476 do
477 compStr++;
478 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
479 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000480
481 if (*compStr) {
482 // We didn't get to the end of the string. This means the component names
483 // didn't come from the same set *or* we encountered an illegal name.
484 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
485 std::string(compStr,compStr+1), SourceRange(CompLoc));
486 return QualType();
487 }
488 // Each component accessor can't exceed the vector type.
489 compStr = CompName.getName();
490 while (*compStr) {
491 if (vecType->isAccessorWithinNumElements(*compStr))
492 compStr++;
493 else
494 break;
495 }
496 if (*compStr) {
497 // We didn't get to the end of the string. This means a component accessor
498 // exceeds the number of elements in the vector.
499 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
500 baseType.getAsString(), SourceRange(CompLoc));
501 return QualType();
502 }
503 // The component accessor looks fine - now we need to compute the actual type.
504 // The vector type is implied by the component accessor. For example,
505 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
506 unsigned CompSize = strlen(CompName.getName());
507 if (CompSize == 1)
508 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000509
510 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
511 // Now look up the TypeDefDecl from the vector type. Without this,
512 // diagostics look bad. We want OCU vector types to appear built-in.
513 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
514 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
515 return Context.getTypedefType(OCUVectorDecls[i]);
516 }
517 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000518}
519
Chris Lattner4b009652007-07-25 00:24:17 +0000520Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000521ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000522 tok::TokenKind OpKind, SourceLocation MemberLoc,
523 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000524 Expr *BaseExpr = static_cast<Expr *>(Base);
525 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000526
527 // Perform default conversions.
528 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000529
Steve Naroff2cb66382007-07-26 03:11:44 +0000530 QualType BaseType = BaseExpr->getType();
531 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000532
Chris Lattner4b009652007-07-25 00:24:17 +0000533 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000534 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000535 BaseType = PT->getPointeeType();
536 else
537 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
538 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000539 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000540 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000541 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000542 RecordDecl *RDecl = RTy->getDecl();
543 if (RTy->isIncompleteType())
544 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
545 BaseExpr->getSourceRange());
546 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000547 FieldDecl *MemberDecl = RDecl->getMember(&Member);
548 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000549 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
550 SourceRange(MemberLoc));
Eli Friedman76b49832008-02-06 22:48:16 +0000551
552 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000553 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000554 QualType MemberType = MemberDecl->getType();
555 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000556 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000557 MemberType = MemberType.getQualifiedType(combinedQualifiers);
558
559 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl,
560 MemberLoc, MemberType);
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000561 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000562 // Component access limited to variables (reject vec4.rg.g).
Nate Begeman78a2a312008-03-17 17:22:18 +0000563 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr))
Steve Naroff89345522007-08-03 22:40:33 +0000564 return Diag(OpLoc, diag::err_ocuvector_component_access,
565 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000566 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
567 if (ret.isNull())
568 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000569 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Ted Kremenek42730c52008-01-07 19:49:32 +0000570 } else if (BaseType->isObjCInterfaceType()) {
571 ObjCInterfaceDecl *IFace;
572 if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
573 IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000574 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000575 IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
576 ObjCInterfaceDecl *clsDeclared;
577 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000578 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
579 OpKind==tok::arrow);
580 }
581 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
582 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000583}
584
Steve Naroff87d58b42007-09-16 03:34:24 +0000585/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000586/// This provides the location of the left/right parens and a list of comma
587/// locations.
588Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000589ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000590 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000591 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
592 Expr *Fn = static_cast<Expr *>(fn);
593 Expr **Args = reinterpret_cast<Expr**>(args);
594 assert(Fn && "no function call expression");
595
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000596 // Make the call expr early, before semantic checks. This guarantees cleanup
597 // of arguments and function on error.
598 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
599 Context.BoolTy, RParenLoc));
600
601 // Promote the function operand.
602 TheCall->setCallee(UsualUnaryConversions(Fn));
603
Chris Lattner4b009652007-07-25 00:24:17 +0000604 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
605 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000606 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000607 if (PT == 0)
608 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
609 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000610 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
611 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000612 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
613 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000614
615 // We know the result type of the call, set it.
616 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000617
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000618 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000619 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
620 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000621 unsigned NumArgsInProto = Proto->getNumArgs();
622 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000623
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000624 // If too few arguments are available, don't make the call.
625 if (NumArgs < NumArgsInProto)
626 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
627 Fn->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000628
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000629 // If too many are passed and not variadic, error on the extras and drop
630 // them.
631 if (NumArgs > NumArgsInProto) {
632 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000633 Diag(Args[NumArgsInProto]->getLocStart(),
634 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
635 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000636 Args[NumArgs-1]->getLocEnd()));
637 // This deletes the extra arguments.
638 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000639 }
640 NumArgsToCheck = NumArgsInProto;
641 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000642
Chris Lattner4b009652007-07-25 00:24:17 +0000643 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000644 for (unsigned i = 0; i != NumArgsToCheck; i++) {
645 Expr *Arg = Args[i];
Chris Lattner005ed752008-01-04 18:04:52 +0000646 QualType ProtoArgType = Proto->getArgType(i);
647 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000648
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000649 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +0000650 AssignConvertType ConvTy =
651 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000652 TheCall->setArg(i, Arg);
653
Chris Lattner005ed752008-01-04 18:04:52 +0000654 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
655 ArgType, Arg, "passing"))
656 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000657 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000658
659 // If this is a variadic call, handle args passed through "...".
660 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +0000661 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000662 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
663 Expr *Arg = Args[i];
664 DefaultArgumentPromotion(Arg);
665 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000666 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000667 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000668 } else {
669 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
670
Steve Naroffdb65e052007-08-28 23:30:39 +0000671 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000672 for (unsigned i = 0; i != NumArgs; i++) {
673 Expr *Arg = Args[i];
674 DefaultArgumentPromotion(Arg);
675 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000676 }
Chris Lattner4b009652007-07-25 00:24:17 +0000677 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000678
Chris Lattner2e64c072007-08-10 20:18:51 +0000679 // Do special checking on direct calls to functions.
680 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
681 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
682 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000683 if (CheckFunctionCall(FDecl, TheCall.get()))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000684 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000685
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000686 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000687}
688
689Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000690ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000691 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000692 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000693 QualType literalType = QualType::getFromOpaquePtr(Ty);
694 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000695 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000696 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000697
Steve Naroffcb69fb72007-12-10 22:44:33 +0000698 // FIXME: add more semantic analysis (C99 6.5.2.5).
Steve Narofff0b23542008-01-10 22:15:12 +0000699 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +0000700 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +0000701
702 bool isFileScope = !CurFunctionDecl && !CurMethodDecl;
703 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +0000704 if (CheckForConstantInitializer(literalExpr, literalType))
705 return true;
706 }
Steve Naroffbe37fc02008-01-14 18:19:28 +0000707 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000708}
709
710Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000711ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000712 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000713 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000714
Steve Naroff0acc9c92007-09-15 18:49:24 +0000715 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000716 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000717
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000718 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
719 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
720 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000721}
722
Chris Lattnerd1f26b32007-12-20 00:44:32 +0000723bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000724 assert(VectorTy->isVectorType() && "Not a vector type!");
725
726 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000727 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000728 return Diag(R.getBegin(),
729 Ty->isVectorType() ?
730 diag::err_invalid_conversion_between_vectors :
731 diag::err_invalid_conversion_between_vector_and_integer,
732 VectorTy.getAsString().c_str(),
733 Ty.getAsString().c_str(), R);
734 } else
735 return Diag(R.getBegin(),
736 diag::err_invalid_conversion_between_vector_and_scalar,
737 VectorTy.getAsString().c_str(),
738 Ty.getAsString().c_str(), R);
739
740 return false;
741}
742
Chris Lattner4b009652007-07-25 00:24:17 +0000743Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000744ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000745 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000746 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000747
748 Expr *castExpr = static_cast<Expr*>(Op);
749 QualType castType = QualType::getFromOpaquePtr(Ty);
750
Steve Naroff68adb482007-08-31 00:32:44 +0000751 UsualUnaryConversions(castExpr);
752
Chris Lattner4b009652007-07-25 00:24:17 +0000753 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
754 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000755 if (!castType->isVoidType()) { // Cast to void allows any expr type.
Steve Narofff459ee52008-01-24 22:55:05 +0000756 if (!castType->isScalarType() && !castType->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000757 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
758 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Steve Narofff459ee52008-01-24 22:55:05 +0000759 if (!castExpr->getType()->isScalarType() &&
760 !castExpr->getType()->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000761 return Diag(castExpr->getLocStart(),
762 diag::err_typecheck_expect_scalar_operand,
763 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000764
765 if (castExpr->getType()->isVectorType()) {
766 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
767 castExpr->getType(), castType))
768 return true;
769 } else if (castType->isVectorType()) {
770 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
771 castType, castExpr->getType()))
772 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000773 }
Chris Lattner4b009652007-07-25 00:24:17 +0000774 }
775 return new CastExpr(castType, castExpr, LParenLoc);
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 }
Chris Lattner992ae932008-01-06 22:42:25 +0000795
796 // Now check the two expressions.
797
798 // If both operands have arithmetic type, do the usual arithmetic conversions
799 // to find a common type: C99 6.5.15p3,5.
800 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000801 UsualArithmeticConversions(lex, rex);
802 return lex->getType();
803 }
Chris Lattner992ae932008-01-06 22:42:25 +0000804
805 // If both operands are the same structure or union type, the result is that
806 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000807 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +0000808 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +0000809 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +0000810 // "If both the operands have structure or union type, the result has
811 // that type." This implies that CV qualifiers are dropped.
812 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000813 }
Chris Lattner992ae932008-01-06 22:42:25 +0000814
815 // C99 6.5.15p5: "If both operands have void type, the result has void type."
816 if (lexT->isVoidType() && rexT->isVoidType())
817 return lexT.getUnqualifiedType();
Steve Naroff12ebf272008-01-08 01:11:38 +0000818
819 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
820 // the type of the other operand."
821 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000822 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000823 return lexT;
824 }
825 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000826 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000827 return rexT;
828 }
Chris Lattner0ac51632008-01-06 22:50:31 +0000829 // Handle the case where both operands are pointers before we handle null
830 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +0000831 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
832 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
833 // get the "pointed to" types
834 QualType lhptee = LHSPT->getPointeeType();
835 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000836
Chris Lattner71225142007-07-31 21:27:01 +0000837 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
838 if (lhptee->isVoidType() &&
Eli Friedmanca07c902008-02-10 22:59:36 +0000839 (rhptee->isObjectType() || rhptee->isIncompleteType())) {
Chris Lattner35fef522008-02-20 20:55:12 +0000840 // Figure out necessary qualifiers (C99 6.5.15p6)
841 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000842 QualType destType = Context.getPointerType(destPointee);
843 ImpCastExprToType(lex, destType); // add qualifiers if necessary
844 ImpCastExprToType(rex, destType); // promote to void*
845 return destType;
846 }
Chris Lattner71225142007-07-31 21:27:01 +0000847 if (rhptee->isVoidType() &&
Eli Friedmanca07c902008-02-10 22:59:36 +0000848 (lhptee->isObjectType() || lhptee->isIncompleteType())) {
Chris Lattner35fef522008-02-20 20:55:12 +0000849 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000850 QualType destType = Context.getPointerType(destPointee);
851 ImpCastExprToType(lex, destType); // add qualifiers if necessary
852 ImpCastExprToType(rex, destType); // promote to void*
853 return destType;
854 }
Chris Lattner4b009652007-07-25 00:24:17 +0000855
Steve Naroff85f0dc52007-10-15 20:41:53 +0000856 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
857 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +0000858 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +0000859 lexT.getAsString(), rexT.getAsString(),
860 lex->getSourceRange(), rex->getSourceRange());
Eli Friedman33284862008-01-30 17:02:03 +0000861 // In this situation, we assume void* type. No especially good
862 // reason, but this is what gcc does, and we do have to pick
863 // to get a consistent AST.
864 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
865 ImpCastExprToType(lex, voidPtrTy);
866 ImpCastExprToType(rex, voidPtrTy);
867 return voidPtrTy;
Chris Lattner71225142007-07-31 21:27:01 +0000868 }
869 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000870 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
871 // differently qualified versions of compatible types, the result type is
872 // a pointer to an appropriately qualified version of the *composite*
873 // type.
Chris Lattner0ac51632008-01-06 22:50:31 +0000874 // FIXME: Need to return the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +0000875 // FIXME: Need to add qualifiers
Chris Lattner0ac51632008-01-06 22:50:31 +0000876 return lexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000877 }
Chris Lattner4b009652007-07-25 00:24:17 +0000878 }
Chris Lattner71225142007-07-31 21:27:01 +0000879
Chris Lattner992ae932008-01-06 22:42:25 +0000880 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +0000881 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
882 lexT.getAsString(), rexT.getAsString(),
883 lex->getSourceRange(), rex->getSourceRange());
884 return QualType();
885}
886
Steve Naroff87d58b42007-09-16 03:34:24 +0000887/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000888/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000889Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000890 SourceLocation ColonLoc,
891 ExprTy *Cond, ExprTy *LHS,
892 ExprTy *RHS) {
893 Expr *CondExpr = (Expr *) Cond;
894 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000895
896 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
897 // was the condition.
898 bool isLHSNull = LHSExpr == 0;
899 if (isLHSNull)
900 LHSExpr = CondExpr;
901
Chris Lattner4b009652007-07-25 00:24:17 +0000902 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
903 RHSExpr, QuestionLoc);
904 if (result.isNull())
905 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000906 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
907 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000908}
909
Steve Naroffdb65e052007-08-28 23:30:39 +0000910/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Steve Naroffbbaed752008-01-29 02:42:22 +0000911/// do not have a prototype. Arguments that have type float are promoted to
912/// double. All other argument types are converted by UsualUnaryConversions().
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000913void Sema::DefaultArgumentPromotion(Expr *&Expr) {
914 QualType Ty = Expr->getType();
915 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffdb65e052007-08-28 23:30:39 +0000916
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000917 if (Ty == Context.FloatTy)
Chris Lattnere992d6c2008-01-16 19:17:22 +0000918 ImpCastExprToType(Expr, Context.DoubleTy);
Steve Naroffbbaed752008-01-29 02:42:22 +0000919 else
920 UsualUnaryConversions(Expr);
Steve Naroffdb65e052007-08-28 23:30:39 +0000921}
922
Chris Lattner4b009652007-07-25 00:24:17 +0000923/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
924void Sema::DefaultFunctionArrayConversion(Expr *&e) {
925 QualType t = e->getType();
926 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
927
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000928 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000929 ImpCastExprToType(e, ref->getReferenceeType()); // C++ [expr]
Chris Lattner4b009652007-07-25 00:24:17 +0000930 t = e->getType();
931 }
932 if (t->isFunctionType())
Chris Lattnere992d6c2008-01-16 19:17:22 +0000933 ImpCastExprToType(e, Context.getPointerType(t));
Steve Naroffac26e9a2008-02-09 16:59:44 +0000934 else if (const ArrayType *ary = t->getAsArrayType()) {
Steve Naroff9ffeda12008-02-09 17:25:18 +0000935 // Make sure we don't lose qualifiers when dealing with typedefs. Example:
Steve Naroffac26e9a2008-02-09 16:59:44 +0000936 // typedef int arr[10];
937 // void test2() {
938 // const arr b;
939 // b[4] = 1;
940 // }
941 QualType ELT = ary->getElementType();
Chris Lattner35fef522008-02-20 20:55:12 +0000942 // FIXME: Handle ASQualType
943 ELT = ELT.getQualifiedType(t.getCVRQualifiers()|ELT.getCVRQualifiers());
Steve Naroffac26e9a2008-02-09 16:59:44 +0000944 ImpCastExprToType(e, Context.getPointerType(ELT));
945 }
Chris Lattner4b009652007-07-25 00:24:17 +0000946}
947
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000948/// UsualUnaryConversions - Performs various conversions that are common to most
Chris Lattner4b009652007-07-25 00:24:17 +0000949/// operators (C99 6.3). The conversions of array and function types are
950/// sometimes surpressed. For example, the array->pointer conversion doesn't
951/// apply if the array is an argument to the sizeof or address (&) operators.
952/// In these instances, this routine should *not* be called.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000953Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
954 QualType Ty = Expr->getType();
955 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000956
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000957 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000958 ImpCastExprToType(Expr, Ref->getReferenceeType()); // C++ [expr]
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000959 Ty = Expr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000960 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000961 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
Chris Lattnere992d6c2008-01-16 19:17:22 +0000962 ImpCastExprToType(Expr, Context.IntTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000963 else
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000964 DefaultFunctionArrayConversion(Expr);
965
966 return Expr;
Chris Lattner4b009652007-07-25 00:24:17 +0000967}
968
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000969/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000970/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
971/// routine returns the first non-arithmetic type found. The client is
972/// responsible for emitting appropriate error diagnostics.
Steve Naroffe8419ca2008-01-15 22:21:49 +0000973/// FIXME: verify the conversion rules for "complex int" are consistent with GCC.
Steve Naroff8f708362007-08-24 19:07:16 +0000974QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
975 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000976 if (!isCompAssign) {
977 UsualUnaryConversions(lhsExpr);
978 UsualUnaryConversions(rhsExpr);
979 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000980 // For conversion purposes, we ignore any qualifiers.
981 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000982 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
983 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000984
985 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000986 if (lhs == rhs)
987 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000988
989 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
990 // The caller can deal with this (e.g. pointer + int).
991 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000992 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000993
994 // At this point, we have two different arithmetic types.
995
996 // Handle complex types first (C99 6.3.1.8p1).
997 if (lhs->isComplexType() || rhs->isComplexType()) {
Steve Naroff43001212008-01-15 19:36:10 +0000998 // if we have an integer operand, the result is the complex type.
Steve Naroffe8419ca2008-01-15 22:21:49 +0000999 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001000 // convert the rhs to the lhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001001 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001002 return lhs;
Steve Naroff43001212008-01-15 19:36:10 +00001003 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001004 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001005 // convert the lhs to the rhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001006 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001007 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001008 }
Steve Naroff3cf497f2007-08-27 01:27:54 +00001009 // This handles complex/complex, complex/float, or float/complex.
1010 // When both operands are complex, the shorter operand is converted to the
1011 // type of the longer, and that is the type of the result. This corresponds
1012 // to what is done when combining two real floating-point operands.
1013 // The fun begins when size promotion occur across type domains.
1014 // From H&S 6.3.4: When one operand is complex and the other is a real
1015 // floating-point type, the less precise type is converted, within it's
1016 // real or complex domain, to the precision of the other type. For example,
1017 // when combining a "long double" with a "double _Complex", the
1018 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +00001019 int result = Context.compareFloatingType(lhs, rhs);
1020
1021 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +00001022 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
1023 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001024 ImpCastExprToType(rhsExpr, rhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001025 } else if (result < 0) { // The right side is bigger, convert lhs.
1026 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
1027 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001028 ImpCastExprToType(lhsExpr, lhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001029 }
1030 // At this point, lhs and rhs have the same rank/size. Now, make sure the
1031 // domains match. This is a requirement for our implementation, C99
1032 // does not require this promotion.
1033 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1034 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001035 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001036 ImpCastExprToType(lhsExpr, rhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001037 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001038 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001039 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001040 ImpCastExprToType(rhsExpr, lhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001041 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001042 }
Chris Lattner4b009652007-07-25 00:24:17 +00001043 }
Steve Naroff3b6157f2007-08-27 21:43:43 +00001044 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +00001045 }
1046 // Now handle "real" floating types (i.e. float, double, long double).
1047 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1048 // if we have an integer operand, the result is the real floating type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001049 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001050 // convert rhs to the lhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001051 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001052 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001053 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001054 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001055 // convert lhs to the rhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001056 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001057 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001058 }
1059 // We have two real floating types, float/complex combos were handled above.
1060 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +00001061 int result = Context.compareFloatingType(lhs, rhs);
1062
1063 if (result > 0) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001064 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001065 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001066 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001067 if (result < 0) { // convert the lhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001068 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff45fc9822007-08-27 15:30:22 +00001069 return rhs;
1070 }
1071 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001072 }
Steve Naroff43001212008-01-15 19:36:10 +00001073 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
1074 // Handle GCC complex int extension.
Steve Naroff43001212008-01-15 19:36:10 +00001075 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
Eli Friedman50727042008-02-08 01:19:44 +00001076 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
Steve Naroff43001212008-01-15 19:36:10 +00001077
Eli Friedman50727042008-02-08 01:19:44 +00001078 if (lhsComplexInt && rhsComplexInt) {
1079 if (Context.maxIntegerType(lhsComplexInt->getElementType(),
Eli Friedman94075c02008-02-08 01:24:30 +00001080 rhsComplexInt->getElementType()) == lhs) {
1081 // convert the rhs
1082 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1083 return lhs;
Eli Friedman50727042008-02-08 01:19:44 +00001084 }
1085 if (!isCompAssign)
Eli Friedman94075c02008-02-08 01:24:30 +00001086 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Eli Friedman50727042008-02-08 01:19:44 +00001087 return rhs;
1088 } else if (lhsComplexInt && rhs->isIntegerType()) {
1089 // convert the rhs to the lhs complex type.
1090 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1091 return lhs;
1092 } else if (rhsComplexInt && lhs->isIntegerType()) {
1093 // convert the lhs to the rhs complex type.
1094 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1095 return rhs;
1096 }
Steve Naroff43001212008-01-15 19:36:10 +00001097 }
Chris Lattner4b009652007-07-25 00:24:17 +00001098 // Finally, we have two differing integer types.
1099 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001100 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001101 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001102 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001103 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff8f708362007-08-24 19:07:16 +00001104 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001105}
1106
1107// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1108// being closely modeled after the C99 spec:-). The odd characteristic of this
1109// routine is it effectively iqnores the qualifiers on the top level pointee.
1110// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1111// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001112Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001113Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1114 QualType lhptee, rhptee;
1115
1116 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001117 lhptee = lhsType->getAsPointerType()->getPointeeType();
1118 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001119
1120 // make sure we operate on the canonical type
1121 lhptee = lhptee.getCanonicalType();
1122 rhptee = rhptee.getCanonicalType();
1123
Chris Lattner005ed752008-01-04 18:04:52 +00001124 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001125
1126 // C99 6.5.16.1p1: This following citation is common to constraints
1127 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1128 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001129 // FIXME: Handle ASQualType
1130 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1131 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001132 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001133
1134 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1135 // incomplete type and the other is a pointer to a qualified or unqualified
1136 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001137 if (lhptee->isVoidType()) {
1138 if (rhptee->isObjectType() || rhptee->isIncompleteType())
Chris Lattner005ed752008-01-04 18:04:52 +00001139 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001140
1141 // As an extension, we allow cast to/from void* to function pointer.
1142 if (rhptee->isFunctionType())
1143 return FunctionVoidPointer;
1144 }
1145
1146 if (rhptee->isVoidType()) {
1147 if (lhptee->isObjectType() || lhptee->isIncompleteType())
Chris Lattner005ed752008-01-04 18:04:52 +00001148 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001149
1150 // As an extension, we allow cast to/from void* to function pointer.
1151 if (lhptee->isFunctionType())
1152 return FunctionVoidPointer;
1153 }
1154
Chris Lattner4b009652007-07-25 00:24:17 +00001155 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1156 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001157 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1158 rhptee.getUnqualifiedType()))
1159 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001160 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001161}
1162
1163/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1164/// has code to accommodate several GCC extensions when type checking
1165/// pointers. Here are some objectionable examples that GCC considers warnings:
1166///
1167/// int a, *pint;
1168/// short *pshort;
1169/// struct foo *pfoo;
1170///
1171/// pint = pshort; // warning: assignment from incompatible pointer type
1172/// a = pint; // warning: assignment makes integer from pointer without a cast
1173/// pint = a; // warning: assignment makes pointer from integer without a cast
1174/// pint = pfoo; // warning: assignment from incompatible pointer type
1175///
1176/// As a result, the code for dealing with pointers is more complex than the
1177/// C99 spec dictates.
1178/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1179///
Chris Lattner005ed752008-01-04 18:04:52 +00001180Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001181Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001182 // Get canonical types. We're not formatting these types, just comparing
1183 // them.
1184 lhsType = lhsType.getCanonicalType();
1185 rhsType = rhsType.getCanonicalType();
1186
1187 if (lhsType.getUnqualifiedType() == rhsType.getUnqualifiedType())
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001188 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001189
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001190 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001191 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001192 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001193 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001194 }
Chris Lattner1853da22008-01-04 23:18:45 +00001195
Ted Kremenek42730c52008-01-07 19:49:32 +00001196 if (lhsType->isObjCQualifiedIdType()
1197 || rhsType->isObjCQualifiedIdType()) {
1198 if (Context.ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001199 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001200 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001201 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001202
1203 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1204 // For OCUVector, allow vector splats; float -> <n x float>
1205 if (const OCUVectorType *LV = lhsType->getAsOCUVectorType()) {
1206 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1207 return Compatible;
1208 }
1209
1210 // If LHS and RHS are both vectors of integer or both vectors of floating
1211 // point types, and the total vector length is the same, allow the
1212 // conversion. This is a bitcast; no bits are changed but the result type
1213 // is different.
1214 if (getLangOptions().LaxVectorConversions &&
1215 lhsType->isVectorType() && rhsType->isVectorType()) {
1216 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1217 (lhsType->isRealFloatingType() && rhsType->isRealFloatingType())) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001218 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Nate Begemanec2d1062007-12-30 02:59:45 +00001219 return Compatible;
1220 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001221 }
1222 return Incompatible;
1223 }
1224
1225 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001226 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001227
1228 if (lhsType->isPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001229 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001230 return IntToPointer;
Chris Lattner4b009652007-07-25 00:24:17 +00001231
1232 if (rhsType->isPointerType())
1233 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001234 return Incompatible;
1235 }
1236
1237 if (rhsType->isPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001238 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1239 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001240 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001241
1242 if (lhsType->isPointerType())
1243 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001244 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001245 }
1246
1247 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001248 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001249 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001250 }
1251 return Incompatible;
1252}
1253
Chris Lattner005ed752008-01-04 18:04:52 +00001254Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001255Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001256 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1257 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001258 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001259 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001260 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001261 return Compatible;
1262 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001263 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001264 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001265 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001266 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001267 //
1268 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1269 // are better understood.
1270 if (!lhsType->isReferenceType())
1271 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001272
Chris Lattner005ed752008-01-04 18:04:52 +00001273 Sema::AssignConvertType result =
1274 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001275
1276 // C99 6.5.16.1p2: The value of the right operand is converted to the
1277 // type of the assignment expression.
1278 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001279 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001280 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001281}
1282
Chris Lattner005ed752008-01-04 18:04:52 +00001283Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001284Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1285 return CheckAssignmentConstraints(lhsType, rhsType);
1286}
1287
Chris Lattner2c8bff72007-12-12 05:47:28 +00001288QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001289 Diag(loc, diag::err_typecheck_invalid_operands,
1290 lex->getType().getAsString(), rex->getType().getAsString(),
1291 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001292 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001293}
1294
1295inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1296 Expr *&rex) {
1297 QualType lhsType = lex->getType(), rhsType = rex->getType();
1298
1299 // make sure the vector types are identical.
Nate Begeman78a2a312008-03-17 17:22:18 +00001300 if (lhsType.getCanonicalType() == rhsType.getCanonicalType())
Chris Lattner4b009652007-07-25 00:24:17 +00001301 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001302
1303 // if the lhs is an ocu vector and the rhs is a scalar of the same type,
1304 // promote the rhs to the vector type.
1305 if (const OCUVectorType *V = lhsType->getAsOCUVectorType()) {
1306 if (V->getElementType().getCanonicalType().getTypePtr()
1307 == rhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001308 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001309 return lhsType;
1310 }
1311 }
1312
1313 // if the rhs is an ocu vector and the lhs is a scalar of the same type,
1314 // promote the lhs to the vector type.
1315 if (const OCUVectorType *V = rhsType->getAsOCUVectorType()) {
1316 if (V->getElementType().getCanonicalType().getTypePtr()
1317 == lhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001318 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001319 return rhsType;
1320 }
1321 }
1322
Chris Lattner4b009652007-07-25 00:24:17 +00001323 // You cannot convert between vector values of different size.
1324 Diag(loc, diag::err_typecheck_vector_not_convertable,
1325 lex->getType().getAsString(), rex->getType().getAsString(),
1326 lex->getSourceRange(), rex->getSourceRange());
1327 return QualType();
1328}
1329
1330inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001331 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001332{
1333 QualType lhsType = lex->getType(), rhsType = rex->getType();
1334
1335 if (lhsType->isVectorType() || rhsType->isVectorType())
1336 return CheckVectorOperands(loc, lex, rex);
1337
Steve Naroff8f708362007-08-24 19:07:16 +00001338 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001339
Chris Lattner4b009652007-07-25 00:24:17 +00001340 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001341 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001342 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001343}
1344
1345inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001346 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001347{
1348 QualType lhsType = lex->getType(), rhsType = rex->getType();
1349
Steve Naroff8f708362007-08-24 19:07:16 +00001350 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001351
Chris Lattner4b009652007-07-25 00:24:17 +00001352 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001353 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001354 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001355}
1356
1357inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001358 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001359{
1360 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1361 return CheckVectorOperands(loc, lex, rex);
1362
Steve Naroff8f708362007-08-24 19:07:16 +00001363 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001364
1365 // handle the common case first (both operands are arithmetic).
1366 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001367 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001368
1369 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1370 return lex->getType();
1371 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1372 return rex->getType();
Chris Lattner2c8bff72007-12-12 05:47:28 +00001373 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001374}
1375
1376inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001377 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001378{
1379 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1380 return CheckVectorOperands(loc, lex, rex);
1381
Steve Naroff8f708362007-08-24 19:07:16 +00001382 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001383
Chris Lattnerf6da2912007-12-09 21:53:25 +00001384 // Enforce type constraints: C99 6.5.6p3.
1385
1386 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001387 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001388 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001389
1390 // Either ptr - int or ptr - ptr.
1391 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001392 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001393
Chris Lattnerf6da2912007-12-09 21:53:25 +00001394 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001395 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001396 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001397 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001398 Diag(loc, diag::ext_gnu_void_ptr,
1399 lex->getSourceRange(), rex->getSourceRange());
1400 } else {
1401 Diag(loc, diag::err_typecheck_sub_ptr_object,
1402 lex->getType().getAsString(), lex->getSourceRange());
1403 return QualType();
1404 }
1405 }
1406
1407 // The result type of a pointer-int computation is the pointer type.
1408 if (rex->getType()->isIntegerType())
1409 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001410
Chris Lattnerf6da2912007-12-09 21:53:25 +00001411 // Handle pointer-pointer subtractions.
1412 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001413 QualType rpointee = RHSPTy->getPointeeType();
1414
Chris Lattnerf6da2912007-12-09 21:53:25 +00001415 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001416 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001417 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001418 if (rpointee->isVoidType()) {
1419 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001420 Diag(loc, diag::ext_gnu_void_ptr,
1421 lex->getSourceRange(), rex->getSourceRange());
1422 } else {
1423 Diag(loc, diag::err_typecheck_sub_ptr_object,
1424 rex->getType().getAsString(), rex->getSourceRange());
1425 return QualType();
1426 }
1427 }
1428
1429 // Pointee types must be compatible.
Steve Naroff577f9722008-01-29 18:58:14 +00001430 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1431 rpointee.getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001432 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1433 lex->getType().getAsString(), rex->getType().getAsString(),
1434 lex->getSourceRange(), rex->getSourceRange());
1435 return QualType();
1436 }
1437
1438 return Context.getPointerDiffType();
1439 }
1440 }
1441
Chris Lattner2c8bff72007-12-12 05:47:28 +00001442 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001443}
1444
1445inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Chris Lattner2c8bff72007-12-12 05:47:28 +00001446 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1447 // C99 6.5.7p2: Each of the operands shall have integer type.
1448 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1449 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001450
Chris Lattner2c8bff72007-12-12 05:47:28 +00001451 // Shifts don't perform usual arithmetic conversions, they just do integer
1452 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001453 if (!isCompAssign)
1454 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001455 UsualUnaryConversions(rex);
1456
1457 // "The type of the result is that of the promoted left operand."
1458 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001459}
1460
Chris Lattner254f3bc2007-08-26 01:18:55 +00001461inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1462 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001463{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001464 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001465 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1466 UsualArithmeticConversions(lex, rex);
1467 else {
1468 UsualUnaryConversions(lex);
1469 UsualUnaryConversions(rex);
1470 }
Chris Lattner4b009652007-07-25 00:24:17 +00001471 QualType lType = lex->getType();
1472 QualType rType = rex->getType();
1473
Ted Kremenek486509e2007-10-29 17:13:39 +00001474 // For non-floating point types, check for self-comparisons of the form
1475 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1476 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001477 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001478 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1479 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001480 if (DRL->getDecl() == DRR->getDecl())
1481 Diag(loc, diag::warn_selfcomparison);
1482 }
1483
Chris Lattner254f3bc2007-08-26 01:18:55 +00001484 if (isRelational) {
1485 if (lType->isRealType() && rType->isRealType())
1486 return Context.IntTy;
1487 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001488 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001489 if (lType->isFloatingType()) {
1490 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001491 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001492 }
1493
Chris Lattner254f3bc2007-08-26 01:18:55 +00001494 if (lType->isArithmeticType() && rType->isArithmeticType())
1495 return Context.IntTy;
1496 }
Chris Lattner4b009652007-07-25 00:24:17 +00001497
Chris Lattner22be8422007-08-26 01:10:14 +00001498 bool LHSIsNull = lex->isNullPointerConstant(Context);
1499 bool RHSIsNull = rex->isNullPointerConstant(Context);
1500
Chris Lattner254f3bc2007-08-26 01:18:55 +00001501 // All of the following pointer related warnings are GCC extensions, except
1502 // when handling null pointer constants. One day, we can consider making them
1503 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001504 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Eli Friedman50727042008-02-08 01:19:44 +00001505 QualType lpointee = lType->getAsPointerType()->getPointeeType();
1506 QualType rpointee = rType->getAsPointerType()->getPointeeType();
1507
Steve Naroff3b435622007-11-13 14:57:38 +00001508 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Steve Naroff577f9722008-01-29 18:58:14 +00001509 !lpointee->isVoidType() && !lpointee->isVoidType() &&
1510 !Context.typesAreCompatible(lpointee.getUnqualifiedType(),
Eli Friedman50727042008-02-08 01:19:44 +00001511 rpointee.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001512 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1513 lType.getAsString(), rType.getAsString(),
1514 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001515 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001516 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001517 return Context.IntTy;
1518 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001519 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())
1520 && Context.ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001521 ImpCastExprToType(rex, lType);
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001522 return Context.IntTy;
1523 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001524 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001525 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001526 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1527 lType.getAsString(), rType.getAsString(),
1528 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001529 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001530 return Context.IntTy;
1531 }
1532 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001533 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001534 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1535 lType.getAsString(), rType.getAsString(),
1536 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001537 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001538 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001539 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001540 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001541}
1542
Chris Lattner4b009652007-07-25 00:24:17 +00001543inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001544 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001545{
1546 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1547 return CheckVectorOperands(loc, lex, rex);
1548
Steve Naroff8f708362007-08-24 19:07:16 +00001549 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001550
1551 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001552 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001553 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001554}
1555
1556inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1557 Expr *&lex, Expr *&rex, SourceLocation loc)
1558{
1559 UsualUnaryConversions(lex);
1560 UsualUnaryConversions(rex);
1561
1562 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1563 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001564 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001565}
1566
1567inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001568 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001569{
1570 QualType lhsType = lex->getType();
1571 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner4b009652007-07-25 00:24:17 +00001572 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1573
1574 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001575 case Expr::MLV_Valid:
1576 break;
1577 case Expr::MLV_ConstQualified:
1578 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1579 return QualType();
1580 case Expr::MLV_ArrayType:
1581 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1582 lhsType.getAsString(), lex->getSourceRange());
1583 return QualType();
1584 case Expr::MLV_NotObjectType:
1585 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1586 lhsType.getAsString(), lex->getSourceRange());
1587 return QualType();
1588 case Expr::MLV_InvalidExpression:
1589 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1590 lex->getSourceRange());
1591 return QualType();
1592 case Expr::MLV_IncompleteType:
1593 case Expr::MLV_IncompleteVoidType:
1594 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1595 lhsType.getAsString(), lex->getSourceRange());
1596 return QualType();
1597 case Expr::MLV_DuplicateVectorComponents:
1598 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1599 lex->getSourceRange());
1600 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001601 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001602
Chris Lattner005ed752008-01-04 18:04:52 +00001603 AssignConvertType ConvTy;
1604 if (compoundType.isNull())
1605 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1606 else
1607 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1608
1609 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1610 rex, "assigning"))
1611 return QualType();
1612
Chris Lattner4b009652007-07-25 00:24:17 +00001613 // C99 6.5.16p3: The type of an assignment expression is the type of the
1614 // left operand unless the left operand has qualified type, in which case
1615 // it is the unqualified version of the type of the left operand.
1616 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1617 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001618 // C++ 5.17p1: the type of the assignment expression is that of its left
1619 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001620 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001621}
1622
1623inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1624 Expr *&lex, Expr *&rex, SourceLocation loc) {
1625 UsualUnaryConversions(rex);
1626 return rex->getType();
1627}
1628
1629/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1630/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1631QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1632 QualType resType = op->getType();
1633 assert(!resType.isNull() && "no type for increment/decrement expression");
1634
Steve Naroffd30e1932007-08-24 17:20:07 +00001635 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001636 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001637 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1638 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1639 resType.getAsString(), op->getSourceRange());
1640 return QualType();
1641 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001642 } else if (!resType->isRealType()) {
1643 if (resType->isComplexType())
1644 // C99 does not support ++/-- on complex types.
1645 Diag(OpLoc, diag::ext_integer_increment_complex,
1646 resType.getAsString(), op->getSourceRange());
1647 else {
1648 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1649 resType.getAsString(), op->getSourceRange());
1650 return QualType();
1651 }
Chris Lattner4b009652007-07-25 00:24:17 +00001652 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001653 // At this point, we know we have a real, complex or pointer type.
1654 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001655 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1656 if (mlval != Expr::MLV_Valid) {
1657 // FIXME: emit a more precise diagnostic...
1658 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1659 op->getSourceRange());
1660 return QualType();
1661 }
1662 return resType;
1663}
1664
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001665/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00001666/// This routine allows us to typecheck complex/recursive expressions
1667/// where the declaration is needed for type checking. Here are some
1668/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001669static ValueDecl *getPrimaryDecl(Expr *e) {
Chris Lattner4b009652007-07-25 00:24:17 +00001670 switch (e->getStmtClass()) {
1671 case Stmt::DeclRefExprClass:
1672 return cast<DeclRefExpr>(e)->getDecl();
1673 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001674 // Fields cannot be declared with a 'register' storage class.
1675 // &X->f is always ok, even if X is declared register.
1676 if (cast<MemberExpr>(e)->isArrow())
1677 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001678 return getPrimaryDecl(cast<MemberExpr>(e)->getBase());
1679 case Stmt::ArraySubscriptExprClass: {
1680 // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer.
1681
1682 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(e)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00001683 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001684 return 0;
1685 else
1686 return VD;
1687 }
Chris Lattner4b009652007-07-25 00:24:17 +00001688 case Stmt::UnaryOperatorClass:
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001689 return getPrimaryDecl(cast<UnaryOperator>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001690 case Stmt::ParenExprClass:
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001691 return getPrimaryDecl(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001692 case Stmt::ImplicitCastExprClass:
1693 // &X[4] when X is an array, has an implicit cast from array to pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001694 return getPrimaryDecl(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001695 default:
1696 return 0;
1697 }
1698}
1699
1700/// CheckAddressOfOperand - The operand of & must be either a function
1701/// designator or an lvalue designating an object. If it is an lvalue, the
1702/// object cannot be declared with storage class register or be a bit field.
1703/// Note: The usual conversions are *not* applied to the operand of the &
1704/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1705QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001706 if (getLangOptions().C99) {
1707 // Implement C99-only parts of addressof rules.
1708 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
1709 if (uOp->getOpcode() == UnaryOperator::Deref)
1710 // Per C99 6.5.3.2, the address of a deref always returns a valid result
1711 // (assuming the deref expression is valid).
1712 return uOp->getSubExpr()->getType();
1713 }
1714 // Technically, there should be a check for array subscript
1715 // expressions here, but the result of one is always an lvalue anyway.
1716 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001717 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner4b009652007-07-25 00:24:17 +00001718 Expr::isLvalueResult lval = op->isLvalue();
1719
1720 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001721 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1722 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001723 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1724 op->getSourceRange());
1725 return QualType();
1726 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00001727 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
1728 if (MemExpr->getMemberDecl()->isBitField()) {
1729 Diag(OpLoc, diag::err_typecheck_address_of,
1730 std::string("bit-field"), op->getSourceRange());
1731 return QualType();
1732 }
1733 // Check for Apple extension for accessing vector components.
1734 } else if (isa<ArraySubscriptExpr>(op) &&
1735 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
1736 Diag(OpLoc, diag::err_typecheck_address_of,
1737 std::string("vector"), op->getSourceRange());
1738 return QualType();
1739 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00001740 // We have an lvalue with a decl. Make sure the decl is not declared
1741 // with the register storage-class specifier.
1742 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1743 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00001744 Diag(OpLoc, diag::err_typecheck_address_of,
1745 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001746 return QualType();
1747 }
1748 } else
1749 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00001750 }
1751 // If the operand has type "type", the result has type "pointer to type".
1752 return Context.getPointerType(op->getType());
1753}
1754
1755QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1756 UsualUnaryConversions(op);
1757 QualType qType = op->getType();
1758
Chris Lattner7931f4a2007-07-31 16:53:04 +00001759 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001760 // Note that per both C89 and C99, this is always legal, even
1761 // if ptype is an incomplete type or void.
1762 // It would be possible to warn about dereferencing a
1763 // void pointer, but it's completely well-defined,
1764 // and such a warning is unlikely to catch any mistakes.
1765 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001766 }
1767 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1768 qType.getAsString(), op->getSourceRange());
1769 return QualType();
1770}
1771
1772static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1773 tok::TokenKind Kind) {
1774 BinaryOperator::Opcode Opc;
1775 switch (Kind) {
1776 default: assert(0 && "Unknown binop!");
1777 case tok::star: Opc = BinaryOperator::Mul; break;
1778 case tok::slash: Opc = BinaryOperator::Div; break;
1779 case tok::percent: Opc = BinaryOperator::Rem; break;
1780 case tok::plus: Opc = BinaryOperator::Add; break;
1781 case tok::minus: Opc = BinaryOperator::Sub; break;
1782 case tok::lessless: Opc = BinaryOperator::Shl; break;
1783 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1784 case tok::lessequal: Opc = BinaryOperator::LE; break;
1785 case tok::less: Opc = BinaryOperator::LT; break;
1786 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1787 case tok::greater: Opc = BinaryOperator::GT; break;
1788 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1789 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1790 case tok::amp: Opc = BinaryOperator::And; break;
1791 case tok::caret: Opc = BinaryOperator::Xor; break;
1792 case tok::pipe: Opc = BinaryOperator::Or; break;
1793 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1794 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1795 case tok::equal: Opc = BinaryOperator::Assign; break;
1796 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1797 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1798 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1799 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1800 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1801 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1802 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1803 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1804 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1805 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1806 case tok::comma: Opc = BinaryOperator::Comma; break;
1807 }
1808 return Opc;
1809}
1810
1811static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1812 tok::TokenKind Kind) {
1813 UnaryOperator::Opcode Opc;
1814 switch (Kind) {
1815 default: assert(0 && "Unknown unary op!");
1816 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1817 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1818 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1819 case tok::star: Opc = UnaryOperator::Deref; break;
1820 case tok::plus: Opc = UnaryOperator::Plus; break;
1821 case tok::minus: Opc = UnaryOperator::Minus; break;
1822 case tok::tilde: Opc = UnaryOperator::Not; break;
1823 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1824 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1825 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1826 case tok::kw___real: Opc = UnaryOperator::Real; break;
1827 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1828 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1829 }
1830 return Opc;
1831}
1832
1833// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001834Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001835 ExprTy *LHS, ExprTy *RHS) {
1836 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1837 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1838
Steve Naroff87d58b42007-09-16 03:34:24 +00001839 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1840 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001841
1842 QualType ResultTy; // Result type of the binary operator.
1843 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1844
1845 switch (Opc) {
1846 default:
1847 assert(0 && "Unknown binary expr!");
1848 case BinaryOperator::Assign:
1849 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1850 break;
1851 case BinaryOperator::Mul:
1852 case BinaryOperator::Div:
1853 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1854 break;
1855 case BinaryOperator::Rem:
1856 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1857 break;
1858 case BinaryOperator::Add:
1859 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1860 break;
1861 case BinaryOperator::Sub:
1862 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1863 break;
1864 case BinaryOperator::Shl:
1865 case BinaryOperator::Shr:
1866 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1867 break;
1868 case BinaryOperator::LE:
1869 case BinaryOperator::LT:
1870 case BinaryOperator::GE:
1871 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001872 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001873 break;
1874 case BinaryOperator::EQ:
1875 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001876 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001877 break;
1878 case BinaryOperator::And:
1879 case BinaryOperator::Xor:
1880 case BinaryOperator::Or:
1881 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1882 break;
1883 case BinaryOperator::LAnd:
1884 case BinaryOperator::LOr:
1885 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1886 break;
1887 case BinaryOperator::MulAssign:
1888 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001889 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001890 if (!CompTy.isNull())
1891 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1892 break;
1893 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001894 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001895 if (!CompTy.isNull())
1896 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1897 break;
1898 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001899 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001900 if (!CompTy.isNull())
1901 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1902 break;
1903 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001904 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001905 if (!CompTy.isNull())
1906 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1907 break;
1908 case BinaryOperator::ShlAssign:
1909 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001910 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001911 if (!CompTy.isNull())
1912 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1913 break;
1914 case BinaryOperator::AndAssign:
1915 case BinaryOperator::XorAssign:
1916 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001917 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001918 if (!CompTy.isNull())
1919 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1920 break;
1921 case BinaryOperator::Comma:
1922 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1923 break;
1924 }
1925 if (ResultTy.isNull())
1926 return true;
1927 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001928 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001929 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001930 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001931}
1932
1933// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001934Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001935 ExprTy *input) {
1936 Expr *Input = (Expr*)input;
1937 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1938 QualType resultType;
1939 switch (Opc) {
1940 default:
1941 assert(0 && "Unimplemented unary expr!");
1942 case UnaryOperator::PreInc:
1943 case UnaryOperator::PreDec:
1944 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1945 break;
1946 case UnaryOperator::AddrOf:
1947 resultType = CheckAddressOfOperand(Input, OpLoc);
1948 break;
1949 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00001950 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00001951 resultType = CheckIndirectionOperand(Input, OpLoc);
1952 break;
1953 case UnaryOperator::Plus:
1954 case UnaryOperator::Minus:
1955 UsualUnaryConversions(Input);
1956 resultType = Input->getType();
1957 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1958 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1959 resultType.getAsString());
1960 break;
1961 case UnaryOperator::Not: // bitwise complement
1962 UsualUnaryConversions(Input);
1963 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001964 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1965 if (!resultType->isIntegerType()) {
1966 if (resultType->isComplexType())
1967 // C99 does not support '~' for complex conjugation.
1968 Diag(OpLoc, diag::ext_integer_complement_complex,
1969 resultType.getAsString());
1970 else
1971 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1972 resultType.getAsString());
1973 }
Chris Lattner4b009652007-07-25 00:24:17 +00001974 break;
1975 case UnaryOperator::LNot: // logical negation
1976 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1977 DefaultFunctionArrayConversion(Input);
1978 resultType = Input->getType();
1979 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1980 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1981 resultType.getAsString());
1982 // LNot always has type int. C99 6.5.3.3p5.
1983 resultType = Context.IntTy;
1984 break;
1985 case UnaryOperator::SizeOf:
1986 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1987 break;
1988 case UnaryOperator::AlignOf:
1989 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1990 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001991 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001992 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001993 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001994 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001995 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001996 resultType = Input->getType();
1997 break;
1998 }
1999 if (resultType.isNull())
2000 return true;
2001 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2002}
2003
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002004/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2005Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002006 SourceLocation LabLoc,
2007 IdentifierInfo *LabelII) {
2008 // Look up the record for this label identifier.
2009 LabelStmt *&LabelDecl = LabelMap[LabelII];
2010
2011 // If we haven't seen this label yet, create a forward reference.
2012 if (LabelDecl == 0)
2013 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2014
2015 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002016 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2017 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002018}
2019
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002020Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002021 SourceLocation RPLoc) { // "({..})"
2022 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2023 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2024 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2025
2026 // FIXME: there are a variety of strange constraints to enforce here, for
2027 // example, it is not possible to goto into a stmt expression apparently.
2028 // More semantic analysis is needed.
2029
2030 // FIXME: the last statement in the compount stmt has its value used. We
2031 // should not warn about it being unused.
2032
2033 // If there are sub stmts in the compound stmt, take the type of the last one
2034 // as the type of the stmtexpr.
2035 QualType Ty = Context.VoidTy;
2036
2037 if (!Compound->body_empty())
2038 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
2039 Ty = LastExpr->getType();
2040
2041 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2042}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002043
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002044Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002045 SourceLocation TypeLoc,
2046 TypeTy *argty,
2047 OffsetOfComponent *CompPtr,
2048 unsigned NumComponents,
2049 SourceLocation RPLoc) {
2050 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2051 assert(!ArgTy.isNull() && "Missing type argument!");
2052
2053 // We must have at least one component that refers to the type, and the first
2054 // one is known to be a field designator. Verify that the ArgTy represents
2055 // a struct/union/class.
2056 if (!ArgTy->isRecordType())
2057 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2058
2059 // Otherwise, create a compound literal expression as the base, and
2060 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002061 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002062
Chris Lattnerb37522e2007-08-31 21:49:13 +00002063 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2064 // GCC extension, diagnose them.
2065 if (NumComponents != 1)
2066 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2067 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2068
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002069 for (unsigned i = 0; i != NumComponents; ++i) {
2070 const OffsetOfComponent &OC = CompPtr[i];
2071 if (OC.isBrackets) {
2072 // Offset of an array sub-field. TODO: Should we allow vector elements?
2073 const ArrayType *AT = Res->getType()->getAsArrayType();
2074 if (!AT) {
2075 delete Res;
2076 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2077 Res->getType().getAsString());
2078 }
2079
Chris Lattner2af6a802007-08-30 17:59:59 +00002080 // FIXME: C++: Verify that operator[] isn't overloaded.
2081
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002082 // C99 6.5.2.1p1
2083 Expr *Idx = static_cast<Expr*>(OC.U.E);
2084 if (!Idx->getType()->isIntegerType())
2085 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2086 Idx->getSourceRange());
2087
2088 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2089 continue;
2090 }
2091
2092 const RecordType *RC = Res->getType()->getAsRecordType();
2093 if (!RC) {
2094 delete Res;
2095 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2096 Res->getType().getAsString());
2097 }
2098
2099 // Get the decl corresponding to this.
2100 RecordDecl *RD = RC->getDecl();
2101 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2102 if (!MemberDecl)
2103 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2104 OC.U.IdentInfo->getName(),
2105 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002106
2107 // FIXME: C++: Verify that MemberDecl isn't a static field.
2108 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002109 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2110 // matter here.
2111 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002112 }
2113
2114 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2115 BuiltinLoc);
2116}
2117
2118
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002119Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002120 TypeTy *arg1, TypeTy *arg2,
2121 SourceLocation RPLoc) {
2122 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2123 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2124
2125 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2126
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002127 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002128}
2129
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002130Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002131 ExprTy *expr1, ExprTy *expr2,
2132 SourceLocation RPLoc) {
2133 Expr *CondExpr = static_cast<Expr*>(cond);
2134 Expr *LHSExpr = static_cast<Expr*>(expr1);
2135 Expr *RHSExpr = static_cast<Expr*>(expr2);
2136
2137 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2138
2139 // The conditional expression is required to be a constant expression.
2140 llvm::APSInt condEval(32);
2141 SourceLocation ExpLoc;
2142 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2143 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2144 CondExpr->getSourceRange());
2145
2146 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2147 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2148 RHSExpr->getType();
2149 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2150}
2151
Nate Begemanbd881ef2008-01-30 20:50:20 +00002152/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002153/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002154/// The number of arguments has already been validated to match the number of
2155/// arguments in FnType.
2156static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002157 unsigned NumParams = FnType->getNumArgs();
2158 for (unsigned i = 0; i != NumParams; ++i)
Nate Begemanbd881ef2008-01-30 20:50:20 +00002159 if (Args[i]->getType().getCanonicalType() !=
2160 FnType->getArgType(i).getCanonicalType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002161 return false;
2162 return true;
2163}
2164
2165Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2166 SourceLocation *CommaLocs,
2167 SourceLocation BuiltinLoc,
2168 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002169 // __builtin_overload requires at least 2 arguments
2170 if (NumArgs < 2)
2171 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2172 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002173
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002174 // The first argument is required to be a constant expression. It tells us
2175 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002176 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002177 Expr *NParamsExpr = Args[0];
2178 llvm::APSInt constEval(32);
2179 SourceLocation ExpLoc;
2180 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2181 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2182 NParamsExpr->getSourceRange());
2183
2184 // Verify that the number of parameters is > 0
2185 unsigned NumParams = constEval.getZExtValue();
2186 if (NumParams == 0)
2187 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2188 NParamsExpr->getSourceRange());
2189 // Verify that we have at least 1 + NumParams arguments to the builtin.
2190 if ((NumParams + 1) > NumArgs)
2191 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2192 SourceRange(BuiltinLoc, RParenLoc));
2193
2194 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002195 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002196 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002197 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2198 // UsualUnaryConversions will convert the function DeclRefExpr into a
2199 // pointer to function.
2200 Expr *Fn = UsualUnaryConversions(Args[i]);
2201 FunctionTypeProto *FnType = 0;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002202 if (const PointerType *PT = Fn->getType()->getAsPointerType()) {
2203 QualType PointeeType = PT->getPointeeType().getCanonicalType();
2204 FnType = dyn_cast<FunctionTypeProto>(PointeeType);
2205 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002206
2207 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2208 // parameters, and the number of parameters must match the value passed to
2209 // the builtin.
2210 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002211 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2212 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002213
2214 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002215 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002216 // If they match, return a new OverloadExpr.
Nate Begemanc6078c92008-01-31 05:38:29 +00002217 if (ExprsMatchFnType(Args+1, FnType)) {
2218 if (OE)
2219 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2220 OE->getFn()->getSourceRange());
2221 // Remember our match, and continue processing the remaining arguments
2222 // to catch any errors.
2223 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2224 BuiltinLoc, RParenLoc);
2225 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002226 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002227 // Return the newly created OverloadExpr node, if we succeded in matching
2228 // exactly one of the candidate functions.
2229 if (OE)
2230 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002231
2232 // If we didn't find a matching function Expr in the __builtin_overload list
2233 // the return an error.
2234 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002235 for (unsigned i = 0; i != NumParams; ++i) {
2236 if (i != 0) typeNames += ", ";
2237 typeNames += Args[i+1]->getType().getAsString();
2238 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002239
2240 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2241 SourceRange(BuiltinLoc, RParenLoc));
2242}
2243
Anders Carlsson36760332007-10-15 20:28:48 +00002244Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2245 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002246 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002247 Expr *E = static_cast<Expr*>(expr);
2248 QualType T = QualType::getFromOpaquePtr(type);
2249
2250 InitBuiltinVaListType();
2251
Chris Lattner005ed752008-01-04 18:04:52 +00002252 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2253 != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002254 return Diag(E->getLocStart(),
2255 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2256 E->getType().getAsString(),
2257 E->getSourceRange());
2258
2259 // FIXME: Warn if a non-POD type is passed in.
2260
2261 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2262}
2263
Chris Lattner005ed752008-01-04 18:04:52 +00002264bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2265 SourceLocation Loc,
2266 QualType DstType, QualType SrcType,
2267 Expr *SrcExpr, const char *Flavor) {
2268 // Decode the result (notice that AST's are still created for extensions).
2269 bool isInvalid = false;
2270 unsigned DiagKind;
2271 switch (ConvTy) {
2272 default: assert(0 && "Unknown conversion type");
2273 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002274 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002275 DiagKind = diag::ext_typecheck_convert_pointer_int;
2276 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002277 case IntToPointer:
2278 DiagKind = diag::ext_typecheck_convert_int_pointer;
2279 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002280 case IncompatiblePointer:
2281 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2282 break;
2283 case FunctionVoidPointer:
2284 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2285 break;
2286 case CompatiblePointerDiscardsQualifiers:
2287 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2288 break;
2289 case Incompatible:
2290 DiagKind = diag::err_typecheck_convert_incompatible;
2291 isInvalid = true;
2292 break;
2293 }
2294
2295 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2296 SrcExpr->getSourceRange());
2297 return isInvalid;
2298}
2299