blob: e5ac14e092c568291ff7654aa77bfda2ea6502cb [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"
Chris Lattner3e254fb2008-04-08 04:40:51 +000018#include "clang/AST/ExprCXX.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000019#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Chris Lattner83bd5eb2007-12-28 05:29:59 +000024#include "llvm/ADT/OwningPtr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000026#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Steve Naroff87d58b42007-09-16 03:34:24 +000029/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000030/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
31/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
32/// multiple tokens. However, the common case is that StringToks points to one
33/// string.
34///
35Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000036Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000037 assert(NumStringToks && "Must have at least one string!");
38
39 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
40 if (Literal.hadError)
41 return ExprResult(true);
42
43 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
44 for (unsigned i = 0; i != NumStringToks; ++i)
45 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +000046
47 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000048 if (Literal.Pascal && Literal.GetStringLength() > 256)
49 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
50 SourceRange(StringToks[0].getLocation(),
51 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000052
Chris Lattnera6dcce32008-02-11 00:02:17 +000053 QualType StrTy = Context.CharTy;
54 // FIXME: handle wchar_t
55 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
56
57 // Get an array type for the string, according to C99 6.4.5. This includes
58 // the nul terminator character as well as the string length for pascal
59 // strings.
60 StrTy = Context.getConstantArrayType(StrTy,
61 llvm::APInt(32, Literal.GetStringLength()+1),
62 ArrayType::Normal, 0);
63
Chris Lattner4b009652007-07-25 00:24:17 +000064 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
65 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +000066 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000067 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000068 StringToks[NumStringToks-1].getLocation());
69}
70
71
Steve Naroff0acc9c92007-09-15 18:49:24 +000072/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000073/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +000074/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000075Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000076 IdentifierInfo &II,
77 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +000078 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +000079 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +000080
81 // If this reference is in an Objective-C method, then ivar lookup happens as
82 // well.
83 if (CurMethodDecl) {
Steve Naroffe57c21a2008-04-01 23:04:06 +000084 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +000085 // There are two cases to handle here. 1) scoped lookup could have failed,
86 // in which case we should look for an ivar. 2) scoped lookup could have
87 // found a decl, but that decl is outside the current method (i.e. a global
88 // variable). In these two cases, we do a lookup for an ivar with this
89 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +000090 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +000091 ObjCInterfaceDecl *IFace = CurMethodDecl->getClassInterface(), *DeclClass;
92 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II, DeclClass)) {
93 // FIXME: This should use a new expr for a direct reference, don't turn
94 // this into Self->ivar, just return a BareIVarExpr or something.
95 IdentifierInfo &II = Context.Idents.get("self");
96 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
97 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
98 static_cast<Expr*>(SelfExpr.Val), true, true);
99 }
100 }
101 }
102
Chris Lattner4b009652007-07-25 00:24:17 +0000103 if (D == 0) {
104 // Otherwise, this could be an implicitly declared function reference (legal
105 // in C90, extension in C99).
106 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000107 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000108 D = ImplicitlyDefineFunction(Loc, II, S);
109 else {
110 // If this name wasn't predeclared and if this is not a function call,
111 // diagnose the problem.
112 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
113 }
114 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000115
Steve Naroff91b03f72007-08-28 03:03:08 +0000116 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneree4c3bf2008-02-29 16:48:43 +0000117 // check if referencing an identifier with __attribute__((deprecated)).
118 if (VD->getAttr<DeprecatedAttr>())
119 Diag(Loc, diag::warn_deprecated, VD->getName());
120
Steve Naroffcae537d2007-08-28 18:45:29 +0000121 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000122 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000123 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000124 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000125 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000126
Chris Lattner4b009652007-07-25 00:24:17 +0000127 if (isa<TypedefDecl>(D))
128 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000129 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000130 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000131 if (isa<NamespaceDecl>(D))
132 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000133
134 assert(0 && "Invalid decl");
135 abort();
136}
137
Steve Naroff87d58b42007-09-16 03:34:24 +0000138Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000139 tok::TokenKind Kind) {
140 PreDefinedExpr::IdentType IT;
141
142 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000143 default: assert(0 && "Unknown simple primary expr!");
144 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
145 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
146 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000147 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000148
149 // Verify that this is in a function context.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000150 if (CurFunctionDecl == 0 && CurMethodDecl == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000151 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000152
Chris Lattner7e637512008-01-12 08:14:25 +0000153 // Pre-defined identifiers are of type char[x], where x is the length of the
154 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000155 unsigned Length;
156 if (CurFunctionDecl)
157 Length = CurFunctionDecl->getIdentifier()->getLength();
158 else
Fariborz Jahaniandcecd5c2008-01-17 17:37:26 +0000159 Length = CurMethodDecl->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000160
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000161 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000162 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000163 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner7e637512008-01-12 08:14:25 +0000164 return new PreDefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000165}
166
Steve Naroff87d58b42007-09-16 03:34:24 +0000167Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000168 llvm::SmallString<16> CharBuffer;
169 CharBuffer.resize(Tok.getLength());
170 const char *ThisTokBegin = &CharBuffer[0];
171 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
172
173 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
174 Tok.getLocation(), PP);
175 if (Literal.hadError())
176 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000177
178 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
179
180 return new CharacterLiteral(Literal.getValue(), type, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000181}
182
Steve Naroff87d58b42007-09-16 03:34:24 +0000183Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000184 // fast path for a single digit (which is quite common). A single digit
185 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
186 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000187 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000188
Chris Lattner8cd0e932008-03-05 18:54:05 +0000189 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000190 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000191 Context.IntTy,
192 Tok.getLocation()));
193 }
194 llvm::SmallString<512> IntegerBuffer;
195 IntegerBuffer.resize(Tok.getLength());
196 const char *ThisTokBegin = &IntegerBuffer[0];
197
198 // Get the spelling of the token, which eliminates trigraphs, etc.
199 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
200 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
201 Tok.getLocation(), PP);
202 if (Literal.hadError)
203 return ExprResult(true);
204
Chris Lattner1de66eb2007-08-26 03:42:43 +0000205 Expr *Res;
206
207 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000208 QualType Ty;
209 const llvm::fltSemantics *Format;
Chris Lattner858eece2007-09-22 18:29:59 +0000210
211 if (Literal.isFloat) {
212 Ty = Context.FloatTy;
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000213 Format = Context.Target.getFloatFormat();
214 } else if (!Literal.isLong) {
Chris Lattner858eece2007-09-22 18:29:59 +0000215 Ty = Context.DoubleTy;
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000216 Format = Context.Target.getDoubleFormat();
217 } else {
218 Ty = Context.LongDoubleTy;
219 Format = Context.Target.getLongDoubleFormat();
Chris Lattner858eece2007-09-22 18:29:59 +0000220 }
221
Ted Kremenekddedbe22007-11-29 00:56:49 +0000222 // isExact will be set by GetFloatValue().
223 bool isExact = false;
224
225 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
226 Ty, Tok.getLocation());
227
Chris Lattner1de66eb2007-08-26 03:42:43 +0000228 } else if (!Literal.isIntegerLiteral()) {
229 return ExprResult(true);
230 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000231 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000232
Neil Booth7421e9c2007-08-29 22:00:19 +0000233 // long long is a C99 feature.
234 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000235 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000236 Diag(Tok.getLocation(), diag::ext_longlong);
237
Chris Lattner4b009652007-07-25 00:24:17 +0000238 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000239 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000240
241 if (Literal.GetIntegerValue(ResultVal)) {
242 // If this value didn't fit into uintmax_t, warn and force to ull.
243 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000244 Ty = Context.UnsignedLongLongTy;
245 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000246 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000247 } else {
248 // If this value fits into a ULL, try to figure out what else it fits into
249 // according to the rules of C99 6.4.4.1p5.
250
251 // Octal, Hexadecimal, and integers with a U suffix are allowed to
252 // be an unsigned int.
253 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
254
255 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000256 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000257 if (!Literal.isLong && !Literal.isLongLong) {
258 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000259 unsigned IntSize = Context.Target.getIntWidth();
260
Chris Lattner4b009652007-07-25 00:24:17 +0000261 // Does it fit in a unsigned int?
262 if (ResultVal.isIntN(IntSize)) {
263 // Does it fit in a signed int?
264 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000265 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000266 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000267 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000268 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000269 }
Chris Lattner4b009652007-07-25 00:24:17 +0000270 }
271
272 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000273 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000274 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000275
276 // Does it fit in a unsigned long?
277 if (ResultVal.isIntN(LongSize)) {
278 // Does it fit in a signed long?
279 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000280 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000281 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000282 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000283 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000284 }
Chris Lattner4b009652007-07-25 00:24:17 +0000285 }
286
287 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000288 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000289 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000290
291 // Does it fit in a unsigned long long?
292 if (ResultVal.isIntN(LongLongSize)) {
293 // Does it fit in a signed long long?
294 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000295 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000296 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000297 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000298 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000299 }
300 }
301
302 // If we still couldn't decide a type, we probably have something that
303 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000304 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000305 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000306 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000307 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000308 }
Chris Lattnere4068872008-05-09 05:59:00 +0000309
310 if (ResultVal.getBitWidth() != Width)
311 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000312 }
313
Chris Lattner48d7f382008-04-02 04:24:33 +0000314 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000315 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000316
317 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
318 if (Literal.isImaginary)
319 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
320
321 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000322}
323
Steve Naroff87d58b42007-09-16 03:34:24 +0000324Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000325 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000326 Expr *E = (Expr *)Val;
327 assert((E != 0) && "ActOnParenExpr() missing expr");
328 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000329}
330
331/// The UsualUnaryConversions() function is *not* called by this routine.
332/// See C99 6.3.2.1p[2-4] for more details.
333QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
334 SourceLocation OpLoc, bool isSizeof) {
335 // C99 6.5.3.4p1:
336 if (isa<FunctionType>(exprType) && isSizeof)
337 // alignof(function) is allowed.
338 Diag(OpLoc, diag::ext_sizeof_function_type);
339 else if (exprType->isVoidType())
340 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
341 else if (exprType->isIncompleteType()) {
342 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
343 diag::err_alignof_incomplete_type,
344 exprType.getAsString());
345 return QualType(); // error
346 }
347 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
348 return Context.getSizeType();
349}
350
351Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000352ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000353 SourceLocation LPLoc, TypeTy *Ty,
354 SourceLocation RPLoc) {
355 // If error parsing type, ignore.
356 if (Ty == 0) return true;
357
358 // Verify that this is a valid expression.
359 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
360
361 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
362
363 if (resultType.isNull())
364 return true;
365 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
366}
367
Chris Lattner5110ad52007-08-24 21:41:10 +0000368QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000369 DefaultFunctionArrayConversion(V);
370
Chris Lattnera16e42d2007-08-26 05:39:26 +0000371 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000372 if (const ComplexType *CT = V->getType()->getAsComplexType())
373 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000374
375 // Otherwise they pass through real integer and floating point types here.
376 if (V->getType()->isArithmeticType())
377 return V->getType();
378
379 // Reject anything else.
380 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
381 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000382}
383
384
Chris Lattner4b009652007-07-25 00:24:17 +0000385
Steve Naroff87d58b42007-09-16 03:34:24 +0000386Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000387 tok::TokenKind Kind,
388 ExprTy *Input) {
389 UnaryOperator::Opcode Opc;
390 switch (Kind) {
391 default: assert(0 && "Unknown unary op!");
392 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
393 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
394 }
395 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
396 if (result.isNull())
397 return true;
398 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
399}
400
401Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000402ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000403 ExprTy *Idx, SourceLocation RLoc) {
404 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
405
406 // Perform default conversions.
407 DefaultFunctionArrayConversion(LHSExp);
408 DefaultFunctionArrayConversion(RHSExp);
409
410 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
411
412 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000413 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000414 // in the subscript position. As a result, we need to derive the array base
415 // and index from the expression types.
416 Expr *BaseExpr, *IndexExpr;
417 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000418 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000419 BaseExpr = LHSExp;
420 IndexExpr = RHSExp;
421 // FIXME: need to deal with const...
422 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000423 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000424 // Handle the uncommon case of "123[Ptr]".
425 BaseExpr = RHSExp;
426 IndexExpr = LHSExp;
427 // FIXME: need to deal with const...
428 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000429 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
430 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000431 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000432
433 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000434 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
435 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000436 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000437 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000438 // FIXME: need to deal with const...
439 ResultType = VTy->getElementType();
440 } else {
441 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
442 RHSExp->getSourceRange());
443 }
444 // C99 6.5.2.1p1
445 if (!IndexExpr->getType()->isIntegerType())
446 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
447 IndexExpr->getSourceRange());
448
449 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
450 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000451 // void (*)(int)) and pointers to incomplete types. Functions are not
452 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000453 if (!ResultType->isObjectType())
454 return Diag(BaseExpr->getLocStart(),
455 diag::err_typecheck_subscript_not_object,
456 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
457
458 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
459}
460
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000461QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000462CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000463 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000464 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000465
466 // This flag determines whether or not the component is to be treated as a
467 // special name, or a regular GLSL-style component access.
468 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000469
470 // The vector accessor can't exceed the number of elements.
471 const char *compStr = CompName.getName();
472 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000473 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000474 baseType.getAsString(), SourceRange(CompLoc));
475 return QualType();
476 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000477
478 // Check that we've found one of the special components, or that the component
479 // names must come from the same set.
480 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
481 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
482 SpecialComponent = true;
483 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000484 do
485 compStr++;
486 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
487 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
488 do
489 compStr++;
490 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
491 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
492 do
493 compStr++;
494 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
495 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000496
Nate Begemanc8e51f82008-05-09 06:41:27 +0000497 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000498 // We didn't get to the end of the string. This means the component names
499 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000500 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000501 std::string(compStr,compStr+1), SourceRange(CompLoc));
502 return QualType();
503 }
504 // Each component accessor can't exceed the vector type.
505 compStr = CompName.getName();
506 while (*compStr) {
507 if (vecType->isAccessorWithinNumElements(*compStr))
508 compStr++;
509 else
510 break;
511 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000512 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000513 // We didn't get to the end of the string. This means a component accessor
514 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000515 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000516 baseType.getAsString(), SourceRange(CompLoc));
517 return QualType();
518 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000519
520 // If we have a special component name, verify that the current vector length
521 // is an even number, since all special component names return exactly half
522 // the elements.
523 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
524 return QualType();
525 }
526
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000527 // The component accessor looks fine - now we need to compute the actual type.
528 // The vector type is implied by the component accessor. For example,
529 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000530 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
531 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
532 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000533 if (CompSize == 1)
534 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000535
Nate Begemanaf6ed502008-04-18 23:10:10 +0000536 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000537 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000538 // diagostics look bad. We want extended vector types to appear built-in.
539 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
540 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
541 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000542 }
543 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000544}
545
Chris Lattner4b009652007-07-25 00:24:17 +0000546Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000547ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000548 tok::TokenKind OpKind, SourceLocation MemberLoc,
549 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000550 Expr *BaseExpr = static_cast<Expr *>(Base);
551 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000552
553 // Perform default conversions.
554 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000555
Steve Naroff2cb66382007-07-26 03:11:44 +0000556 QualType BaseType = BaseExpr->getType();
557 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000558
Chris Lattner4b009652007-07-25 00:24:17 +0000559 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000560 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000561 BaseType = PT->getPointeeType();
562 else
563 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
564 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000565 }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000566 // The base type is either a record or an ExtVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000567 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000568 RecordDecl *RDecl = RTy->getDecl();
569 if (RTy->isIncompleteType())
570 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
571 BaseExpr->getSourceRange());
572 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000573 FieldDecl *MemberDecl = RDecl->getMember(&Member);
574 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000575 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
576 SourceRange(MemberLoc));
Eli Friedman76b49832008-02-06 22:48:16 +0000577
578 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000579 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000580 QualType MemberType = MemberDecl->getType();
581 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000582 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000583 MemberType = MemberType.getQualifiedType(combinedQualifiers);
584
585 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl,
586 MemberLoc, MemberType);
Nate Begemanaf6ed502008-04-18 23:10:10 +0000587 } else if (BaseType->isExtVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000588 // Component access limited to variables (reject vec4.rg.g).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000589 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
590 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000591 return Diag(OpLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000592 SourceRange(MemberLoc));
Nate Begemanaf6ed502008-04-18 23:10:10 +0000593 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000594 if (ret.isNull())
595 return true;
Nate Begemanaf6ed502008-04-18 23:10:10 +0000596 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Ted Kremenek42730c52008-01-07 19:49:32 +0000597 } else if (BaseType->isObjCInterfaceType()) {
598 ObjCInterfaceDecl *IFace;
599 if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
600 IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000601 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000602 IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
603 ObjCInterfaceDecl *clsDeclared;
604 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000605 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
606 OpKind==tok::arrow);
607 }
608 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
609 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000610}
611
Steve Naroff87d58b42007-09-16 03:34:24 +0000612/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000613/// This provides the location of the left/right parens and a list of comma
614/// locations.
615Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000616ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000617 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000618 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
619 Expr *Fn = static_cast<Expr *>(fn);
620 Expr **Args = reinterpret_cast<Expr**>(args);
621 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +0000622 FunctionDecl *FDecl = NULL;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000623
624 // Promote the function operand.
625 UsualUnaryConversions(Fn);
626
627 // If we're directly calling a function, get the declaration for
628 // that function.
629 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
630 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
631 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
632
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000633 // Make the call expr early, before semantic checks. This guarantees cleanup
634 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +0000635 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000636 Context.BoolTy, RParenLoc));
637
Chris Lattner4b009652007-07-25 00:24:17 +0000638 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
639 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000640 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000641 if (PT == 0)
642 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
643 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000644 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
645 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000646 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
647 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000648
649 // We know the result type of the call, set it.
650 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000651
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000652 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000653 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
654 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000655 unsigned NumArgsInProto = Proto->getNumArgs();
656 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000657
Chris Lattner3e254fb2008-04-08 04:40:51 +0000658 // If too few arguments are available (and we don't have default
659 // arguments for the remaining parameters), don't make the call.
660 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +0000661 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000662 // Use default arguments for missing arguments
663 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +0000664 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000665 } else
666 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
667 Fn->getSourceRange());
668 }
669
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000670 // If too many are passed and not variadic, error on the extras and drop
671 // them.
672 if (NumArgs > NumArgsInProto) {
673 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000674 Diag(Args[NumArgsInProto]->getLocStart(),
675 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
676 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000677 Args[NumArgs-1]->getLocEnd()));
678 // This deletes the extra arguments.
679 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000680 }
681 NumArgsToCheck = NumArgsInProto;
682 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000683
Chris Lattner4b009652007-07-25 00:24:17 +0000684 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000685 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +0000686 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000687
688 Expr *Arg;
689 if (i < NumArgs)
690 Arg = Args[i];
691 else
692 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +0000693 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000694
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000695 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +0000696 AssignConvertType ConvTy =
697 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000698 TheCall->setArg(i, Arg);
699
Chris Lattner005ed752008-01-04 18:04:52 +0000700 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
701 ArgType, Arg, "passing"))
702 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000703 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000704
705 // If this is a variadic call, handle args passed through "...".
706 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +0000707 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000708 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
709 Expr *Arg = Args[i];
710 DefaultArgumentPromotion(Arg);
711 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000712 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000713 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000714 } else {
715 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
716
Steve Naroffdb65e052007-08-28 23:30:39 +0000717 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000718 for (unsigned i = 0; i != NumArgs; i++) {
719 Expr *Arg = Args[i];
720 DefaultArgumentPromotion(Arg);
721 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000722 }
Chris Lattner4b009652007-07-25 00:24:17 +0000723 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000724
Chris Lattner2e64c072007-08-10 20:18:51 +0000725 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +0000726 if (FDecl)
727 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +0000728
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000729 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000730}
731
732Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000733ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000734 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000735 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000736 QualType literalType = QualType::getFromOpaquePtr(Ty);
737 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000738 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000739 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000740
Steve Naroffcb69fb72007-12-10 22:44:33 +0000741 // FIXME: add more semantic analysis (C99 6.5.2.5).
Steve Narofff0b23542008-01-10 22:15:12 +0000742 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +0000743 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +0000744
745 bool isFileScope = !CurFunctionDecl && !CurMethodDecl;
746 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +0000747 if (CheckForConstantInitializer(literalExpr, literalType))
748 return true;
749 }
Steve Naroffbe37fc02008-01-14 18:19:28 +0000750 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000751}
752
753Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000754ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000755 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000756 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000757
Steve Naroff0acc9c92007-09-15 18:49:24 +0000758 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000759 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000760
Chris Lattner48d7f382008-04-02 04:24:33 +0000761 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
762 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
763 return E;
Chris Lattner4b009652007-07-25 00:24:17 +0000764}
765
Chris Lattnerd1f26b32007-12-20 00:44:32 +0000766bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000767 assert(VectorTy->isVectorType() && "Not a vector type!");
768
769 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000770 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000771 return Diag(R.getBegin(),
772 Ty->isVectorType() ?
773 diag::err_invalid_conversion_between_vectors :
774 diag::err_invalid_conversion_between_vector_and_integer,
775 VectorTy.getAsString().c_str(),
776 Ty.getAsString().c_str(), R);
777 } else
778 return Diag(R.getBegin(),
779 diag::err_invalid_conversion_between_vector_and_scalar,
780 VectorTy.getAsString().c_str(),
781 Ty.getAsString().c_str(), R);
782
783 return false;
784}
785
Chris Lattner4b009652007-07-25 00:24:17 +0000786Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000787ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000788 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000789 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000790
791 Expr *castExpr = static_cast<Expr*>(Op);
792 QualType castType = QualType::getFromOpaquePtr(Ty);
793
Steve Naroff68adb482007-08-31 00:32:44 +0000794 UsualUnaryConversions(castExpr);
795
Chris Lattner4b009652007-07-25 00:24:17 +0000796 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
797 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000798 if (!castType->isVoidType()) { // Cast to void allows any expr type.
Steve Narofff459ee52008-01-24 22:55:05 +0000799 if (!castType->isScalarType() && !castType->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000800 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
801 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Steve Narofff459ee52008-01-24 22:55:05 +0000802 if (!castExpr->getType()->isScalarType() &&
803 !castExpr->getType()->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000804 return Diag(castExpr->getLocStart(),
805 diag::err_typecheck_expect_scalar_operand,
806 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000807
808 if (castExpr->getType()->isVectorType()) {
809 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
810 castExpr->getType(), castType))
811 return true;
812 } else if (castType->isVectorType()) {
813 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
814 castType, castExpr->getType()))
815 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000816 }
Chris Lattner4b009652007-07-25 00:24:17 +0000817 }
818 return new CastExpr(castType, castExpr, LParenLoc);
819}
820
Chris Lattner98a425c2007-11-26 01:40:58 +0000821/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
822/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000823inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
824 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
825 UsualUnaryConversions(cond);
826 UsualUnaryConversions(lex);
827 UsualUnaryConversions(rex);
828 QualType condT = cond->getType();
829 QualType lexT = lex->getType();
830 QualType rexT = rex->getType();
831
832 // first, check the condition.
833 if (!condT->isScalarType()) { // C99 6.5.15p2
834 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
835 condT.getAsString());
836 return QualType();
837 }
Chris Lattner992ae932008-01-06 22:42:25 +0000838
839 // Now check the two expressions.
840
841 // If both operands have arithmetic type, do the usual arithmetic conversions
842 // to find a common type: C99 6.5.15p3,5.
843 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000844 UsualArithmeticConversions(lex, rex);
845 return lex->getType();
846 }
Chris Lattner992ae932008-01-06 22:42:25 +0000847
848 // If both operands are the same structure or union type, the result is that
849 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000850 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +0000851 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +0000852 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +0000853 // "If both the operands have structure or union type, the result has
854 // that type." This implies that CV qualifiers are dropped.
855 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000856 }
Chris Lattner992ae932008-01-06 22:42:25 +0000857
858 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +0000859 // The following || allows only one side to be void (a GCC-ism).
860 if (lexT->isVoidType() || rexT->isVoidType()) {
861 if (!lexT->isVoidType())
862 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
863 rex->getSourceRange());
864 if (!rexT->isVoidType())
865 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
866 lex->getSourceRange());
Chris Lattner992ae932008-01-06 22:42:25 +0000867 return lexT.getUnqualifiedType();
Steve Naroff95cb3892008-05-12 21:44:38 +0000868 }
Steve Naroff12ebf272008-01-08 01:11:38 +0000869 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
870 // the type of the other operand."
871 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000872 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000873 return lexT;
874 }
875 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000876 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000877 return rexT;
878 }
Chris Lattner0ac51632008-01-06 22:50:31 +0000879 // Handle the case where both operands are pointers before we handle null
880 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +0000881 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
882 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
883 // get the "pointed to" types
884 QualType lhptee = LHSPT->getPointeeType();
885 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000886
Chris Lattner71225142007-07-31 21:27:01 +0000887 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
888 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +0000889 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +0000890 // Figure out necessary qualifiers (C99 6.5.15p6)
891 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000892 QualType destType = Context.getPointerType(destPointee);
893 ImpCastExprToType(lex, destType); // add qualifiers if necessary
894 ImpCastExprToType(rex, destType); // promote to void*
895 return destType;
896 }
Chris Lattner9db553e2008-04-02 06:59:01 +0000897 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +0000898 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000899 QualType destType = Context.getPointerType(destPointee);
900 ImpCastExprToType(lex, destType); // add qualifiers if necessary
901 ImpCastExprToType(rex, destType); // promote to void*
902 return destType;
903 }
Chris Lattner4b009652007-07-25 00:24:17 +0000904
Steve Naroff85f0dc52007-10-15 20:41:53 +0000905 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
906 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +0000907 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +0000908 lexT.getAsString(), rexT.getAsString(),
909 lex->getSourceRange(), rex->getSourceRange());
Eli Friedman33284862008-01-30 17:02:03 +0000910 // In this situation, we assume void* type. No especially good
911 // reason, but this is what gcc does, and we do have to pick
912 // to get a consistent AST.
913 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
914 ImpCastExprToType(lex, voidPtrTy);
915 ImpCastExprToType(rex, voidPtrTy);
916 return voidPtrTy;
Chris Lattner71225142007-07-31 21:27:01 +0000917 }
918 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000919 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
920 // differently qualified versions of compatible types, the result type is
921 // a pointer to an appropriately qualified version of the *composite*
922 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +0000923 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +0000924 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +0000925 QualType compositeType = lexT;
926 ImpCastExprToType(lex, compositeType);
927 ImpCastExprToType(rex, compositeType);
928 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +0000929 }
Chris Lattner4b009652007-07-25 00:24:17 +0000930 }
Chris Lattner71225142007-07-31 21:27:01 +0000931
Chris Lattner992ae932008-01-06 22:42:25 +0000932 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +0000933 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
934 lexT.getAsString(), rexT.getAsString(),
935 lex->getSourceRange(), rex->getSourceRange());
936 return QualType();
937}
938
Steve Naroff87d58b42007-09-16 03:34:24 +0000939/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000940/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000941Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000942 SourceLocation ColonLoc,
943 ExprTy *Cond, ExprTy *LHS,
944 ExprTy *RHS) {
945 Expr *CondExpr = (Expr *) Cond;
946 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000947
948 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
949 // was the condition.
950 bool isLHSNull = LHSExpr == 0;
951 if (isLHSNull)
952 LHSExpr = CondExpr;
953
Chris Lattner4b009652007-07-25 00:24:17 +0000954 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
955 RHSExpr, QuestionLoc);
956 if (result.isNull())
957 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000958 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
959 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000960}
961
Steve Naroffdb65e052007-08-28 23:30:39 +0000962/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Steve Naroffbbaed752008-01-29 02:42:22 +0000963/// do not have a prototype. Arguments that have type float are promoted to
964/// double. All other argument types are converted by UsualUnaryConversions().
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000965void Sema::DefaultArgumentPromotion(Expr *&Expr) {
966 QualType Ty = Expr->getType();
967 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffdb65e052007-08-28 23:30:39 +0000968
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000969 if (Ty == Context.FloatTy)
Chris Lattnere992d6c2008-01-16 19:17:22 +0000970 ImpCastExprToType(Expr, Context.DoubleTy);
Steve Naroffbbaed752008-01-29 02:42:22 +0000971 else
972 UsualUnaryConversions(Expr);
Steve Naroffdb65e052007-08-28 23:30:39 +0000973}
974
Chris Lattner4b009652007-07-25 00:24:17 +0000975/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Chris Lattner48d7f382008-04-02 04:24:33 +0000976void Sema::DefaultFunctionArrayConversion(Expr *&E) {
977 QualType Ty = E->getType();
978 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000979
Chris Lattner48d7f382008-04-02 04:24:33 +0000980 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
Chris Lattnera05f7d22008-04-02 17:45:06 +0000981 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
Chris Lattner48d7f382008-04-02 04:24:33 +0000982 Ty = E->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000983 }
Chris Lattner48d7f382008-04-02 04:24:33 +0000984 if (Ty->isFunctionType())
985 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner19eb97e2008-04-02 05:18:44 +0000986 else if (Ty->isArrayType())
987 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
Chris Lattner4b009652007-07-25 00:24:17 +0000988}
989
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000990/// UsualUnaryConversions - Performs various conversions that are common to most
Chris Lattner4b009652007-07-25 00:24:17 +0000991/// operators (C99 6.3). The conversions of array and function types are
992/// sometimes surpressed. For example, the array->pointer conversion doesn't
993/// apply if the array is an argument to the sizeof or address (&) operators.
994/// In these instances, this routine should *not* be called.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000995Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
996 QualType Ty = Expr->getType();
997 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000998
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000999 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
Chris Lattnera05f7d22008-04-02 17:45:06 +00001000 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001001 Ty = Expr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001002 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001003 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
Chris Lattnere992d6c2008-01-16 19:17:22 +00001004 ImpCastExprToType(Expr, Context.IntTy);
Chris Lattner4b009652007-07-25 00:24:17 +00001005 else
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001006 DefaultFunctionArrayConversion(Expr);
1007
1008 return Expr;
Chris Lattner4b009652007-07-25 00:24:17 +00001009}
1010
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001011/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +00001012/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1013/// routine returns the first non-arithmetic type found. The client is
1014/// responsible for emitting appropriate error diagnostics.
Chris Lattner48d7f382008-04-02 04:24:33 +00001015/// FIXME: verify the conversion rules for "complex int" are consistent with
1016/// GCC.
Steve Naroff8f708362007-08-24 19:07:16 +00001017QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
1018 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +00001019 if (!isCompAssign) {
1020 UsualUnaryConversions(lhsExpr);
1021 UsualUnaryConversions(rhsExpr);
1022 }
Steve Naroff7438fdf2007-10-18 18:55:53 +00001023 // For conversion purposes, we ignore any qualifiers.
1024 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +00001025 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
1026 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001027
1028 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +00001029 if (lhs == rhs)
1030 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001031
1032 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1033 // The caller can deal with this (e.g. pointer + int).
1034 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001035 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001036
1037 // At this point, we have two different arithmetic types.
1038
1039 // Handle complex types first (C99 6.3.1.8p1).
1040 if (lhs->isComplexType() || rhs->isComplexType()) {
Steve Naroff43001212008-01-15 19:36:10 +00001041 // if we have an integer operand, the result is the complex type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001042 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001043 // convert the rhs to the lhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001044 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001045 return lhs;
Steve Naroff43001212008-01-15 19:36:10 +00001046 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001047 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001048 // convert the lhs to the rhs complex 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 }
Steve Naroff3cf497f2007-08-27 01:27:54 +00001052 // This handles complex/complex, complex/float, or float/complex.
1053 // When both operands are complex, the shorter operand is converted to the
1054 // type of the longer, and that is the type of the result. This corresponds
1055 // to what is done when combining two real floating-point operands.
1056 // The fun begins when size promotion occur across type domains.
1057 // From H&S 6.3.4: When one operand is complex and the other is a real
1058 // floating-point type, the less precise type is converted, within it's
1059 // real or complex domain, to the precision of the other type. For example,
1060 // when combining a "long double" with a "double _Complex", the
1061 // "double _Complex" is promoted to "long double _Complex".
Chris Lattnerd7135b42008-04-06 23:38:49 +00001062 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Naroff45fc9822007-08-27 15:30:22 +00001063
1064 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +00001065 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
1066 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001067 ImpCastExprToType(rhsExpr, rhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001068 } else if (result < 0) { // The right side is bigger, convert lhs.
1069 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
1070 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001071 ImpCastExprToType(lhsExpr, lhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001072 }
1073 // At this point, lhs and rhs have the same rank/size. Now, make sure the
1074 // domains match. This is a requirement for our implementation, C99
1075 // does not require this promotion.
1076 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1077 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001078 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001079 ImpCastExprToType(lhsExpr, rhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001080 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001081 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001082 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001083 ImpCastExprToType(rhsExpr, lhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001084 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001085 }
Chris Lattner4b009652007-07-25 00:24:17 +00001086 }
Steve Naroff3b6157f2007-08-27 21:43:43 +00001087 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +00001088 }
1089 // Now handle "real" floating types (i.e. float, double, long double).
1090 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1091 // if we have an integer operand, the result is the real floating type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001092 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001093 // convert rhs to the lhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001094 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001095 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001096 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001097 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001098 // convert lhs to the rhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001099 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001100 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001101 }
1102 // We have two real floating types, float/complex combos were handled above.
1103 // Convert the smaller operand to the bigger result.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001104 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Naroff45fc9822007-08-27 15:30:22 +00001105
1106 if (result > 0) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001107 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001108 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001109 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001110 if (result < 0) { // convert the lhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001111 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff45fc9822007-08-27 15:30:22 +00001112 return rhs;
1113 }
1114 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001115 }
Steve Naroff43001212008-01-15 19:36:10 +00001116 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
1117 // Handle GCC complex int extension.
Steve Naroff43001212008-01-15 19:36:10 +00001118 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
Eli Friedman50727042008-02-08 01:19:44 +00001119 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
Steve Naroff43001212008-01-15 19:36:10 +00001120
Eli Friedman50727042008-02-08 01:19:44 +00001121 if (lhsComplexInt && rhsComplexInt) {
Chris Lattner51285d82008-04-06 23:55:33 +00001122 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
1123 rhsComplexInt->getElementType()) >= 0) {
Eli Friedman94075c02008-02-08 01:24:30 +00001124 // convert the rhs
1125 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1126 return lhs;
Eli Friedman50727042008-02-08 01:19:44 +00001127 }
1128 if (!isCompAssign)
Eli Friedman94075c02008-02-08 01:24:30 +00001129 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Eli Friedman50727042008-02-08 01:19:44 +00001130 return rhs;
1131 } else if (lhsComplexInt && rhs->isIntegerType()) {
1132 // convert the rhs to the lhs complex type.
1133 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1134 return lhs;
1135 } else if (rhsComplexInt && lhs->isIntegerType()) {
1136 // convert the lhs to the rhs complex type.
1137 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1138 return rhs;
1139 }
Steve Naroff43001212008-01-15 19:36:10 +00001140 }
Chris Lattner4b009652007-07-25 00:24:17 +00001141 // Finally, we have two differing integer types.
Chris Lattner51285d82008-04-06 23:55:33 +00001142 if (Context.getIntegerTypeOrder(lhs, rhs) >= 0) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001143 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001144 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001145 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001146 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff8f708362007-08-24 19:07:16 +00001147 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001148}
1149
1150// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1151// being closely modeled after the C99 spec:-). The odd characteristic of this
1152// routine is it effectively iqnores the qualifiers on the top level pointee.
1153// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1154// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001155Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001156Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1157 QualType lhptee, rhptee;
1158
1159 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001160 lhptee = lhsType->getAsPointerType()->getPointeeType();
1161 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001162
1163 // make sure we operate on the canonical type
1164 lhptee = lhptee.getCanonicalType();
1165 rhptee = rhptee.getCanonicalType();
1166
Chris Lattner005ed752008-01-04 18:04:52 +00001167 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001168
1169 // C99 6.5.16.1p1: This following citation is common to constraints
1170 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1171 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001172 // FIXME: Handle ASQualType
1173 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1174 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001175 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001176
1177 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1178 // incomplete type and the other is a pointer to a qualified or unqualified
1179 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001180 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001181 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001182 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001183
1184 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001185 assert(rhptee->isFunctionType());
1186 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001187 }
1188
1189 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001190 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001191 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001192
1193 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001194 assert(lhptee->isFunctionType());
1195 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001196 }
1197
Chris Lattner4b009652007-07-25 00:24:17 +00001198 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1199 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001200 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1201 rhptee.getUnqualifiedType()))
1202 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001203 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001204}
1205
1206/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1207/// has code to accommodate several GCC extensions when type checking
1208/// pointers. Here are some objectionable examples that GCC considers warnings:
1209///
1210/// int a, *pint;
1211/// short *pshort;
1212/// struct foo *pfoo;
1213///
1214/// pint = pshort; // warning: assignment from incompatible pointer type
1215/// a = pint; // warning: assignment makes integer from pointer without a cast
1216/// pint = a; // warning: assignment makes pointer from integer without a cast
1217/// pint = pfoo; // warning: assignment from incompatible pointer type
1218///
1219/// As a result, the code for dealing with pointers is more complex than the
1220/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001221///
Chris Lattner005ed752008-01-04 18:04:52 +00001222Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001223Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001224 // Get canonical types. We're not formatting these types, just comparing
1225 // them.
1226 lhsType = lhsType.getCanonicalType();
1227 rhsType = rhsType.getCanonicalType();
1228
1229 if (lhsType.getUnqualifiedType() == rhsType.getUnqualifiedType())
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001230 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001231
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001232 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001233 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001234 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001235 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001236 }
Chris Lattner1853da22008-01-04 23:18:45 +00001237
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001238 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1239 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001240 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001241 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001242 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001243
Chris Lattner390564e2008-04-07 06:49:41 +00001244 if (isa<VectorType>(lhsType) || isa<VectorType>(rhsType)) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001245 // For ExtVector, allow vector splats; float -> <n x float>
1246 if (const ExtVectorType *LV = dyn_cast<ExtVectorType>(lhsType)) {
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001247 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1248 return Compatible;
1249 }
1250
1251 // If LHS and RHS are both vectors of integer or both vectors of floating
1252 // point types, and the total vector length is the same, allow the
1253 // conversion. This is a bitcast; no bits are changed but the result type
1254 // is different.
1255 if (getLangOptions().LaxVectorConversions &&
1256 lhsType->isVectorType() && rhsType->isVectorType()) {
1257 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1258 (lhsType->isRealFloatingType() && rhsType->isRealFloatingType())) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001259 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Nate Begemanec2d1062007-12-30 02:59:45 +00001260 return Compatible;
1261 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001262 }
1263 return Incompatible;
1264 }
1265
1266 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001267 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001268
Chris Lattner390564e2008-04-07 06:49:41 +00001269 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001270 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001271 return IntToPointer;
Chris Lattner4b009652007-07-25 00:24:17 +00001272
Chris Lattner390564e2008-04-07 06:49:41 +00001273 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001274 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001275 return Incompatible;
1276 }
1277
Chris Lattner390564e2008-04-07 06:49:41 +00001278 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001279 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Chris Lattner390564e2008-04-07 06:49:41 +00001280 if (lhsType->isIntegerType() && lhsType != Context.BoolTy)
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001281 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001282
Chris Lattner390564e2008-04-07 06:49:41 +00001283 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001284 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001285 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001286 }
1287
1288 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001289 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001290 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001291 }
1292 return Incompatible;
1293}
1294
Chris Lattner005ed752008-01-04 18:04:52 +00001295Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001296Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001297 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1298 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001299 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001300 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001301 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001302 return Compatible;
1303 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001304 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001305 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001306 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001307 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001308 //
1309 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1310 // are better understood.
1311 if (!lhsType->isReferenceType())
1312 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001313
Chris Lattner005ed752008-01-04 18:04:52 +00001314 Sema::AssignConvertType result =
1315 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001316
1317 // C99 6.5.16.1p2: The value of the right operand is converted to the
1318 // type of the assignment expression.
1319 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001320 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001321 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001322}
1323
Chris Lattner005ed752008-01-04 18:04:52 +00001324Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001325Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1326 return CheckAssignmentConstraints(lhsType, rhsType);
1327}
1328
Chris Lattner2c8bff72007-12-12 05:47:28 +00001329QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001330 Diag(loc, diag::err_typecheck_invalid_operands,
1331 lex->getType().getAsString(), rex->getType().getAsString(),
1332 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001333 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001334}
1335
1336inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1337 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001338 // For conversion purposes, we ignore any qualifiers.
1339 // For example, "const float" and "float" are equivalent.
1340 QualType lhsType = lex->getType().getCanonicalType().getUnqualifiedType();
1341 QualType rhsType = rex->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001342
1343 // make sure the vector types are identical.
Nate Begeman03105572008-04-04 01:30:25 +00001344 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001345 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001346
Nate Begemanaf6ed502008-04-18 23:10:10 +00001347 // if the lhs is an extended vector and the rhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001348 // promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001349 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001350 if (V->getElementType().getCanonicalType().getTypePtr()
1351 == rhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001352 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001353 return lhsType;
1354 }
1355 }
1356
Nate Begemanaf6ed502008-04-18 23:10:10 +00001357 // if the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001358 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001359 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001360 if (V->getElementType().getCanonicalType().getTypePtr()
1361 == lhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001362 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001363 return rhsType;
1364 }
1365 }
1366
Chris Lattner4b009652007-07-25 00:24:17 +00001367 // You cannot convert between vector values of different size.
1368 Diag(loc, diag::err_typecheck_vector_not_convertable,
1369 lex->getType().getAsString(), rex->getType().getAsString(),
1370 lex->getSourceRange(), rex->getSourceRange());
1371 return QualType();
1372}
1373
1374inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001375 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001376{
1377 QualType lhsType = lex->getType(), rhsType = rex->getType();
1378
1379 if (lhsType->isVectorType() || rhsType->isVectorType())
1380 return CheckVectorOperands(loc, lex, rex);
1381
Steve Naroff8f708362007-08-24 19:07:16 +00001382 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001383
Chris Lattner4b009652007-07-25 00:24:17 +00001384 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001385 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001386 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001387}
1388
1389inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001390 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001391{
1392 QualType lhsType = lex->getType(), rhsType = rex->getType();
1393
Steve Naroff8f708362007-08-24 19:07:16 +00001394 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001395
Chris Lattner4b009652007-07-25 00:24:17 +00001396 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001397 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001398 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001399}
1400
1401inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001402 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001403{
1404 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1405 return CheckVectorOperands(loc, lex, rex);
1406
Steve Naroff8f708362007-08-24 19:07:16 +00001407 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001408
Chris Lattner4b009652007-07-25 00:24:17 +00001409 // handle the common case first (both operands are arithmetic).
1410 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001411 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001412
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001413 // Put any potential pointer into PExp
1414 Expr* PExp = lex, *IExp = rex;
1415 if (IExp->getType()->isPointerType())
1416 std::swap(PExp, IExp);
1417
1418 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1419 if (IExp->getType()->isIntegerType()) {
1420 // Check for arithmetic on pointers to incomplete types
1421 if (!PTy->getPointeeType()->isObjectType()) {
1422 if (PTy->getPointeeType()->isVoidType()) {
1423 Diag(loc, diag::ext_gnu_void_ptr,
1424 lex->getSourceRange(), rex->getSourceRange());
1425 } else {
1426 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1427 lex->getType().getAsString(), lex->getSourceRange());
1428 return QualType();
1429 }
1430 }
1431 return PExp->getType();
1432 }
1433 }
1434
Chris Lattner2c8bff72007-12-12 05:47:28 +00001435 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001436}
1437
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001438// C99 6.5.6
1439QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1440 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001441 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1442 return CheckVectorOperands(loc, lex, rex);
1443
Steve Naroff8f708362007-08-24 19:07:16 +00001444 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001445
Chris Lattnerf6da2912007-12-09 21:53:25 +00001446 // Enforce type constraints: C99 6.5.6p3.
1447
1448 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001449 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001450 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001451
1452 // Either ptr - int or ptr - ptr.
1453 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001454 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001455
Chris Lattnerf6da2912007-12-09 21:53:25 +00001456 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001457 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001458 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001459 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001460 Diag(loc, diag::ext_gnu_void_ptr,
1461 lex->getSourceRange(), rex->getSourceRange());
1462 } else {
1463 Diag(loc, diag::err_typecheck_sub_ptr_object,
1464 lex->getType().getAsString(), lex->getSourceRange());
1465 return QualType();
1466 }
1467 }
1468
1469 // The result type of a pointer-int computation is the pointer type.
1470 if (rex->getType()->isIntegerType())
1471 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001472
Chris Lattnerf6da2912007-12-09 21:53:25 +00001473 // Handle pointer-pointer subtractions.
1474 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001475 QualType rpointee = RHSPTy->getPointeeType();
1476
Chris Lattnerf6da2912007-12-09 21:53:25 +00001477 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001478 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001479 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001480 if (rpointee->isVoidType()) {
1481 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001482 Diag(loc, diag::ext_gnu_void_ptr,
1483 lex->getSourceRange(), rex->getSourceRange());
1484 } else {
1485 Diag(loc, diag::err_typecheck_sub_ptr_object,
1486 rex->getType().getAsString(), rex->getSourceRange());
1487 return QualType();
1488 }
1489 }
1490
1491 // Pointee types must be compatible.
Steve Naroff577f9722008-01-29 18:58:14 +00001492 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1493 rpointee.getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001494 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1495 lex->getType().getAsString(), rex->getType().getAsString(),
1496 lex->getSourceRange(), rex->getSourceRange());
1497 return QualType();
1498 }
1499
1500 return Context.getPointerDiffType();
1501 }
1502 }
1503
Chris Lattner2c8bff72007-12-12 05:47:28 +00001504 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001505}
1506
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001507// C99 6.5.7
1508QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1509 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00001510 // C99 6.5.7p2: Each of the operands shall have integer type.
1511 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1512 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001513
Chris Lattner2c8bff72007-12-12 05:47:28 +00001514 // Shifts don't perform usual arithmetic conversions, they just do integer
1515 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001516 if (!isCompAssign)
1517 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001518 UsualUnaryConversions(rex);
1519
1520 // "The type of the result is that of the promoted left operand."
1521 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001522}
1523
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001524// C99 6.5.8
1525QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1526 bool isRelational) {
Chris Lattner254f3bc2007-08-26 01:18:55 +00001527 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001528 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1529 UsualArithmeticConversions(lex, rex);
1530 else {
1531 UsualUnaryConversions(lex);
1532 UsualUnaryConversions(rex);
1533 }
Chris Lattner4b009652007-07-25 00:24:17 +00001534 QualType lType = lex->getType();
1535 QualType rType = rex->getType();
1536
Ted Kremenek486509e2007-10-29 17:13:39 +00001537 // For non-floating point types, check for self-comparisons of the form
1538 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1539 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001540 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001541 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1542 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001543 if (DRL->getDecl() == DRR->getDecl())
1544 Diag(loc, diag::warn_selfcomparison);
1545 }
1546
Chris Lattner254f3bc2007-08-26 01:18:55 +00001547 if (isRelational) {
1548 if (lType->isRealType() && rType->isRealType())
1549 return Context.IntTy;
1550 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001551 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001552 if (lType->isFloatingType()) {
1553 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001554 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001555 }
1556
Chris Lattner254f3bc2007-08-26 01:18:55 +00001557 if (lType->isArithmeticType() && rType->isArithmeticType())
1558 return Context.IntTy;
1559 }
Chris Lattner4b009652007-07-25 00:24:17 +00001560
Chris Lattner22be8422007-08-26 01:10:14 +00001561 bool LHSIsNull = lex->isNullPointerConstant(Context);
1562 bool RHSIsNull = rex->isNullPointerConstant(Context);
1563
Chris Lattner254f3bc2007-08-26 01:18:55 +00001564 // All of the following pointer related warnings are GCC extensions, except
1565 // when handling null pointer constants. One day, we can consider making them
1566 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001567 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001568 QualType LCanPointeeTy =
1569 lType->getAsPointerType()->getPointeeType().getCanonicalType();
1570 QualType RCanPointeeTy =
1571 rType->getAsPointerType()->getPointeeType().getCanonicalType();
Eli Friedman50727042008-02-08 01:19:44 +00001572
Steve Naroff3b435622007-11-13 14:57:38 +00001573 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001574 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1575 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
1576 RCanPointeeTy.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001577 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1578 lType.getAsString(), rType.getAsString(),
1579 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001580 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001581 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001582 return Context.IntTy;
1583 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001584 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001585 && ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001586 ImpCastExprToType(rex, lType);
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001587 return Context.IntTy;
1588 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001589 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001590 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001591 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1592 lType.getAsString(), rType.getAsString(),
1593 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001594 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001595 return Context.IntTy;
1596 }
1597 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001598 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001599 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1600 lType.getAsString(), rType.getAsString(),
1601 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001602 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001603 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001604 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001605 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001606}
1607
Chris Lattner4b009652007-07-25 00:24:17 +00001608inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001609 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001610{
1611 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1612 return CheckVectorOperands(loc, lex, rex);
1613
Steve Naroff8f708362007-08-24 19:07:16 +00001614 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001615
1616 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001617 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001618 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001619}
1620
1621inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1622 Expr *&lex, Expr *&rex, SourceLocation loc)
1623{
1624 UsualUnaryConversions(lex);
1625 UsualUnaryConversions(rex);
1626
Eli Friedmanbea3f842008-05-13 20:16:47 +00001627 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00001628 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001629 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001630}
1631
1632inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001633 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001634{
1635 QualType lhsType = lex->getType();
1636 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner4b009652007-07-25 00:24:17 +00001637 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1638
1639 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001640 case Expr::MLV_Valid:
1641 break;
1642 case Expr::MLV_ConstQualified:
1643 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1644 return QualType();
1645 case Expr::MLV_ArrayType:
1646 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1647 lhsType.getAsString(), lex->getSourceRange());
1648 return QualType();
1649 case Expr::MLV_NotObjectType:
1650 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1651 lhsType.getAsString(), lex->getSourceRange());
1652 return QualType();
1653 case Expr::MLV_InvalidExpression:
1654 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1655 lex->getSourceRange());
1656 return QualType();
1657 case Expr::MLV_IncompleteType:
1658 case Expr::MLV_IncompleteVoidType:
1659 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1660 lhsType.getAsString(), lex->getSourceRange());
1661 return QualType();
1662 case Expr::MLV_DuplicateVectorComponents:
1663 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1664 lex->getSourceRange());
1665 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001666 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001667
Chris Lattner005ed752008-01-04 18:04:52 +00001668 AssignConvertType ConvTy;
1669 if (compoundType.isNull())
1670 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1671 else
1672 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1673
1674 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1675 rex, "assigning"))
1676 return QualType();
1677
Chris Lattner4b009652007-07-25 00:24:17 +00001678 // C99 6.5.16p3: The type of an assignment expression is the type of the
1679 // left operand unless the left operand has qualified type, in which case
1680 // it is the unqualified version of the type of the left operand.
1681 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1682 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001683 // C++ 5.17p1: the type of the assignment expression is that of its left
1684 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001685 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001686}
1687
1688inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1689 Expr *&lex, Expr *&rex, SourceLocation loc) {
1690 UsualUnaryConversions(rex);
1691 return rex->getType();
1692}
1693
1694/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1695/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1696QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1697 QualType resType = op->getType();
1698 assert(!resType.isNull() && "no type for increment/decrement expression");
1699
Steve Naroffd30e1932007-08-24 17:20:07 +00001700 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001701 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001702 if (pt->getPointeeType()->isVoidType()) {
1703 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
1704 } else if (!pt->getPointeeType()->isObjectType()) {
1705 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00001706 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1707 resType.getAsString(), op->getSourceRange());
1708 return QualType();
1709 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001710 } else if (!resType->isRealType()) {
1711 if (resType->isComplexType())
1712 // C99 does not support ++/-- on complex types.
1713 Diag(OpLoc, diag::ext_integer_increment_complex,
1714 resType.getAsString(), op->getSourceRange());
1715 else {
1716 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1717 resType.getAsString(), op->getSourceRange());
1718 return QualType();
1719 }
Chris Lattner4b009652007-07-25 00:24:17 +00001720 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001721 // At this point, we know we have a real, complex or pointer type.
1722 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001723 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1724 if (mlval != Expr::MLV_Valid) {
1725 // FIXME: emit a more precise diagnostic...
1726 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1727 op->getSourceRange());
1728 return QualType();
1729 }
1730 return resType;
1731}
1732
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001733/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00001734/// This routine allows us to typecheck complex/recursive expressions
1735/// where the declaration is needed for type checking. Here are some
1736/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
Chris Lattner48d7f382008-04-02 04:24:33 +00001737static ValueDecl *getPrimaryDecl(Expr *E) {
1738 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001739 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001740 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001741 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001742 // Fields cannot be declared with a 'register' storage class.
1743 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00001744 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00001745 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00001746 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001747 case Stmt::ArraySubscriptExprClass: {
1748 // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer.
1749
Chris Lattner48d7f382008-04-02 04:24:33 +00001750 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00001751 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001752 return 0;
1753 else
1754 return VD;
1755 }
Chris Lattner4b009652007-07-25 00:24:17 +00001756 case Stmt::UnaryOperatorClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001757 return getPrimaryDecl(cast<UnaryOperator>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001758 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001759 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001760 case Stmt::ImplicitCastExprClass:
1761 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00001762 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001763 default:
1764 return 0;
1765 }
1766}
1767
1768/// CheckAddressOfOperand - The operand of & must be either a function
1769/// designator or an lvalue designating an object. If it is an lvalue, the
1770/// object cannot be declared with storage class register or be a bit field.
1771/// Note: The usual conversions are *not* applied to the operand of the &
1772/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1773QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001774 if (getLangOptions().C99) {
1775 // Implement C99-only parts of addressof rules.
1776 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
1777 if (uOp->getOpcode() == UnaryOperator::Deref)
1778 // Per C99 6.5.3.2, the address of a deref always returns a valid result
1779 // (assuming the deref expression is valid).
1780 return uOp->getSubExpr()->getType();
1781 }
1782 // Technically, there should be a check for array subscript
1783 // expressions here, but the result of one is always an lvalue anyway.
1784 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001785 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner4b009652007-07-25 00:24:17 +00001786 Expr::isLvalueResult lval = op->isLvalue();
1787
1788 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001789 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1790 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001791 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1792 op->getSourceRange());
1793 return QualType();
1794 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00001795 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
1796 if (MemExpr->getMemberDecl()->isBitField()) {
1797 Diag(OpLoc, diag::err_typecheck_address_of,
1798 std::string("bit-field"), op->getSourceRange());
1799 return QualType();
1800 }
1801 // Check for Apple extension for accessing vector components.
1802 } else if (isa<ArraySubscriptExpr>(op) &&
1803 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
1804 Diag(OpLoc, diag::err_typecheck_address_of,
1805 std::string("vector"), op->getSourceRange());
1806 return QualType();
1807 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00001808 // We have an lvalue with a decl. Make sure the decl is not declared
1809 // with the register storage-class specifier.
1810 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1811 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00001812 Diag(OpLoc, diag::err_typecheck_address_of,
1813 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001814 return QualType();
1815 }
1816 } else
1817 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00001818 }
1819 // If the operand has type "type", the result has type "pointer to type".
1820 return Context.getPointerType(op->getType());
1821}
1822
1823QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1824 UsualUnaryConversions(op);
1825 QualType qType = op->getType();
1826
Chris Lattner7931f4a2007-07-31 16:53:04 +00001827 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001828 // Note that per both C89 and C99, this is always legal, even
1829 // if ptype is an incomplete type or void.
1830 // It would be possible to warn about dereferencing a
1831 // void pointer, but it's completely well-defined,
1832 // and such a warning is unlikely to catch any mistakes.
1833 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001834 }
1835 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1836 qType.getAsString(), op->getSourceRange());
1837 return QualType();
1838}
1839
1840static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1841 tok::TokenKind Kind) {
1842 BinaryOperator::Opcode Opc;
1843 switch (Kind) {
1844 default: assert(0 && "Unknown binop!");
1845 case tok::star: Opc = BinaryOperator::Mul; break;
1846 case tok::slash: Opc = BinaryOperator::Div; break;
1847 case tok::percent: Opc = BinaryOperator::Rem; break;
1848 case tok::plus: Opc = BinaryOperator::Add; break;
1849 case tok::minus: Opc = BinaryOperator::Sub; break;
1850 case tok::lessless: Opc = BinaryOperator::Shl; break;
1851 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1852 case tok::lessequal: Opc = BinaryOperator::LE; break;
1853 case tok::less: Opc = BinaryOperator::LT; break;
1854 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1855 case tok::greater: Opc = BinaryOperator::GT; break;
1856 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1857 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1858 case tok::amp: Opc = BinaryOperator::And; break;
1859 case tok::caret: Opc = BinaryOperator::Xor; break;
1860 case tok::pipe: Opc = BinaryOperator::Or; break;
1861 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1862 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1863 case tok::equal: Opc = BinaryOperator::Assign; break;
1864 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1865 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1866 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1867 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1868 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1869 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1870 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1871 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1872 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1873 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1874 case tok::comma: Opc = BinaryOperator::Comma; break;
1875 }
1876 return Opc;
1877}
1878
1879static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1880 tok::TokenKind Kind) {
1881 UnaryOperator::Opcode Opc;
1882 switch (Kind) {
1883 default: assert(0 && "Unknown unary op!");
1884 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1885 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1886 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1887 case tok::star: Opc = UnaryOperator::Deref; break;
1888 case tok::plus: Opc = UnaryOperator::Plus; break;
1889 case tok::minus: Opc = UnaryOperator::Minus; break;
1890 case tok::tilde: Opc = UnaryOperator::Not; break;
1891 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1892 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1893 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1894 case tok::kw___real: Opc = UnaryOperator::Real; break;
1895 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1896 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1897 }
1898 return Opc;
1899}
1900
1901// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001902Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001903 ExprTy *LHS, ExprTy *RHS) {
1904 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1905 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1906
Steve Naroff87d58b42007-09-16 03:34:24 +00001907 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1908 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001909
1910 QualType ResultTy; // Result type of the binary operator.
1911 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1912
1913 switch (Opc) {
1914 default:
1915 assert(0 && "Unknown binary expr!");
1916 case BinaryOperator::Assign:
1917 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1918 break;
1919 case BinaryOperator::Mul:
1920 case BinaryOperator::Div:
1921 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1922 break;
1923 case BinaryOperator::Rem:
1924 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1925 break;
1926 case BinaryOperator::Add:
1927 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1928 break;
1929 case BinaryOperator::Sub:
1930 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1931 break;
1932 case BinaryOperator::Shl:
1933 case BinaryOperator::Shr:
1934 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1935 break;
1936 case BinaryOperator::LE:
1937 case BinaryOperator::LT:
1938 case BinaryOperator::GE:
1939 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001940 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001941 break;
1942 case BinaryOperator::EQ:
1943 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001944 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001945 break;
1946 case BinaryOperator::And:
1947 case BinaryOperator::Xor:
1948 case BinaryOperator::Or:
1949 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1950 break;
1951 case BinaryOperator::LAnd:
1952 case BinaryOperator::LOr:
1953 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1954 break;
1955 case BinaryOperator::MulAssign:
1956 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001957 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001958 if (!CompTy.isNull())
1959 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1960 break;
1961 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001962 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001963 if (!CompTy.isNull())
1964 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1965 break;
1966 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001967 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001968 if (!CompTy.isNull())
1969 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1970 break;
1971 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001972 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001973 if (!CompTy.isNull())
1974 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1975 break;
1976 case BinaryOperator::ShlAssign:
1977 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001978 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001979 if (!CompTy.isNull())
1980 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1981 break;
1982 case BinaryOperator::AndAssign:
1983 case BinaryOperator::XorAssign:
1984 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001985 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001986 if (!CompTy.isNull())
1987 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1988 break;
1989 case BinaryOperator::Comma:
1990 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1991 break;
1992 }
1993 if (ResultTy.isNull())
1994 return true;
1995 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001996 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001997 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001998 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001999}
2000
2001// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002002Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002003 ExprTy *input) {
2004 Expr *Input = (Expr*)input;
2005 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2006 QualType resultType;
2007 switch (Opc) {
2008 default:
2009 assert(0 && "Unimplemented unary expr!");
2010 case UnaryOperator::PreInc:
2011 case UnaryOperator::PreDec:
2012 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2013 break;
2014 case UnaryOperator::AddrOf:
2015 resultType = CheckAddressOfOperand(Input, OpLoc);
2016 break;
2017 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002018 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002019 resultType = CheckIndirectionOperand(Input, OpLoc);
2020 break;
2021 case UnaryOperator::Plus:
2022 case UnaryOperator::Minus:
2023 UsualUnaryConversions(Input);
2024 resultType = Input->getType();
2025 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2026 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2027 resultType.getAsString());
2028 break;
2029 case UnaryOperator::Not: // bitwise complement
2030 UsualUnaryConversions(Input);
2031 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00002032 // C99 6.5.3.3p1. We allow complex as a GCC extension.
2033 if (!resultType->isIntegerType()) {
2034 if (resultType->isComplexType())
2035 // C99 does not support '~' for complex conjugation.
2036 Diag(OpLoc, diag::ext_integer_complement_complex,
2037 resultType.getAsString());
2038 else
2039 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2040 resultType.getAsString());
2041 }
Chris Lattner4b009652007-07-25 00:24:17 +00002042 break;
2043 case UnaryOperator::LNot: // logical negation
2044 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2045 DefaultFunctionArrayConversion(Input);
2046 resultType = Input->getType();
2047 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2048 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2049 resultType.getAsString());
2050 // LNot always has type int. C99 6.5.3.3p5.
2051 resultType = Context.IntTy;
2052 break;
2053 case UnaryOperator::SizeOf:
2054 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
2055 break;
2056 case UnaryOperator::AlignOf:
2057 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
2058 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002059 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002060 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002061 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002062 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002063 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002064 resultType = Input->getType();
2065 break;
2066 }
2067 if (resultType.isNull())
2068 return true;
2069 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2070}
2071
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002072/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2073Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002074 SourceLocation LabLoc,
2075 IdentifierInfo *LabelII) {
2076 // Look up the record for this label identifier.
2077 LabelStmt *&LabelDecl = LabelMap[LabelII];
2078
2079 // If we haven't seen this label yet, create a forward reference.
2080 if (LabelDecl == 0)
2081 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2082
2083 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002084 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2085 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002086}
2087
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002088Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002089 SourceLocation RPLoc) { // "({..})"
2090 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2091 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2092 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2093
2094 // FIXME: there are a variety of strange constraints to enforce here, for
2095 // example, it is not possible to goto into a stmt expression apparently.
2096 // More semantic analysis is needed.
2097
2098 // FIXME: the last statement in the compount stmt has its value used. We
2099 // should not warn about it being unused.
2100
2101 // If there are sub stmts in the compound stmt, take the type of the last one
2102 // as the type of the stmtexpr.
2103 QualType Ty = Context.VoidTy;
2104
2105 if (!Compound->body_empty())
2106 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
2107 Ty = LastExpr->getType();
2108
2109 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2110}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002111
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002112Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002113 SourceLocation TypeLoc,
2114 TypeTy *argty,
2115 OffsetOfComponent *CompPtr,
2116 unsigned NumComponents,
2117 SourceLocation RPLoc) {
2118 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2119 assert(!ArgTy.isNull() && "Missing type argument!");
2120
2121 // We must have at least one component that refers to the type, and the first
2122 // one is known to be a field designator. Verify that the ArgTy represents
2123 // a struct/union/class.
2124 if (!ArgTy->isRecordType())
2125 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2126
2127 // Otherwise, create a compound literal expression as the base, and
2128 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002129 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002130
Chris Lattnerb37522e2007-08-31 21:49:13 +00002131 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2132 // GCC extension, diagnose them.
2133 if (NumComponents != 1)
2134 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2135 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2136
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002137 for (unsigned i = 0; i != NumComponents; ++i) {
2138 const OffsetOfComponent &OC = CompPtr[i];
2139 if (OC.isBrackets) {
2140 // Offset of an array sub-field. TODO: Should we allow vector elements?
2141 const ArrayType *AT = Res->getType()->getAsArrayType();
2142 if (!AT) {
2143 delete Res;
2144 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2145 Res->getType().getAsString());
2146 }
2147
Chris Lattner2af6a802007-08-30 17:59:59 +00002148 // FIXME: C++: Verify that operator[] isn't overloaded.
2149
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002150 // C99 6.5.2.1p1
2151 Expr *Idx = static_cast<Expr*>(OC.U.E);
2152 if (!Idx->getType()->isIntegerType())
2153 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2154 Idx->getSourceRange());
2155
2156 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2157 continue;
2158 }
2159
2160 const RecordType *RC = Res->getType()->getAsRecordType();
2161 if (!RC) {
2162 delete Res;
2163 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2164 Res->getType().getAsString());
2165 }
2166
2167 // Get the decl corresponding to this.
2168 RecordDecl *RD = RC->getDecl();
2169 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2170 if (!MemberDecl)
2171 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2172 OC.U.IdentInfo->getName(),
2173 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002174
2175 // FIXME: C++: Verify that MemberDecl isn't a static field.
2176 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002177 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2178 // matter here.
2179 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002180 }
2181
2182 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2183 BuiltinLoc);
2184}
2185
2186
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002187Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002188 TypeTy *arg1, TypeTy *arg2,
2189 SourceLocation RPLoc) {
2190 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2191 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2192
2193 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2194
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002195 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002196}
2197
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002198Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002199 ExprTy *expr1, ExprTy *expr2,
2200 SourceLocation RPLoc) {
2201 Expr *CondExpr = static_cast<Expr*>(cond);
2202 Expr *LHSExpr = static_cast<Expr*>(expr1);
2203 Expr *RHSExpr = static_cast<Expr*>(expr2);
2204
2205 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2206
2207 // The conditional expression is required to be a constant expression.
2208 llvm::APSInt condEval(32);
2209 SourceLocation ExpLoc;
2210 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2211 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2212 CondExpr->getSourceRange());
2213
2214 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2215 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2216 RHSExpr->getType();
2217 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2218}
2219
Nate Begemanbd881ef2008-01-30 20:50:20 +00002220/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002221/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002222/// The number of arguments has already been validated to match the number of
2223/// arguments in FnType.
2224static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002225 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00002226 for (unsigned i = 0; i != NumParams; ++i) {
2227 QualType ExprTy = Args[i]->getType().getCanonicalType();
2228 QualType ParmTy = FnType->getArgType(i).getCanonicalType();
2229
2230 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002231 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00002232 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002233 return true;
2234}
2235
2236Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2237 SourceLocation *CommaLocs,
2238 SourceLocation BuiltinLoc,
2239 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002240 // __builtin_overload requires at least 2 arguments
2241 if (NumArgs < 2)
2242 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2243 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002244
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002245 // The first argument is required to be a constant expression. It tells us
2246 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002247 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002248 Expr *NParamsExpr = Args[0];
2249 llvm::APSInt constEval(32);
2250 SourceLocation ExpLoc;
2251 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2252 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2253 NParamsExpr->getSourceRange());
2254
2255 // Verify that the number of parameters is > 0
2256 unsigned NumParams = constEval.getZExtValue();
2257 if (NumParams == 0)
2258 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2259 NParamsExpr->getSourceRange());
2260 // Verify that we have at least 1 + NumParams arguments to the builtin.
2261 if ((NumParams + 1) > NumArgs)
2262 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2263 SourceRange(BuiltinLoc, RParenLoc));
2264
2265 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002266 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002267 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002268 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2269 // UsualUnaryConversions will convert the function DeclRefExpr into a
2270 // pointer to function.
2271 Expr *Fn = UsualUnaryConversions(Args[i]);
2272 FunctionTypeProto *FnType = 0;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002273 if (const PointerType *PT = Fn->getType()->getAsPointerType()) {
2274 QualType PointeeType = PT->getPointeeType().getCanonicalType();
2275 FnType = dyn_cast<FunctionTypeProto>(PointeeType);
2276 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002277
2278 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2279 // parameters, and the number of parameters must match the value passed to
2280 // the builtin.
2281 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002282 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2283 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002284
2285 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002286 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002287 // If they match, return a new OverloadExpr.
Nate Begemanc6078c92008-01-31 05:38:29 +00002288 if (ExprsMatchFnType(Args+1, FnType)) {
2289 if (OE)
2290 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2291 OE->getFn()->getSourceRange());
2292 // Remember our match, and continue processing the remaining arguments
2293 // to catch any errors.
2294 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2295 BuiltinLoc, RParenLoc);
2296 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002297 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002298 // Return the newly created OverloadExpr node, if we succeded in matching
2299 // exactly one of the candidate functions.
2300 if (OE)
2301 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002302
2303 // If we didn't find a matching function Expr in the __builtin_overload list
2304 // the return an error.
2305 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002306 for (unsigned i = 0; i != NumParams; ++i) {
2307 if (i != 0) typeNames += ", ";
2308 typeNames += Args[i+1]->getType().getAsString();
2309 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002310
2311 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2312 SourceRange(BuiltinLoc, RParenLoc));
2313}
2314
Anders Carlsson36760332007-10-15 20:28:48 +00002315Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2316 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002317 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002318 Expr *E = static_cast<Expr*>(expr);
2319 QualType T = QualType::getFromOpaquePtr(type);
2320
2321 InitBuiltinVaListType();
2322
Chris Lattner005ed752008-01-04 18:04:52 +00002323 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2324 != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002325 return Diag(E->getLocStart(),
2326 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2327 E->getType().getAsString(),
2328 E->getSourceRange());
2329
2330 // FIXME: Warn if a non-POD type is passed in.
2331
2332 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2333}
2334
Chris Lattner005ed752008-01-04 18:04:52 +00002335bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2336 SourceLocation Loc,
2337 QualType DstType, QualType SrcType,
2338 Expr *SrcExpr, const char *Flavor) {
2339 // Decode the result (notice that AST's are still created for extensions).
2340 bool isInvalid = false;
2341 unsigned DiagKind;
2342 switch (ConvTy) {
2343 default: assert(0 && "Unknown conversion type");
2344 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002345 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002346 DiagKind = diag::ext_typecheck_convert_pointer_int;
2347 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002348 case IntToPointer:
2349 DiagKind = diag::ext_typecheck_convert_int_pointer;
2350 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002351 case IncompatiblePointer:
2352 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2353 break;
2354 case FunctionVoidPointer:
2355 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2356 break;
2357 case CompatiblePointerDiscardsQualifiers:
2358 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2359 break;
2360 case Incompatible:
2361 DiagKind = diag::err_typecheck_convert_incompatible;
2362 isInvalid = true;
2363 break;
2364 }
2365
2366 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2367 SrcExpr->getSourceRange());
2368 return isInvalid;
2369}
2370
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002371
2372