blob: 5b5b2d235ce5fa74fd52f8683ee7a52e332e538d [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
73/// identifier is used in an 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) {
77 // Could be enum-constant or decl.
Steve Narofff0c31dd2007-09-16 16:16:00 +000078 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Chris Lattner4b009652007-07-25 00:24:17 +000079 if (D == 0) {
80 // Otherwise, this could be an implicitly declared function reference (legal
81 // in C90, extension in C99).
82 if (HasTrailingLParen &&
83 // Not in C++.
84 !getLangOptions().CPlusPlus)
85 D = ImplicitlyDefineFunction(Loc, II, S);
86 else {
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000087 if (CurMethodDecl) {
Ted Kremenek42730c52008-01-07 19:49:32 +000088 ObjCInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
89 ObjCInterfaceDecl *clsDeclared;
90 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
Steve Naroff6b759ce2007-11-15 02:58:25 +000091 IdentifierInfo &II = Context.Idents.get("self");
92 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
93 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
94 static_cast<Expr*>(SelfExpr.Val), true, true);
95 }
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000096 }
Chris Lattner4b009652007-07-25 00:24:17 +000097 // If this name wasn't predeclared and if this is not a function call,
98 // diagnose the problem.
99 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
100 }
101 }
Steve Naroff91b03f72007-08-28 03:03:08 +0000102 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneree4c3bf2008-02-29 16:48:43 +0000103 // check if referencing an identifier with __attribute__((deprecated)).
104 if (VD->getAttr<DeprecatedAttr>())
105 Diag(Loc, diag::warn_deprecated, VD->getName());
106
Steve Naroffcae537d2007-08-28 18:45:29 +0000107 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000108 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000109 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000110 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000111 }
Chris Lattner4b009652007-07-25 00:24:17 +0000112 if (isa<TypedefDecl>(D))
113 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000114 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000115 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000116
117 assert(0 && "Invalid decl");
118 abort();
119}
120
Steve Naroff87d58b42007-09-16 03:34:24 +0000121Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000122 tok::TokenKind Kind) {
123 PreDefinedExpr::IdentType IT;
124
125 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000126 default: assert(0 && "Unknown simple primary expr!");
127 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
128 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
129 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000130 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000131
132 // Verify that this is in a function context.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000133 if (CurFunctionDecl == 0 && CurMethodDecl == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000134 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000135
Chris Lattner7e637512008-01-12 08:14:25 +0000136 // Pre-defined identifiers are of type char[x], where x is the length of the
137 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000138 unsigned Length;
139 if (CurFunctionDecl)
140 Length = CurFunctionDecl->getIdentifier()->getLength();
141 else
Fariborz Jahaniandcecd5c2008-01-17 17:37:26 +0000142 Length = CurMethodDecl->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000143
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000144 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000145 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000146 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner7e637512008-01-12 08:14:25 +0000147 return new PreDefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000148}
149
Steve Naroff87d58b42007-09-16 03:34:24 +0000150Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000151 llvm::SmallString<16> CharBuffer;
152 CharBuffer.resize(Tok.getLength());
153 const char *ThisTokBegin = &CharBuffer[0];
154 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
155
156 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
157 Tok.getLocation(), PP);
158 if (Literal.hadError())
159 return ExprResult(true);
160 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
161 Tok.getLocation());
162}
163
Steve Naroff87d58b42007-09-16 03:34:24 +0000164Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000165 // fast path for a single digit (which is quite common). A single digit
166 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
167 if (Tok.getLength() == 1) {
168 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
169
Chris Lattner3496d522007-09-04 02:45:27 +0000170 unsigned IntSize = static_cast<unsigned>(
171 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000172 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
173 Context.IntTy,
174 Tok.getLocation()));
175 }
176 llvm::SmallString<512> IntegerBuffer;
177 IntegerBuffer.resize(Tok.getLength());
178 const char *ThisTokBegin = &IntegerBuffer[0];
179
180 // Get the spelling of the token, which eliminates trigraphs, etc.
181 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
182 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
183 Tok.getLocation(), PP);
184 if (Literal.hadError)
185 return ExprResult(true);
186
Chris Lattner1de66eb2007-08-26 03:42:43 +0000187 Expr *Res;
188
189 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000190 QualType Ty;
191 const llvm::fltSemantics *Format;
192 uint64_t Size; unsigned Align;
193
194 if (Literal.isFloat) {
195 Ty = Context.FloatTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000196 Context.Target.getFloatInfo(Size, Align, Format,
197 Context.getFullLoc(Tok.getLocation()));
198
Chris Lattner858eece2007-09-22 18:29:59 +0000199 } else if (Literal.isLong) {
200 Ty = Context.LongDoubleTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000201 Context.Target.getLongDoubleInfo(Size, Align, Format,
202 Context.getFullLoc(Tok.getLocation()));
Chris Lattner858eece2007-09-22 18:29:59 +0000203 } else {
204 Ty = Context.DoubleTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000205 Context.Target.getDoubleInfo(Size, Align, Format,
206 Context.getFullLoc(Tok.getLocation()));
Chris Lattner858eece2007-09-22 18:29:59 +0000207 }
208
Ted Kremenekddedbe22007-11-29 00:56:49 +0000209 // isExact will be set by GetFloatValue().
210 bool isExact = false;
211
212 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
213 Ty, Tok.getLocation());
214
Chris Lattner1de66eb2007-08-26 03:42:43 +0000215 } else if (!Literal.isIntegerLiteral()) {
216 return ExprResult(true);
217 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000218 QualType t;
219
Neil Booth7421e9c2007-08-29 22:00:19 +0000220 // long long is a C99 feature.
221 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000222 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000223 Diag(Tok.getLocation(), diag::ext_longlong);
224
Chris Lattner4b009652007-07-25 00:24:17 +0000225 // Get the value in the widest-possible width.
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000226 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(
227 Context.getFullLoc(Tok.getLocation())), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000228
229 if (Literal.GetIntegerValue(ResultVal)) {
230 // If this value didn't fit into uintmax_t, warn and force to ull.
231 Diag(Tok.getLocation(), diag::warn_integer_too_large);
232 t = Context.UnsignedLongLongTy;
233 assert(Context.getTypeSize(t, Tok.getLocation()) ==
234 ResultVal.getBitWidth() && "long long is not intmax_t?");
235 } else {
236 // If this value fits into a ULL, try to figure out what else it fits into
237 // according to the rules of C99 6.4.4.1p5.
238
239 // Octal, Hexadecimal, and integers with a U suffix are allowed to
240 // be an unsigned int.
241 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
242
243 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000244 if (!Literal.isLong && !Literal.isLongLong) {
245 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000246 unsigned IntSize = static_cast<unsigned>(
247 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000248 // Does it fit in a unsigned int?
249 if (ResultVal.isIntN(IntSize)) {
250 // Does it fit in a signed int?
251 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
252 t = Context.IntTy;
253 else if (AllowUnsigned)
254 t = Context.UnsignedIntTy;
255 }
256
257 if (!t.isNull())
258 ResultVal.trunc(IntSize);
259 }
260
261 // Are long/unsigned long possibilities?
262 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000263 unsigned LongSize = static_cast<unsigned>(
264 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000265
266 // Does it fit in a unsigned long?
267 if (ResultVal.isIntN(LongSize)) {
268 // Does it fit in a signed long?
269 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
270 t = Context.LongTy;
271 else if (AllowUnsigned)
272 t = Context.UnsignedLongTy;
273 }
274 if (!t.isNull())
275 ResultVal.trunc(LongSize);
276 }
277
278 // Finally, check long long if needed.
279 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000280 unsigned LongLongSize = static_cast<unsigned>(
281 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000282
283 // Does it fit in a unsigned long long?
284 if (ResultVal.isIntN(LongLongSize)) {
285 // Does it fit in a signed long long?
286 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
287 t = Context.LongLongTy;
288 else if (AllowUnsigned)
289 t = Context.UnsignedLongLongTy;
290 }
291 }
292
293 // If we still couldn't decide a type, we probably have something that
294 // does not fit in a signed long long, but has no U suffix.
295 if (t.isNull()) {
296 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
297 t = Context.UnsignedLongLongTy;
298 }
299 }
300
Chris Lattner1de66eb2007-08-26 03:42:43 +0000301 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000302 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000303
304 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
305 if (Literal.isImaginary)
306 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
307
308 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000309}
310
Steve Naroff87d58b42007-09-16 03:34:24 +0000311Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000312 ExprTy *Val) {
313 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000314 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000315 return new ParenExpr(L, R, e);
316}
317
318/// The UsualUnaryConversions() function is *not* called by this routine.
319/// See C99 6.3.2.1p[2-4] for more details.
320QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
321 SourceLocation OpLoc, bool isSizeof) {
322 // C99 6.5.3.4p1:
323 if (isa<FunctionType>(exprType) && isSizeof)
324 // alignof(function) is allowed.
325 Diag(OpLoc, diag::ext_sizeof_function_type);
326 else if (exprType->isVoidType())
327 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
328 else if (exprType->isIncompleteType()) {
329 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
330 diag::err_alignof_incomplete_type,
331 exprType.getAsString());
332 return QualType(); // error
333 }
334 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
335 return Context.getSizeType();
336}
337
338Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000339ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000340 SourceLocation LPLoc, TypeTy *Ty,
341 SourceLocation RPLoc) {
342 // If error parsing type, ignore.
343 if (Ty == 0) return true;
344
345 // Verify that this is a valid expression.
346 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
347
348 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
349
350 if (resultType.isNull())
351 return true;
352 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
353}
354
Chris Lattner5110ad52007-08-24 21:41:10 +0000355QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000356 DefaultFunctionArrayConversion(V);
357
Chris Lattnera16e42d2007-08-26 05:39:26 +0000358 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000359 if (const ComplexType *CT = V->getType()->getAsComplexType())
360 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000361
362 // Otherwise they pass through real integer and floating point types here.
363 if (V->getType()->isArithmeticType())
364 return V->getType();
365
366 // Reject anything else.
367 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
368 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000369}
370
371
Chris Lattner4b009652007-07-25 00:24:17 +0000372
Steve Naroff87d58b42007-09-16 03:34:24 +0000373Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000374 tok::TokenKind Kind,
375 ExprTy *Input) {
376 UnaryOperator::Opcode Opc;
377 switch (Kind) {
378 default: assert(0 && "Unknown unary op!");
379 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
380 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
381 }
382 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
383 if (result.isNull())
384 return true;
385 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
386}
387
388Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000389ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000390 ExprTy *Idx, SourceLocation RLoc) {
391 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
392
393 // Perform default conversions.
394 DefaultFunctionArrayConversion(LHSExp);
395 DefaultFunctionArrayConversion(RHSExp);
396
397 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
398
399 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000400 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000401 // in the subscript position. As a result, we need to derive the array base
402 // and index from the expression types.
403 Expr *BaseExpr, *IndexExpr;
404 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000405 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000406 BaseExpr = LHSExp;
407 IndexExpr = RHSExp;
408 // FIXME: need to deal with const...
409 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000410 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000411 // Handle the uncommon case of "123[Ptr]".
412 BaseExpr = RHSExp;
413 IndexExpr = LHSExp;
414 // FIXME: need to deal with const...
415 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000416 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
417 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000418 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000419
420 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman506806b2008-02-19 01:11:03 +0000421 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr))
Steve Naroff89345522007-08-03 22:40:33 +0000422 return Diag(LLoc, diag::err_ocuvector_component_access,
423 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000424 // FIXME: need to deal with const...
425 ResultType = VTy->getElementType();
426 } else {
427 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
428 RHSExp->getSourceRange());
429 }
430 // C99 6.5.2.1p1
431 if (!IndexExpr->getType()->isIntegerType())
432 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
433 IndexExpr->getSourceRange());
434
435 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
436 // the following check catches trying to index a pointer to a function (e.g.
437 // void (*)(int)). Functions are not objects in C99.
438 if (!ResultType->isObjectType())
439 return Diag(BaseExpr->getLocStart(),
440 diag::err_typecheck_subscript_not_object,
441 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
442
443 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
444}
445
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000446QualType Sema::
447CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
448 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000449 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000450
451 // The vector accessor can't exceed the number of elements.
452 const char *compStr = CompName.getName();
453 if (strlen(compStr) > vecType->getNumElements()) {
454 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
455 baseType.getAsString(), SourceRange(CompLoc));
456 return QualType();
457 }
458 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000459 if (vecType->getPointAccessorIdx(*compStr) != -1) {
460 do
461 compStr++;
462 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
463 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
464 do
465 compStr++;
466 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
467 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
468 do
469 compStr++;
470 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
471 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000472
473 if (*compStr) {
474 // We didn't get to the end of the string. This means the component names
475 // didn't come from the same set *or* we encountered an illegal name.
476 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
477 std::string(compStr,compStr+1), SourceRange(CompLoc));
478 return QualType();
479 }
480 // Each component accessor can't exceed the vector type.
481 compStr = CompName.getName();
482 while (*compStr) {
483 if (vecType->isAccessorWithinNumElements(*compStr))
484 compStr++;
485 else
486 break;
487 }
488 if (*compStr) {
489 // We didn't get to the end of the string. This means a component accessor
490 // exceeds the number of elements in the vector.
491 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
492 baseType.getAsString(), SourceRange(CompLoc));
493 return QualType();
494 }
495 // The component accessor looks fine - now we need to compute the actual type.
496 // The vector type is implied by the component accessor. For example,
497 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
498 unsigned CompSize = strlen(CompName.getName());
499 if (CompSize == 1)
500 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000501
502 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
503 // Now look up the TypeDefDecl from the vector type. Without this,
504 // diagostics look bad. We want OCU vector types to appear built-in.
505 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
506 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
507 return Context.getTypedefType(OCUVectorDecls[i]);
508 }
509 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000510}
511
Chris Lattner4b009652007-07-25 00:24:17 +0000512Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000513ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000514 tok::TokenKind OpKind, SourceLocation MemberLoc,
515 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000516 Expr *BaseExpr = static_cast<Expr *>(Base);
517 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000518
519 // Perform default conversions.
520 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000521
Steve Naroff2cb66382007-07-26 03:11:44 +0000522 QualType BaseType = BaseExpr->getType();
523 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000524
Chris Lattner4b009652007-07-25 00:24:17 +0000525 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000526 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000527 BaseType = PT->getPointeeType();
528 else
529 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
530 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000531 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000532 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000533 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000534 RecordDecl *RDecl = RTy->getDecl();
535 if (RTy->isIncompleteType())
536 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
537 BaseExpr->getSourceRange());
538 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000539 FieldDecl *MemberDecl = RDecl->getMember(&Member);
540 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000541 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
542 SourceRange(MemberLoc));
Eli Friedman76b49832008-02-06 22:48:16 +0000543
544 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000545 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000546 QualType MemberType = MemberDecl->getType();
547 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000548 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000549 MemberType = MemberType.getQualifiedType(combinedQualifiers);
550
551 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl,
552 MemberLoc, MemberType);
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000553 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000554 // Component access limited to variables (reject vec4.rg.g).
555 if (!isa<DeclRefExpr>(BaseExpr))
556 return Diag(OpLoc, diag::err_ocuvector_component_access,
557 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000558 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
559 if (ret.isNull())
560 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000561 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Ted Kremenek42730c52008-01-07 19:49:32 +0000562 } else if (BaseType->isObjCInterfaceType()) {
563 ObjCInterfaceDecl *IFace;
564 if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
565 IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000566 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000567 IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
568 ObjCInterfaceDecl *clsDeclared;
569 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000570 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
571 OpKind==tok::arrow);
572 }
573 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
574 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000575}
576
Steve Naroff87d58b42007-09-16 03:34:24 +0000577/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000578/// This provides the location of the left/right parens and a list of comma
579/// locations.
580Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000581ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000582 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000583 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
584 Expr *Fn = static_cast<Expr *>(fn);
585 Expr **Args = reinterpret_cast<Expr**>(args);
586 assert(Fn && "no function call expression");
587
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000588 // Make the call expr early, before semantic checks. This guarantees cleanup
589 // of arguments and function on error.
590 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
591 Context.BoolTy, RParenLoc));
592
593 // Promote the function operand.
594 TheCall->setCallee(UsualUnaryConversions(Fn));
595
Chris Lattner4b009652007-07-25 00:24:17 +0000596 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
597 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000598 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000599 if (PT == 0)
600 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
601 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000602 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
603 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000604 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
605 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000606
607 // We know the result type of the call, set it.
608 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000609
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000610 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000611 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
612 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000613 unsigned NumArgsInProto = Proto->getNumArgs();
614 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000615
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000616 // If too few arguments are available, don't make the call.
617 if (NumArgs < NumArgsInProto)
618 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
619 Fn->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000620
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000621 // If too many are passed and not variadic, error on the extras and drop
622 // them.
623 if (NumArgs > NumArgsInProto) {
624 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000625 Diag(Args[NumArgsInProto]->getLocStart(),
626 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
627 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000628 Args[NumArgs-1]->getLocEnd()));
629 // This deletes the extra arguments.
630 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000631 }
632 NumArgsToCheck = NumArgsInProto;
633 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000634
Chris Lattner4b009652007-07-25 00:24:17 +0000635 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000636 for (unsigned i = 0; i != NumArgsToCheck; i++) {
637 Expr *Arg = Args[i];
Chris Lattner005ed752008-01-04 18:04:52 +0000638 QualType ProtoArgType = Proto->getArgType(i);
639 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000640
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000641 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +0000642 AssignConvertType ConvTy =
643 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000644 TheCall->setArg(i, Arg);
645
Chris Lattner005ed752008-01-04 18:04:52 +0000646 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
647 ArgType, Arg, "passing"))
648 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000649 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000650
651 // If this is a variadic call, handle args passed through "...".
652 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +0000653 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000654 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
655 Expr *Arg = Args[i];
656 DefaultArgumentPromotion(Arg);
657 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000658 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000659 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000660 } else {
661 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
662
Steve Naroffdb65e052007-08-28 23:30:39 +0000663 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000664 for (unsigned i = 0; i != NumArgs; i++) {
665 Expr *Arg = Args[i];
666 DefaultArgumentPromotion(Arg);
667 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000668 }
Chris Lattner4b009652007-07-25 00:24:17 +0000669 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000670
Chris Lattner2e64c072007-08-10 20:18:51 +0000671 // Do special checking on direct calls to functions.
672 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
673 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
674 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000675 if (CheckFunctionCall(FDecl, TheCall.get()))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000676 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000677
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000678 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000679}
680
681Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000682ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000683 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000684 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000685 QualType literalType = QualType::getFromOpaquePtr(Ty);
686 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000687 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000688 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000689
Steve Naroffcb69fb72007-12-10 22:44:33 +0000690 // FIXME: add more semantic analysis (C99 6.5.2.5).
Steve Narofff0b23542008-01-10 22:15:12 +0000691 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +0000692 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +0000693
694 bool isFileScope = !CurFunctionDecl && !CurMethodDecl;
695 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +0000696 if (CheckForConstantInitializer(literalExpr, literalType))
697 return true;
698 }
Steve Naroffbe37fc02008-01-14 18:19:28 +0000699 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000700}
701
702Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000703ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000704 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000705 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000706
Steve Naroff0acc9c92007-09-15 18:49:24 +0000707 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000708 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000709
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000710 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
711 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
712 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000713}
714
Chris Lattnerd1f26b32007-12-20 00:44:32 +0000715bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000716 assert(VectorTy->isVectorType() && "Not a vector type!");
717
718 if (Ty->isVectorType() || Ty->isIntegerType()) {
719 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
720 Context.getTypeSize(Ty, SourceLocation()))
721 return Diag(R.getBegin(),
722 Ty->isVectorType() ?
723 diag::err_invalid_conversion_between_vectors :
724 diag::err_invalid_conversion_between_vector_and_integer,
725 VectorTy.getAsString().c_str(),
726 Ty.getAsString().c_str(), R);
727 } else
728 return Diag(R.getBegin(),
729 diag::err_invalid_conversion_between_vector_and_scalar,
730 VectorTy.getAsString().c_str(),
731 Ty.getAsString().c_str(), R);
732
733 return false;
734}
735
Chris Lattner4b009652007-07-25 00:24:17 +0000736Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000737ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000738 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000739 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000740
741 Expr *castExpr = static_cast<Expr*>(Op);
742 QualType castType = QualType::getFromOpaquePtr(Ty);
743
Steve Naroff68adb482007-08-31 00:32:44 +0000744 UsualUnaryConversions(castExpr);
745
Chris Lattner4b009652007-07-25 00:24:17 +0000746 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
747 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000748 if (!castType->isVoidType()) { // Cast to void allows any expr type.
Steve Narofff459ee52008-01-24 22:55:05 +0000749 if (!castType->isScalarType() && !castType->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000750 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
751 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Steve Narofff459ee52008-01-24 22:55:05 +0000752 if (!castExpr->getType()->isScalarType() &&
753 !castExpr->getType()->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000754 return Diag(castExpr->getLocStart(),
755 diag::err_typecheck_expect_scalar_operand,
756 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000757
758 if (castExpr->getType()->isVectorType()) {
759 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
760 castExpr->getType(), castType))
761 return true;
762 } else if (castType->isVectorType()) {
763 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
764 castType, castExpr->getType()))
765 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000766 }
Chris Lattner4b009652007-07-25 00:24:17 +0000767 }
768 return new CastExpr(castType, castExpr, LParenLoc);
769}
770
Chris Lattner98a425c2007-11-26 01:40:58 +0000771/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
772/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000773inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
774 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
775 UsualUnaryConversions(cond);
776 UsualUnaryConversions(lex);
777 UsualUnaryConversions(rex);
778 QualType condT = cond->getType();
779 QualType lexT = lex->getType();
780 QualType rexT = rex->getType();
781
782 // first, check the condition.
783 if (!condT->isScalarType()) { // C99 6.5.15p2
784 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
785 condT.getAsString());
786 return QualType();
787 }
Chris Lattner992ae932008-01-06 22:42:25 +0000788
789 // Now check the two expressions.
790
791 // If both operands have arithmetic type, do the usual arithmetic conversions
792 // to find a common type: C99 6.5.15p3,5.
793 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000794 UsualArithmeticConversions(lex, rex);
795 return lex->getType();
796 }
Chris Lattner992ae932008-01-06 22:42:25 +0000797
798 // If both operands are the same structure or union type, the result is that
799 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000800 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +0000801 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +0000802 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +0000803 // "If both the operands have structure or union type, the result has
804 // that type." This implies that CV qualifiers are dropped.
805 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000806 }
Chris Lattner992ae932008-01-06 22:42:25 +0000807
808 // C99 6.5.15p5: "If both operands have void type, the result has void type."
809 if (lexT->isVoidType() && rexT->isVoidType())
810 return lexT.getUnqualifiedType();
Steve Naroff12ebf272008-01-08 01:11:38 +0000811
812 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
813 // the type of the other operand."
814 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000815 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000816 return lexT;
817 }
818 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000819 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000820 return rexT;
821 }
Chris Lattner0ac51632008-01-06 22:50:31 +0000822 // Handle the case where both operands are pointers before we handle null
823 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +0000824 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
825 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
826 // get the "pointed to" types
827 QualType lhptee = LHSPT->getPointeeType();
828 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000829
Chris Lattner71225142007-07-31 21:27:01 +0000830 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
831 if (lhptee->isVoidType() &&
Eli Friedmanca07c902008-02-10 22:59:36 +0000832 (rhptee->isObjectType() || rhptee->isIncompleteType())) {
Chris Lattner35fef522008-02-20 20:55:12 +0000833 // Figure out necessary qualifiers (C99 6.5.15p6)
834 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000835 QualType destType = Context.getPointerType(destPointee);
836 ImpCastExprToType(lex, destType); // add qualifiers if necessary
837 ImpCastExprToType(rex, destType); // promote to void*
838 return destType;
839 }
Chris Lattner71225142007-07-31 21:27:01 +0000840 if (rhptee->isVoidType() &&
Eli Friedmanca07c902008-02-10 22:59:36 +0000841 (lhptee->isObjectType() || lhptee->isIncompleteType())) {
Chris Lattner35fef522008-02-20 20:55:12 +0000842 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000843 QualType destType = Context.getPointerType(destPointee);
844 ImpCastExprToType(lex, destType); // add qualifiers if necessary
845 ImpCastExprToType(rex, destType); // promote to void*
846 return destType;
847 }
Chris Lattner4b009652007-07-25 00:24:17 +0000848
Steve Naroff85f0dc52007-10-15 20:41:53 +0000849 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
850 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +0000851 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +0000852 lexT.getAsString(), rexT.getAsString(),
853 lex->getSourceRange(), rex->getSourceRange());
Eli Friedman33284862008-01-30 17:02:03 +0000854 // In this situation, we assume void* type. No especially good
855 // reason, but this is what gcc does, and we do have to pick
856 // to get a consistent AST.
857 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
858 ImpCastExprToType(lex, voidPtrTy);
859 ImpCastExprToType(rex, voidPtrTy);
860 return voidPtrTy;
Chris Lattner71225142007-07-31 21:27:01 +0000861 }
862 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000863 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
864 // differently qualified versions of compatible types, the result type is
865 // a pointer to an appropriately qualified version of the *composite*
866 // type.
Chris Lattner0ac51632008-01-06 22:50:31 +0000867 // FIXME: Need to return the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +0000868 // FIXME: Need to add qualifiers
Chris Lattner0ac51632008-01-06 22:50:31 +0000869 return lexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000870 }
Chris Lattner4b009652007-07-25 00:24:17 +0000871 }
Chris Lattner71225142007-07-31 21:27:01 +0000872
Chris Lattner992ae932008-01-06 22:42:25 +0000873 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +0000874 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
875 lexT.getAsString(), rexT.getAsString(),
876 lex->getSourceRange(), rex->getSourceRange());
877 return QualType();
878}
879
Steve Naroff87d58b42007-09-16 03:34:24 +0000880/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000881/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000882Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000883 SourceLocation ColonLoc,
884 ExprTy *Cond, ExprTy *LHS,
885 ExprTy *RHS) {
886 Expr *CondExpr = (Expr *) Cond;
887 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000888
889 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
890 // was the condition.
891 bool isLHSNull = LHSExpr == 0;
892 if (isLHSNull)
893 LHSExpr = CondExpr;
894
Chris Lattner4b009652007-07-25 00:24:17 +0000895 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
896 RHSExpr, QuestionLoc);
897 if (result.isNull())
898 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000899 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
900 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000901}
902
Steve Naroffdb65e052007-08-28 23:30:39 +0000903/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Steve Naroffbbaed752008-01-29 02:42:22 +0000904/// do not have a prototype. Arguments that have type float are promoted to
905/// double. All other argument types are converted by UsualUnaryConversions().
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000906void Sema::DefaultArgumentPromotion(Expr *&Expr) {
907 QualType Ty = Expr->getType();
908 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffdb65e052007-08-28 23:30:39 +0000909
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000910 if (Ty == Context.FloatTy)
Chris Lattnere992d6c2008-01-16 19:17:22 +0000911 ImpCastExprToType(Expr, Context.DoubleTy);
Steve Naroffbbaed752008-01-29 02:42:22 +0000912 else
913 UsualUnaryConversions(Expr);
Steve Naroffdb65e052007-08-28 23:30:39 +0000914}
915
Chris Lattner4b009652007-07-25 00:24:17 +0000916/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
917void Sema::DefaultFunctionArrayConversion(Expr *&e) {
918 QualType t = e->getType();
919 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
920
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000921 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000922 ImpCastExprToType(e, ref->getReferenceeType()); // C++ [expr]
Chris Lattner4b009652007-07-25 00:24:17 +0000923 t = e->getType();
924 }
925 if (t->isFunctionType())
Chris Lattnere992d6c2008-01-16 19:17:22 +0000926 ImpCastExprToType(e, Context.getPointerType(t));
Steve Naroffac26e9a2008-02-09 16:59:44 +0000927 else if (const ArrayType *ary = t->getAsArrayType()) {
Steve Naroff9ffeda12008-02-09 17:25:18 +0000928 // Make sure we don't lose qualifiers when dealing with typedefs. Example:
Steve Naroffac26e9a2008-02-09 16:59:44 +0000929 // typedef int arr[10];
930 // void test2() {
931 // const arr b;
932 // b[4] = 1;
933 // }
934 QualType ELT = ary->getElementType();
Chris Lattner35fef522008-02-20 20:55:12 +0000935 // FIXME: Handle ASQualType
936 ELT = ELT.getQualifiedType(t.getCVRQualifiers()|ELT.getCVRQualifiers());
Steve Naroffac26e9a2008-02-09 16:59:44 +0000937 ImpCastExprToType(e, Context.getPointerType(ELT));
938 }
Chris Lattner4b009652007-07-25 00:24:17 +0000939}
940
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000941/// UsualUnaryConversions - Performs various conversions that are common to most
Chris Lattner4b009652007-07-25 00:24:17 +0000942/// operators (C99 6.3). The conversions of array and function types are
943/// sometimes surpressed. For example, the array->pointer conversion doesn't
944/// apply if the array is an argument to the sizeof or address (&) operators.
945/// In these instances, this routine should *not* be called.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000946Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
947 QualType Ty = Expr->getType();
948 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000949
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000950 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000951 ImpCastExprToType(Expr, Ref->getReferenceeType()); // C++ [expr]
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000952 Ty = Expr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000953 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000954 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
Chris Lattnere992d6c2008-01-16 19:17:22 +0000955 ImpCastExprToType(Expr, Context.IntTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000956 else
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000957 DefaultFunctionArrayConversion(Expr);
958
959 return Expr;
Chris Lattner4b009652007-07-25 00:24:17 +0000960}
961
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000962/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000963/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
964/// routine returns the first non-arithmetic type found. The client is
965/// responsible for emitting appropriate error diagnostics.
Steve Naroffe8419ca2008-01-15 22:21:49 +0000966/// FIXME: verify the conversion rules for "complex int" are consistent with GCC.
Steve Naroff8f708362007-08-24 19:07:16 +0000967QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
968 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000969 if (!isCompAssign) {
970 UsualUnaryConversions(lhsExpr);
971 UsualUnaryConversions(rhsExpr);
972 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000973 // For conversion purposes, we ignore any qualifiers.
974 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000975 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
976 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000977
978 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000979 if (lhs == rhs)
980 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000981
982 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
983 // The caller can deal with this (e.g. pointer + int).
984 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000985 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000986
987 // At this point, we have two different arithmetic types.
988
989 // Handle complex types first (C99 6.3.1.8p1).
990 if (lhs->isComplexType() || rhs->isComplexType()) {
Steve Naroff43001212008-01-15 19:36:10 +0000991 // if we have an integer operand, the result is the complex type.
Steve Naroffe8419ca2008-01-15 22:21:49 +0000992 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +0000993 // convert the rhs to the lhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +0000994 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +0000995 return lhs;
Steve Naroff43001212008-01-15 19:36:10 +0000996 }
Steve Naroffe8419ca2008-01-15 22:21:49 +0000997 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +0000998 // convert the lhs to the rhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +0000999 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001000 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001001 }
Steve Naroff3cf497f2007-08-27 01:27:54 +00001002 // This handles complex/complex, complex/float, or float/complex.
1003 // When both operands are complex, the shorter operand is converted to the
1004 // type of the longer, and that is the type of the result. This corresponds
1005 // to what is done when combining two real floating-point operands.
1006 // The fun begins when size promotion occur across type domains.
1007 // From H&S 6.3.4: When one operand is complex and the other is a real
1008 // floating-point type, the less precise type is converted, within it's
1009 // real or complex domain, to the precision of the other type. For example,
1010 // when combining a "long double" with a "double _Complex", the
1011 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +00001012 int result = Context.compareFloatingType(lhs, rhs);
1013
1014 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +00001015 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
1016 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001017 ImpCastExprToType(rhsExpr, rhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001018 } else if (result < 0) { // The right side is bigger, convert lhs.
1019 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
1020 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001021 ImpCastExprToType(lhsExpr, lhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001022 }
1023 // At this point, lhs and rhs have the same rank/size. Now, make sure the
1024 // domains match. This is a requirement for our implementation, C99
1025 // does not require this promotion.
1026 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1027 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001028 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001029 ImpCastExprToType(lhsExpr, rhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001030 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001031 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001032 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001033 ImpCastExprToType(rhsExpr, lhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001034 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001035 }
Chris Lattner4b009652007-07-25 00:24:17 +00001036 }
Steve Naroff3b6157f2007-08-27 21:43:43 +00001037 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +00001038 }
1039 // Now handle "real" floating types (i.e. float, double, long double).
1040 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1041 // if we have an integer operand, the result is the real floating type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001042 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001043 // convert rhs to the lhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001044 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001045 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001046 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001047 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001048 // convert lhs to the rhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001049 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001050 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001051 }
1052 // We have two real floating types, float/complex combos were handled above.
1053 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +00001054 int result = Context.compareFloatingType(lhs, rhs);
1055
1056 if (result > 0) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001057 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001058 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001059 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001060 if (result < 0) { // convert the lhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001061 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff45fc9822007-08-27 15:30:22 +00001062 return rhs;
1063 }
1064 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001065 }
Steve Naroff43001212008-01-15 19:36:10 +00001066 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
1067 // Handle GCC complex int extension.
Steve Naroff43001212008-01-15 19:36:10 +00001068 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
Eli Friedman50727042008-02-08 01:19:44 +00001069 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
Steve Naroff43001212008-01-15 19:36:10 +00001070
Eli Friedman50727042008-02-08 01:19:44 +00001071 if (lhsComplexInt && rhsComplexInt) {
1072 if (Context.maxIntegerType(lhsComplexInt->getElementType(),
Eli Friedman94075c02008-02-08 01:24:30 +00001073 rhsComplexInt->getElementType()) == lhs) {
1074 // convert the rhs
1075 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1076 return lhs;
Eli Friedman50727042008-02-08 01:19:44 +00001077 }
1078 if (!isCompAssign)
Eli Friedman94075c02008-02-08 01:24:30 +00001079 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Eli Friedman50727042008-02-08 01:19:44 +00001080 return rhs;
1081 } else if (lhsComplexInt && rhs->isIntegerType()) {
1082 // convert the rhs to the lhs complex type.
1083 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1084 return lhs;
1085 } else if (rhsComplexInt && lhs->isIntegerType()) {
1086 // convert the lhs to the rhs complex type.
1087 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1088 return rhs;
1089 }
Steve Naroff43001212008-01-15 19:36:10 +00001090 }
Chris Lattner4b009652007-07-25 00:24:17 +00001091 // Finally, we have two differing integer types.
1092 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001093 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001094 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001095 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001096 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff8f708362007-08-24 19:07:16 +00001097 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001098}
1099
1100// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1101// being closely modeled after the C99 spec:-). The odd characteristic of this
1102// routine is it effectively iqnores the qualifiers on the top level pointee.
1103// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1104// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001105Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001106Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1107 QualType lhptee, rhptee;
1108
1109 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001110 lhptee = lhsType->getAsPointerType()->getPointeeType();
1111 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001112
1113 // make sure we operate on the canonical type
1114 lhptee = lhptee.getCanonicalType();
1115 rhptee = rhptee.getCanonicalType();
1116
Chris Lattner005ed752008-01-04 18:04:52 +00001117 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001118
1119 // C99 6.5.16.1p1: This following citation is common to constraints
1120 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1121 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001122 // FIXME: Handle ASQualType
1123 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1124 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001125 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001126
1127 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1128 // incomplete type and the other is a pointer to a qualified or unqualified
1129 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001130 if (lhptee->isVoidType()) {
1131 if (rhptee->isObjectType() || rhptee->isIncompleteType())
Chris Lattner005ed752008-01-04 18:04:52 +00001132 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001133
1134 // As an extension, we allow cast to/from void* to function pointer.
1135 if (rhptee->isFunctionType())
1136 return FunctionVoidPointer;
1137 }
1138
1139 if (rhptee->isVoidType()) {
1140 if (lhptee->isObjectType() || lhptee->isIncompleteType())
Chris Lattner005ed752008-01-04 18:04:52 +00001141 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001142
1143 // As an extension, we allow cast to/from void* to function pointer.
1144 if (lhptee->isFunctionType())
1145 return FunctionVoidPointer;
1146 }
1147
Chris Lattner4b009652007-07-25 00:24:17 +00001148 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1149 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001150 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1151 rhptee.getUnqualifiedType()))
1152 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001153 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001154}
1155
1156/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1157/// has code to accommodate several GCC extensions when type checking
1158/// pointers. Here are some objectionable examples that GCC considers warnings:
1159///
1160/// int a, *pint;
1161/// short *pshort;
1162/// struct foo *pfoo;
1163///
1164/// pint = pshort; // warning: assignment from incompatible pointer type
1165/// a = pint; // warning: assignment makes integer from pointer without a cast
1166/// pint = a; // warning: assignment makes pointer from integer without a cast
1167/// pint = pfoo; // warning: assignment from incompatible pointer type
1168///
1169/// As a result, the code for dealing with pointers is more complex than the
1170/// C99 spec dictates.
1171/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1172///
Chris Lattner005ed752008-01-04 18:04:52 +00001173Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001174Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001175 // Get canonical types. We're not formatting these types, just comparing
1176 // them.
1177 lhsType = lhsType.getCanonicalType();
1178 rhsType = rhsType.getCanonicalType();
1179
1180 if (lhsType.getUnqualifiedType() == rhsType.getUnqualifiedType())
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001181 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001182
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001183 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001184 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001185 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001186 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001187 }
Chris Lattner1853da22008-01-04 23:18:45 +00001188
Ted Kremenek42730c52008-01-07 19:49:32 +00001189 if (lhsType->isObjCQualifiedIdType()
1190 || rhsType->isObjCQualifiedIdType()) {
1191 if (Context.ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001192 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001193 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001194 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001195
1196 if (lhsType->isVectorType() || rhsType->isVectorType()) {
1197 // For OCUVector, allow vector splats; float -> <n x float>
1198 if (const OCUVectorType *LV = lhsType->getAsOCUVectorType()) {
1199 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1200 return Compatible;
1201 }
1202
1203 // If LHS and RHS are both vectors of integer or both vectors of floating
1204 // point types, and the total vector length is the same, allow the
1205 // conversion. This is a bitcast; no bits are changed but the result type
1206 // is different.
1207 if (getLangOptions().LaxVectorConversions &&
1208 lhsType->isVectorType() && rhsType->isVectorType()) {
1209 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1210 (lhsType->isRealFloatingType() && rhsType->isRealFloatingType())) {
1211 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1212 Context.getTypeSize(rhsType, SourceLocation()))
Nate Begemanec2d1062007-12-30 02:59:45 +00001213 return Compatible;
1214 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001215 }
1216 return Incompatible;
1217 }
1218
1219 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001220 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001221
1222 if (lhsType->isPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001223 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001224 return IntToPointer;
Chris Lattner4b009652007-07-25 00:24:17 +00001225
1226 if (rhsType->isPointerType())
1227 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001228 return Incompatible;
1229 }
1230
1231 if (rhsType->isPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001232 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1233 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001234 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001235
1236 if (lhsType->isPointerType())
1237 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001238 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001239 }
1240
1241 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001242 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001243 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001244 }
1245 return Incompatible;
1246}
1247
Chris Lattner005ed752008-01-04 18:04:52 +00001248Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001249Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001250 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1251 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001252 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001253 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001254 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001255 return Compatible;
1256 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001257 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001258 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001259 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001260 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001261 //
1262 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1263 // are better understood.
1264 if (!lhsType->isReferenceType())
1265 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001266
Chris Lattner005ed752008-01-04 18:04:52 +00001267 Sema::AssignConvertType result =
1268 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001269
1270 // C99 6.5.16.1p2: The value of the right operand is converted to the
1271 // type of the assignment expression.
1272 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001273 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001274 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001275}
1276
Chris Lattner005ed752008-01-04 18:04:52 +00001277Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001278Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1279 return CheckAssignmentConstraints(lhsType, rhsType);
1280}
1281
Chris Lattner2c8bff72007-12-12 05:47:28 +00001282QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001283 Diag(loc, diag::err_typecheck_invalid_operands,
1284 lex->getType().getAsString(), rex->getType().getAsString(),
1285 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001286 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001287}
1288
1289inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1290 Expr *&rex) {
1291 QualType lhsType = lex->getType(), rhsType = rex->getType();
1292
1293 // make sure the vector types are identical.
1294 if (lhsType == rhsType)
1295 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001296
1297 // if the lhs is an ocu vector and the rhs is a scalar of the same type,
1298 // promote the rhs to the vector type.
1299 if (const OCUVectorType *V = lhsType->getAsOCUVectorType()) {
1300 if (V->getElementType().getCanonicalType().getTypePtr()
1301 == rhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001302 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001303 return lhsType;
1304 }
1305 }
1306
1307 // if the rhs is an ocu vector and the lhs is a scalar of the same type,
1308 // promote the lhs to the vector type.
1309 if (const OCUVectorType *V = rhsType->getAsOCUVectorType()) {
1310 if (V->getElementType().getCanonicalType().getTypePtr()
1311 == lhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001312 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001313 return rhsType;
1314 }
1315 }
1316
Chris Lattner4b009652007-07-25 00:24:17 +00001317 // You cannot convert between vector values of different size.
1318 Diag(loc, diag::err_typecheck_vector_not_convertable,
1319 lex->getType().getAsString(), rex->getType().getAsString(),
1320 lex->getSourceRange(), rex->getSourceRange());
1321 return QualType();
1322}
1323
1324inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001325 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001326{
1327 QualType lhsType = lex->getType(), rhsType = rex->getType();
1328
1329 if (lhsType->isVectorType() || rhsType->isVectorType())
1330 return CheckVectorOperands(loc, lex, rex);
1331
Steve Naroff8f708362007-08-24 19:07:16 +00001332 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001333
Chris Lattner4b009652007-07-25 00:24:17 +00001334 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001335 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001336 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001337}
1338
1339inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001340 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001341{
1342 QualType lhsType = lex->getType(), rhsType = rex->getType();
1343
Steve Naroff8f708362007-08-24 19:07:16 +00001344 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001345
Chris Lattner4b009652007-07-25 00:24:17 +00001346 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001347 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001348 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001349}
1350
1351inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001352 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001353{
1354 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1355 return CheckVectorOperands(loc, lex, rex);
1356
Steve Naroff8f708362007-08-24 19:07:16 +00001357 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001358
1359 // handle the common case first (both operands are arithmetic).
1360 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001361 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001362
1363 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1364 return lex->getType();
1365 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1366 return rex->getType();
Chris Lattner2c8bff72007-12-12 05:47:28 +00001367 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001368}
1369
1370inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001371 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001372{
1373 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1374 return CheckVectorOperands(loc, lex, rex);
1375
Steve Naroff8f708362007-08-24 19:07:16 +00001376 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001377
Chris Lattnerf6da2912007-12-09 21:53:25 +00001378 // Enforce type constraints: C99 6.5.6p3.
1379
1380 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001381 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001382 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001383
1384 // Either ptr - int or ptr - ptr.
1385 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001386 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001387
Chris Lattnerf6da2912007-12-09 21:53:25 +00001388 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001389 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001390 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001391 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001392 Diag(loc, diag::ext_gnu_void_ptr,
1393 lex->getSourceRange(), rex->getSourceRange());
1394 } else {
1395 Diag(loc, diag::err_typecheck_sub_ptr_object,
1396 lex->getType().getAsString(), lex->getSourceRange());
1397 return QualType();
1398 }
1399 }
1400
1401 // The result type of a pointer-int computation is the pointer type.
1402 if (rex->getType()->isIntegerType())
1403 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001404
Chris Lattnerf6da2912007-12-09 21:53:25 +00001405 // Handle pointer-pointer subtractions.
1406 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001407 QualType rpointee = RHSPTy->getPointeeType();
1408
Chris Lattnerf6da2912007-12-09 21:53:25 +00001409 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001410 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001411 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001412 if (rpointee->isVoidType()) {
1413 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001414 Diag(loc, diag::ext_gnu_void_ptr,
1415 lex->getSourceRange(), rex->getSourceRange());
1416 } else {
1417 Diag(loc, diag::err_typecheck_sub_ptr_object,
1418 rex->getType().getAsString(), rex->getSourceRange());
1419 return QualType();
1420 }
1421 }
1422
1423 // Pointee types must be compatible.
Steve Naroff577f9722008-01-29 18:58:14 +00001424 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1425 rpointee.getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001426 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1427 lex->getType().getAsString(), rex->getType().getAsString(),
1428 lex->getSourceRange(), rex->getSourceRange());
1429 return QualType();
1430 }
1431
1432 return Context.getPointerDiffType();
1433 }
1434 }
1435
Chris Lattner2c8bff72007-12-12 05:47:28 +00001436 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001437}
1438
1439inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Chris Lattner2c8bff72007-12-12 05:47:28 +00001440 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1441 // C99 6.5.7p2: Each of the operands shall have integer type.
1442 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1443 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001444
Chris Lattner2c8bff72007-12-12 05:47:28 +00001445 // Shifts don't perform usual arithmetic conversions, they just do integer
1446 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001447 if (!isCompAssign)
1448 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001449 UsualUnaryConversions(rex);
1450
1451 // "The type of the result is that of the promoted left operand."
1452 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001453}
1454
Chris Lattner254f3bc2007-08-26 01:18:55 +00001455inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1456 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001457{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001458 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001459 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1460 UsualArithmeticConversions(lex, rex);
1461 else {
1462 UsualUnaryConversions(lex);
1463 UsualUnaryConversions(rex);
1464 }
Chris Lattner4b009652007-07-25 00:24:17 +00001465 QualType lType = lex->getType();
1466 QualType rType = rex->getType();
1467
Ted Kremenek486509e2007-10-29 17:13:39 +00001468 // For non-floating point types, check for self-comparisons of the form
1469 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1470 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001471 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001472 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1473 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001474 if (DRL->getDecl() == DRR->getDecl())
1475 Diag(loc, diag::warn_selfcomparison);
1476 }
1477
Chris Lattner254f3bc2007-08-26 01:18:55 +00001478 if (isRelational) {
1479 if (lType->isRealType() && rType->isRealType())
1480 return Context.IntTy;
1481 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001482 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001483 if (lType->isFloatingType()) {
1484 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001485 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001486 }
1487
Chris Lattner254f3bc2007-08-26 01:18:55 +00001488 if (lType->isArithmeticType() && rType->isArithmeticType())
1489 return Context.IntTy;
1490 }
Chris Lattner4b009652007-07-25 00:24:17 +00001491
Chris Lattner22be8422007-08-26 01:10:14 +00001492 bool LHSIsNull = lex->isNullPointerConstant(Context);
1493 bool RHSIsNull = rex->isNullPointerConstant(Context);
1494
Chris Lattner254f3bc2007-08-26 01:18:55 +00001495 // All of the following pointer related warnings are GCC extensions, except
1496 // when handling null pointer constants. One day, we can consider making them
1497 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001498 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Eli Friedman50727042008-02-08 01:19:44 +00001499 QualType lpointee = lType->getAsPointerType()->getPointeeType();
1500 QualType rpointee = rType->getAsPointerType()->getPointeeType();
1501
Steve Naroff3b435622007-11-13 14:57:38 +00001502 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Steve Naroff577f9722008-01-29 18:58:14 +00001503 !lpointee->isVoidType() && !lpointee->isVoidType() &&
1504 !Context.typesAreCompatible(lpointee.getUnqualifiedType(),
Eli Friedman50727042008-02-08 01:19:44 +00001505 rpointee.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001506 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1507 lType.getAsString(), rType.getAsString(),
1508 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001509 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001510 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001511 return Context.IntTy;
1512 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001513 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())
1514 && Context.ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001515 ImpCastExprToType(rex, lType);
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001516 return Context.IntTy;
1517 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001518 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001519 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001520 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1521 lType.getAsString(), rType.getAsString(),
1522 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001523 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001524 return Context.IntTy;
1525 }
1526 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001527 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001528 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1529 lType.getAsString(), rType.getAsString(),
1530 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001531 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001532 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001533 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001534 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001535}
1536
Chris Lattner4b009652007-07-25 00:24:17 +00001537inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001538 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001539{
1540 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1541 return CheckVectorOperands(loc, lex, rex);
1542
Steve Naroff8f708362007-08-24 19:07:16 +00001543 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001544
1545 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001546 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001547 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001548}
1549
1550inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1551 Expr *&lex, Expr *&rex, SourceLocation loc)
1552{
1553 UsualUnaryConversions(lex);
1554 UsualUnaryConversions(rex);
1555
1556 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1557 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001558 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001559}
1560
1561inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001562 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001563{
1564 QualType lhsType = lex->getType();
1565 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner4b009652007-07-25 00:24:17 +00001566 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1567
1568 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001569 case Expr::MLV_Valid:
1570 break;
1571 case Expr::MLV_ConstQualified:
1572 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1573 return QualType();
1574 case Expr::MLV_ArrayType:
1575 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1576 lhsType.getAsString(), lex->getSourceRange());
1577 return QualType();
1578 case Expr::MLV_NotObjectType:
1579 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1580 lhsType.getAsString(), lex->getSourceRange());
1581 return QualType();
1582 case Expr::MLV_InvalidExpression:
1583 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1584 lex->getSourceRange());
1585 return QualType();
1586 case Expr::MLV_IncompleteType:
1587 case Expr::MLV_IncompleteVoidType:
1588 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1589 lhsType.getAsString(), lex->getSourceRange());
1590 return QualType();
1591 case Expr::MLV_DuplicateVectorComponents:
1592 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1593 lex->getSourceRange());
1594 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001595 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001596
Chris Lattner005ed752008-01-04 18:04:52 +00001597 AssignConvertType ConvTy;
1598 if (compoundType.isNull())
1599 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1600 else
1601 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1602
1603 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1604 rex, "assigning"))
1605 return QualType();
1606
Chris Lattner4b009652007-07-25 00:24:17 +00001607 // C99 6.5.16p3: The type of an assignment expression is the type of the
1608 // left operand unless the left operand has qualified type, in which case
1609 // it is the unqualified version of the type of the left operand.
1610 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1611 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001612 // C++ 5.17p1: the type of the assignment expression is that of its left
1613 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001614 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001615}
1616
1617inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1618 Expr *&lex, Expr *&rex, SourceLocation loc) {
1619 UsualUnaryConversions(rex);
1620 return rex->getType();
1621}
1622
1623/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1624/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1625QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1626 QualType resType = op->getType();
1627 assert(!resType.isNull() && "no type for increment/decrement expression");
1628
Steve Naroffd30e1932007-08-24 17:20:07 +00001629 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001630 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001631 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1632 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1633 resType.getAsString(), op->getSourceRange());
1634 return QualType();
1635 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001636 } else if (!resType->isRealType()) {
1637 if (resType->isComplexType())
1638 // C99 does not support ++/-- on complex types.
1639 Diag(OpLoc, diag::ext_integer_increment_complex,
1640 resType.getAsString(), op->getSourceRange());
1641 else {
1642 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1643 resType.getAsString(), op->getSourceRange());
1644 return QualType();
1645 }
Chris Lattner4b009652007-07-25 00:24:17 +00001646 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001647 // At this point, we know we have a real, complex or pointer type.
1648 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001649 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1650 if (mlval != Expr::MLV_Valid) {
1651 // FIXME: emit a more precise diagnostic...
1652 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1653 op->getSourceRange());
1654 return QualType();
1655 }
1656 return resType;
1657}
1658
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001659/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00001660/// This routine allows us to typecheck complex/recursive expressions
1661/// where the declaration is needed for type checking. Here are some
1662/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001663static ValueDecl *getPrimaryDecl(Expr *e) {
Chris Lattner4b009652007-07-25 00:24:17 +00001664 switch (e->getStmtClass()) {
1665 case Stmt::DeclRefExprClass:
1666 return cast<DeclRefExpr>(e)->getDecl();
1667 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001668 // Fields cannot be declared with a 'register' storage class.
1669 // &X->f is always ok, even if X is declared register.
1670 if (cast<MemberExpr>(e)->isArrow())
1671 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001672 return getPrimaryDecl(cast<MemberExpr>(e)->getBase());
1673 case Stmt::ArraySubscriptExprClass: {
1674 // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer.
1675
1676 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(e)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00001677 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001678 return 0;
1679 else
1680 return VD;
1681 }
Chris Lattner4b009652007-07-25 00:24:17 +00001682 case Stmt::UnaryOperatorClass:
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001683 return getPrimaryDecl(cast<UnaryOperator>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001684 case Stmt::ParenExprClass:
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001685 return getPrimaryDecl(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001686 case Stmt::ImplicitCastExprClass:
1687 // &X[4] when X is an array, has an implicit cast from array to pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001688 return getPrimaryDecl(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001689 default:
1690 return 0;
1691 }
1692}
1693
1694/// CheckAddressOfOperand - The operand of & must be either a function
1695/// designator or an lvalue designating an object. If it is an lvalue, the
1696/// object cannot be declared with storage class register or be a bit field.
1697/// Note: The usual conversions are *not* applied to the operand of the &
1698/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1699QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001700 if (getLangOptions().C99) {
1701 // Implement C99-only parts of addressof rules.
1702 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
1703 if (uOp->getOpcode() == UnaryOperator::Deref)
1704 // Per C99 6.5.3.2, the address of a deref always returns a valid result
1705 // (assuming the deref expression is valid).
1706 return uOp->getSubExpr()->getType();
1707 }
1708 // Technically, there should be a check for array subscript
1709 // expressions here, but the result of one is always an lvalue anyway.
1710 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001711 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner4b009652007-07-25 00:24:17 +00001712 Expr::isLvalueResult lval = op->isLvalue();
1713
1714 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001715 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1716 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001717 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1718 op->getSourceRange());
1719 return QualType();
1720 }
1721 } else if (dcl) {
1722 // We have an lvalue with a decl. Make sure the decl is not declared
1723 // with the register storage-class specifier.
1724 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1725 if (vd->getStorageClass() == VarDecl::Register) {
1726 Diag(OpLoc, diag::err_typecheck_address_of_register,
1727 op->getSourceRange());
1728 return QualType();
1729 }
1730 } else
1731 assert(0 && "Unknown/unexpected decl type");
1732
1733 // FIXME: add check for bitfields!
1734 }
1735 // If the operand has type "type", the result has type "pointer to type".
1736 return Context.getPointerType(op->getType());
1737}
1738
1739QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1740 UsualUnaryConversions(op);
1741 QualType qType = op->getType();
1742
Chris Lattner7931f4a2007-07-31 16:53:04 +00001743 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001744 // Note that per both C89 and C99, this is always legal, even
1745 // if ptype is an incomplete type or void.
1746 // It would be possible to warn about dereferencing a
1747 // void pointer, but it's completely well-defined,
1748 // and such a warning is unlikely to catch any mistakes.
1749 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001750 }
1751 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1752 qType.getAsString(), op->getSourceRange());
1753 return QualType();
1754}
1755
1756static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1757 tok::TokenKind Kind) {
1758 BinaryOperator::Opcode Opc;
1759 switch (Kind) {
1760 default: assert(0 && "Unknown binop!");
1761 case tok::star: Opc = BinaryOperator::Mul; break;
1762 case tok::slash: Opc = BinaryOperator::Div; break;
1763 case tok::percent: Opc = BinaryOperator::Rem; break;
1764 case tok::plus: Opc = BinaryOperator::Add; break;
1765 case tok::minus: Opc = BinaryOperator::Sub; break;
1766 case tok::lessless: Opc = BinaryOperator::Shl; break;
1767 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1768 case tok::lessequal: Opc = BinaryOperator::LE; break;
1769 case tok::less: Opc = BinaryOperator::LT; break;
1770 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1771 case tok::greater: Opc = BinaryOperator::GT; break;
1772 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1773 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1774 case tok::amp: Opc = BinaryOperator::And; break;
1775 case tok::caret: Opc = BinaryOperator::Xor; break;
1776 case tok::pipe: Opc = BinaryOperator::Or; break;
1777 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1778 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1779 case tok::equal: Opc = BinaryOperator::Assign; break;
1780 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1781 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1782 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1783 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1784 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1785 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1786 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1787 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1788 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1789 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1790 case tok::comma: Opc = BinaryOperator::Comma; break;
1791 }
1792 return Opc;
1793}
1794
1795static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1796 tok::TokenKind Kind) {
1797 UnaryOperator::Opcode Opc;
1798 switch (Kind) {
1799 default: assert(0 && "Unknown unary op!");
1800 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1801 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1802 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1803 case tok::star: Opc = UnaryOperator::Deref; break;
1804 case tok::plus: Opc = UnaryOperator::Plus; break;
1805 case tok::minus: Opc = UnaryOperator::Minus; break;
1806 case tok::tilde: Opc = UnaryOperator::Not; break;
1807 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1808 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1809 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1810 case tok::kw___real: Opc = UnaryOperator::Real; break;
1811 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1812 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1813 }
1814 return Opc;
1815}
1816
1817// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001818Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001819 ExprTy *LHS, ExprTy *RHS) {
1820 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1821 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1822
Steve Naroff87d58b42007-09-16 03:34:24 +00001823 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1824 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001825
1826 QualType ResultTy; // Result type of the binary operator.
1827 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1828
1829 switch (Opc) {
1830 default:
1831 assert(0 && "Unknown binary expr!");
1832 case BinaryOperator::Assign:
1833 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1834 break;
1835 case BinaryOperator::Mul:
1836 case BinaryOperator::Div:
1837 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1838 break;
1839 case BinaryOperator::Rem:
1840 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1841 break;
1842 case BinaryOperator::Add:
1843 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1844 break;
1845 case BinaryOperator::Sub:
1846 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1847 break;
1848 case BinaryOperator::Shl:
1849 case BinaryOperator::Shr:
1850 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1851 break;
1852 case BinaryOperator::LE:
1853 case BinaryOperator::LT:
1854 case BinaryOperator::GE:
1855 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001856 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001857 break;
1858 case BinaryOperator::EQ:
1859 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001860 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001861 break;
1862 case BinaryOperator::And:
1863 case BinaryOperator::Xor:
1864 case BinaryOperator::Or:
1865 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1866 break;
1867 case BinaryOperator::LAnd:
1868 case BinaryOperator::LOr:
1869 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1870 break;
1871 case BinaryOperator::MulAssign:
1872 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001873 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001874 if (!CompTy.isNull())
1875 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1876 break;
1877 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001878 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001879 if (!CompTy.isNull())
1880 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1881 break;
1882 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001883 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001884 if (!CompTy.isNull())
1885 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1886 break;
1887 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001888 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001889 if (!CompTy.isNull())
1890 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1891 break;
1892 case BinaryOperator::ShlAssign:
1893 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001894 CompTy = CheckShiftOperands(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::AndAssign:
1899 case BinaryOperator::XorAssign:
1900 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001901 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001902 if (!CompTy.isNull())
1903 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1904 break;
1905 case BinaryOperator::Comma:
1906 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1907 break;
1908 }
1909 if (ResultTy.isNull())
1910 return true;
1911 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001912 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001913 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001914 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001915}
1916
1917// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001918Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001919 ExprTy *input) {
1920 Expr *Input = (Expr*)input;
1921 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1922 QualType resultType;
1923 switch (Opc) {
1924 default:
1925 assert(0 && "Unimplemented unary expr!");
1926 case UnaryOperator::PreInc:
1927 case UnaryOperator::PreDec:
1928 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1929 break;
1930 case UnaryOperator::AddrOf:
1931 resultType = CheckAddressOfOperand(Input, OpLoc);
1932 break;
1933 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00001934 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00001935 resultType = CheckIndirectionOperand(Input, OpLoc);
1936 break;
1937 case UnaryOperator::Plus:
1938 case UnaryOperator::Minus:
1939 UsualUnaryConversions(Input);
1940 resultType = Input->getType();
1941 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1942 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1943 resultType.getAsString());
1944 break;
1945 case UnaryOperator::Not: // bitwise complement
1946 UsualUnaryConversions(Input);
1947 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001948 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1949 if (!resultType->isIntegerType()) {
1950 if (resultType->isComplexType())
1951 // C99 does not support '~' for complex conjugation.
1952 Diag(OpLoc, diag::ext_integer_complement_complex,
1953 resultType.getAsString());
1954 else
1955 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1956 resultType.getAsString());
1957 }
Chris Lattner4b009652007-07-25 00:24:17 +00001958 break;
1959 case UnaryOperator::LNot: // logical negation
1960 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1961 DefaultFunctionArrayConversion(Input);
1962 resultType = Input->getType();
1963 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1964 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1965 resultType.getAsString());
1966 // LNot always has type int. C99 6.5.3.3p5.
1967 resultType = Context.IntTy;
1968 break;
1969 case UnaryOperator::SizeOf:
1970 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1971 break;
1972 case UnaryOperator::AlignOf:
1973 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1974 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001975 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001976 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001977 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001978 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001979 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001980 resultType = Input->getType();
1981 break;
1982 }
1983 if (resultType.isNull())
1984 return true;
1985 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1986}
1987
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001988/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1989Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001990 SourceLocation LabLoc,
1991 IdentifierInfo *LabelII) {
1992 // Look up the record for this label identifier.
1993 LabelStmt *&LabelDecl = LabelMap[LabelII];
1994
1995 // If we haven't seen this label yet, create a forward reference.
1996 if (LabelDecl == 0)
1997 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1998
1999 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002000 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2001 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002002}
2003
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002004Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002005 SourceLocation RPLoc) { // "({..})"
2006 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2007 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2008 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2009
2010 // FIXME: there are a variety of strange constraints to enforce here, for
2011 // example, it is not possible to goto into a stmt expression apparently.
2012 // More semantic analysis is needed.
2013
2014 // FIXME: the last statement in the compount stmt has its value used. We
2015 // should not warn about it being unused.
2016
2017 // If there are sub stmts in the compound stmt, take the type of the last one
2018 // as the type of the stmtexpr.
2019 QualType Ty = Context.VoidTy;
2020
2021 if (!Compound->body_empty())
2022 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
2023 Ty = LastExpr->getType();
2024
2025 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2026}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002027
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002028Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002029 SourceLocation TypeLoc,
2030 TypeTy *argty,
2031 OffsetOfComponent *CompPtr,
2032 unsigned NumComponents,
2033 SourceLocation RPLoc) {
2034 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2035 assert(!ArgTy.isNull() && "Missing type argument!");
2036
2037 // We must have at least one component that refers to the type, and the first
2038 // one is known to be a field designator. Verify that the ArgTy represents
2039 // a struct/union/class.
2040 if (!ArgTy->isRecordType())
2041 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2042
2043 // Otherwise, create a compound literal expression as the base, and
2044 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002045 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002046
Chris Lattnerb37522e2007-08-31 21:49:13 +00002047 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2048 // GCC extension, diagnose them.
2049 if (NumComponents != 1)
2050 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2051 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2052
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002053 for (unsigned i = 0; i != NumComponents; ++i) {
2054 const OffsetOfComponent &OC = CompPtr[i];
2055 if (OC.isBrackets) {
2056 // Offset of an array sub-field. TODO: Should we allow vector elements?
2057 const ArrayType *AT = Res->getType()->getAsArrayType();
2058 if (!AT) {
2059 delete Res;
2060 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2061 Res->getType().getAsString());
2062 }
2063
Chris Lattner2af6a802007-08-30 17:59:59 +00002064 // FIXME: C++: Verify that operator[] isn't overloaded.
2065
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002066 // C99 6.5.2.1p1
2067 Expr *Idx = static_cast<Expr*>(OC.U.E);
2068 if (!Idx->getType()->isIntegerType())
2069 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2070 Idx->getSourceRange());
2071
2072 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2073 continue;
2074 }
2075
2076 const RecordType *RC = Res->getType()->getAsRecordType();
2077 if (!RC) {
2078 delete Res;
2079 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2080 Res->getType().getAsString());
2081 }
2082
2083 // Get the decl corresponding to this.
2084 RecordDecl *RD = RC->getDecl();
2085 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2086 if (!MemberDecl)
2087 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2088 OC.U.IdentInfo->getName(),
2089 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002090
2091 // FIXME: C++: Verify that MemberDecl isn't a static field.
2092 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002093 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2094 // matter here.
2095 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002096 }
2097
2098 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2099 BuiltinLoc);
2100}
2101
2102
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002103Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002104 TypeTy *arg1, TypeTy *arg2,
2105 SourceLocation RPLoc) {
2106 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2107 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2108
2109 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2110
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002111 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002112}
2113
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002114Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002115 ExprTy *expr1, ExprTy *expr2,
2116 SourceLocation RPLoc) {
2117 Expr *CondExpr = static_cast<Expr*>(cond);
2118 Expr *LHSExpr = static_cast<Expr*>(expr1);
2119 Expr *RHSExpr = static_cast<Expr*>(expr2);
2120
2121 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2122
2123 // The conditional expression is required to be a constant expression.
2124 llvm::APSInt condEval(32);
2125 SourceLocation ExpLoc;
2126 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2127 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2128 CondExpr->getSourceRange());
2129
2130 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2131 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2132 RHSExpr->getType();
2133 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2134}
2135
Nate Begemanbd881ef2008-01-30 20:50:20 +00002136/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002137/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002138/// The number of arguments has already been validated to match the number of
2139/// arguments in FnType.
2140static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002141 unsigned NumParams = FnType->getNumArgs();
2142 for (unsigned i = 0; i != NumParams; ++i)
Nate Begemanbd881ef2008-01-30 20:50:20 +00002143 if (Args[i]->getType().getCanonicalType() !=
2144 FnType->getArgType(i).getCanonicalType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002145 return false;
2146 return true;
2147}
2148
2149Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2150 SourceLocation *CommaLocs,
2151 SourceLocation BuiltinLoc,
2152 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002153 // __builtin_overload requires at least 2 arguments
2154 if (NumArgs < 2)
2155 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2156 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002157
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002158 // The first argument is required to be a constant expression. It tells us
2159 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002160 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002161 Expr *NParamsExpr = Args[0];
2162 llvm::APSInt constEval(32);
2163 SourceLocation ExpLoc;
2164 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2165 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2166 NParamsExpr->getSourceRange());
2167
2168 // Verify that the number of parameters is > 0
2169 unsigned NumParams = constEval.getZExtValue();
2170 if (NumParams == 0)
2171 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2172 NParamsExpr->getSourceRange());
2173 // Verify that we have at least 1 + NumParams arguments to the builtin.
2174 if ((NumParams + 1) > NumArgs)
2175 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2176 SourceRange(BuiltinLoc, RParenLoc));
2177
2178 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002179 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002180 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002181 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2182 // UsualUnaryConversions will convert the function DeclRefExpr into a
2183 // pointer to function.
2184 Expr *Fn = UsualUnaryConversions(Args[i]);
2185 FunctionTypeProto *FnType = 0;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002186 if (const PointerType *PT = Fn->getType()->getAsPointerType()) {
2187 QualType PointeeType = PT->getPointeeType().getCanonicalType();
2188 FnType = dyn_cast<FunctionTypeProto>(PointeeType);
2189 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002190
2191 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2192 // parameters, and the number of parameters must match the value passed to
2193 // the builtin.
2194 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002195 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2196 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002197
2198 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002199 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002200 // If they match, return a new OverloadExpr.
Nate Begemanc6078c92008-01-31 05:38:29 +00002201 if (ExprsMatchFnType(Args+1, FnType)) {
2202 if (OE)
2203 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2204 OE->getFn()->getSourceRange());
2205 // Remember our match, and continue processing the remaining arguments
2206 // to catch any errors.
2207 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2208 BuiltinLoc, RParenLoc);
2209 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002210 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002211 // Return the newly created OverloadExpr node, if we succeded in matching
2212 // exactly one of the candidate functions.
2213 if (OE)
2214 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002215
2216 // If we didn't find a matching function Expr in the __builtin_overload list
2217 // the return an error.
2218 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002219 for (unsigned i = 0; i != NumParams; ++i) {
2220 if (i != 0) typeNames += ", ";
2221 typeNames += Args[i+1]->getType().getAsString();
2222 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002223
2224 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2225 SourceRange(BuiltinLoc, RParenLoc));
2226}
2227
Anders Carlsson36760332007-10-15 20:28:48 +00002228Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2229 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002230 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002231 Expr *E = static_cast<Expr*>(expr);
2232 QualType T = QualType::getFromOpaquePtr(type);
2233
2234 InitBuiltinVaListType();
2235
Chris Lattner005ed752008-01-04 18:04:52 +00002236 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2237 != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002238 return Diag(E->getLocStart(),
2239 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2240 E->getType().getAsString(),
2241 E->getSourceRange());
2242
2243 // FIXME: Warn if a non-POD type is passed in.
2244
2245 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2246}
2247
Chris Lattner005ed752008-01-04 18:04:52 +00002248bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2249 SourceLocation Loc,
2250 QualType DstType, QualType SrcType,
2251 Expr *SrcExpr, const char *Flavor) {
2252 // Decode the result (notice that AST's are still created for extensions).
2253 bool isInvalid = false;
2254 unsigned DiagKind;
2255 switch (ConvTy) {
2256 default: assert(0 && "Unknown conversion type");
2257 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002258 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002259 DiagKind = diag::ext_typecheck_convert_pointer_int;
2260 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002261 case IntToPointer:
2262 DiagKind = diag::ext_typecheck_convert_int_pointer;
2263 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002264 case IncompatiblePointer:
2265 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2266 break;
2267 case FunctionVoidPointer:
2268 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2269 break;
2270 case CompatiblePointerDiscardsQualifiers:
2271 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2272 break;
2273 case Incompatible:
2274 DiagKind = diag::err_typecheck_convert_incompatible;
2275 isInvalid = true;
2276 break;
2277 }
2278
2279 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2280 SrcExpr->getSourceRange());
2281 return isInvalid;
2282}
2283