blob: b81e090f7fb08951c0fab1ea0468cd39e131d42d [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"
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000017#include "clang/AST/DeclCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "clang/AST/Expr.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000019#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000020#include "clang/AST/ExprObjC.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000021#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Lex/Preprocessor.h"
23#include "clang/Lex/LiteralSupport.h"
24#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "clang/Basic/TargetInfo.h"
Chris Lattner83bd5eb2007-12-28 05:29:59 +000026#include "llvm/ADT/OwningPtr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000028#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029using namespace clang;
30
Steve Naroff87d58b42007-09-16 03:34:24 +000031/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000032/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
33/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
34/// multiple tokens. However, the common case is that StringToks points to one
35/// string.
36///
37Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000038Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000039 assert(NumStringToks && "Must have at least one string!");
40
41 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
42 if (Literal.hadError)
43 return ExprResult(true);
44
45 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
46 for (unsigned i = 0; i != NumStringToks; ++i)
47 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +000048
49 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000050 if (Literal.Pascal && Literal.GetStringLength() > 256)
51 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
52 SourceRange(StringToks[0].getLocation(),
53 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000054
Chris Lattnera6dcce32008-02-11 00:02:17 +000055 QualType StrTy = Context.CharTy;
Eli Friedman256b7d72008-05-27 07:57:14 +000056 if (Literal.AnyWide) StrTy = Context.getWcharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +000057 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
58
59 // Get an array type for the string, according to C99 6.4.5. This includes
60 // the nul terminator character as well as the string length for pascal
61 // strings.
62 StrTy = Context.getConstantArrayType(StrTy,
63 llvm::APInt(32, Literal.GetStringLength()+1),
64 ArrayType::Normal, 0);
65
Chris Lattner4b009652007-07-25 00:24:17 +000066 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
67 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +000068 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000069 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000070 StringToks[NumStringToks-1].getLocation());
71}
72
73
Steve Naroff0acc9c92007-09-15 18:49:24 +000074/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000075/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +000076/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000077Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000078 IdentifierInfo &II,
79 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +000080 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +000081 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +000082
83 // If this reference is in an Objective-C method, then ivar lookup happens as
84 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +000085 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +000086 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +000087 // There are two cases to handle here. 1) scoped lookup could have failed,
88 // in which case we should look for an ivar. 2) scoped lookup could have
89 // found a decl, but that decl is outside the current method (i.e. a global
90 // variable). In these two cases, we do a lookup for an ivar with this
91 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +000092 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +000093 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
94 ObjCInterfaceDecl *DeclClass;
Chris Lattnerc72d22d2008-03-31 00:36:02 +000095 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II, DeclClass)) {
96 // FIXME: This should use a new expr for a direct reference, don't turn
97 // this into Self->ivar, just return a BareIVarExpr or something.
98 IdentifierInfo &II = Context.Idents.get("self");
99 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
100 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
101 static_cast<Expr*>(SelfExpr.Val), true, true);
102 }
103 }
Steve Naroffe90d4cc2008-06-05 18:14:25 +0000104 if (SD == 0 && !strcmp(II.getName(), "super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000105 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000106 getCurMethodDecl()->getClassInterface()));
Steve Naroff6f786252008-06-02 23:03:37 +0000107 return new ObjCSuperRefExpr(T, Loc);
108 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000109 }
110
Chris Lattner4b009652007-07-25 00:24:17 +0000111 if (D == 0) {
112 // Otherwise, this could be an implicitly declared function reference (legal
113 // in C90, extension in C99).
114 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000115 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000116 D = ImplicitlyDefineFunction(Loc, II, S);
117 else {
118 // If this name wasn't predeclared and if this is not a function call,
119 // diagnose the problem.
120 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
121 }
122 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000123
Steve Naroff91b03f72007-08-28 03:03:08 +0000124 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneree4c3bf2008-02-29 16:48:43 +0000125 // check if referencing an identifier with __attribute__((deprecated)).
126 if (VD->getAttr<DeprecatedAttr>())
127 Diag(Loc, diag::warn_deprecated, VD->getName());
128
Steve Naroffcae537d2007-08-28 18:45:29 +0000129 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000130 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000131 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000132 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000133 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000134
135 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
136 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
137 if (MD->isStatic())
138 // "invalid use of member 'x' in static member function"
139 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
140 FD->getName());
141 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
142 // "invalid use of nonstatic data member 'x'"
143 return Diag(Loc, diag::err_invalid_non_static_member_use,
144 FD->getName());
145
146 if (FD->isInvalidDecl())
147 return true;
148
149 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
150 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
151 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
152 true, FD, Loc, FD->getType());
153 }
154
155 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
156 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000157
Chris Lattner4b009652007-07-25 00:24:17 +0000158 if (isa<TypedefDecl>(D))
159 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000160 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000161 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000162 if (isa<NamespaceDecl>(D))
163 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000164
165 assert(0 && "Invalid decl");
166 abort();
167}
168
Steve Naroff87d58b42007-09-16 03:34:24 +0000169Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000170 tok::TokenKind Kind) {
171 PreDefinedExpr::IdentType IT;
172
173 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000174 default: assert(0 && "Unknown simple primary expr!");
175 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
176 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
177 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000178 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000179
180 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000181 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000182 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000183
Chris Lattner7e637512008-01-12 08:14:25 +0000184 // Pre-defined identifiers are of type char[x], where x is the length of the
185 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000186 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000187 if (getCurFunctionDecl())
188 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000189 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000190 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000191
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000192 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000193 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000194 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner7e637512008-01-12 08:14:25 +0000195 return new PreDefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000196}
197
Steve Naroff87d58b42007-09-16 03:34:24 +0000198Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000199 llvm::SmallString<16> CharBuffer;
200 CharBuffer.resize(Tok.getLength());
201 const char *ThisTokBegin = &CharBuffer[0];
202 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
203
204 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
205 Tok.getLocation(), PP);
206 if (Literal.hadError())
207 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000208
209 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
210
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000211 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
212 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000213}
214
Steve Naroff87d58b42007-09-16 03:34:24 +0000215Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000216 // fast path for a single digit (which is quite common). A single digit
217 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
218 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000219 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000220
Chris Lattner8cd0e932008-03-05 18:54:05 +0000221 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000222 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000223 Context.IntTy,
224 Tok.getLocation()));
225 }
226 llvm::SmallString<512> IntegerBuffer;
227 IntegerBuffer.resize(Tok.getLength());
228 const char *ThisTokBegin = &IntegerBuffer[0];
229
230 // Get the spelling of the token, which eliminates trigraphs, etc.
231 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
232 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
233 Tok.getLocation(), PP);
234 if (Literal.hadError)
235 return ExprResult(true);
236
Chris Lattner1de66eb2007-08-26 03:42:43 +0000237 Expr *Res;
238
239 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000240 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000241 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000242 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000243 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000244 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000245 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000246 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000247
248 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
249
Ted Kremenekddedbe22007-11-29 00:56:49 +0000250 // isExact will be set by GetFloatValue().
251 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000252 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000253 Ty, Tok.getLocation());
254
Chris Lattner1de66eb2007-08-26 03:42:43 +0000255 } else if (!Literal.isIntegerLiteral()) {
256 return ExprResult(true);
257 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000258 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000259
Neil Booth7421e9c2007-08-29 22:00:19 +0000260 // long long is a C99 feature.
261 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000262 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000263 Diag(Tok.getLocation(), diag::ext_longlong);
264
Chris Lattner4b009652007-07-25 00:24:17 +0000265 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000266 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000267
268 if (Literal.GetIntegerValue(ResultVal)) {
269 // If this value didn't fit into uintmax_t, warn and force to ull.
270 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000271 Ty = Context.UnsignedLongLongTy;
272 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000273 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000274 } else {
275 // If this value fits into a ULL, try to figure out what else it fits into
276 // according to the rules of C99 6.4.4.1p5.
277
278 // Octal, Hexadecimal, and integers with a U suffix are allowed to
279 // be an unsigned int.
280 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
281
282 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000283 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000284 if (!Literal.isLong && !Literal.isLongLong) {
285 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000286 unsigned IntSize = Context.Target.getIntWidth();
287
Chris Lattner4b009652007-07-25 00:24:17 +0000288 // Does it fit in a unsigned int?
289 if (ResultVal.isIntN(IntSize)) {
290 // Does it fit in a signed int?
291 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000292 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000293 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000294 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000295 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000296 }
Chris Lattner4b009652007-07-25 00:24:17 +0000297 }
298
299 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000300 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000301 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000302
303 // Does it fit in a unsigned long?
304 if (ResultVal.isIntN(LongSize)) {
305 // Does it fit in a signed long?
306 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000307 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000308 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000309 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000310 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000311 }
Chris Lattner4b009652007-07-25 00:24:17 +0000312 }
313
314 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000315 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000316 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000317
318 // Does it fit in a unsigned long long?
319 if (ResultVal.isIntN(LongLongSize)) {
320 // Does it fit in a signed long long?
321 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000322 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000323 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000324 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000325 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000326 }
327 }
328
329 // If we still couldn't decide a type, we probably have something that
330 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000331 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000332 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000333 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000334 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000335 }
Chris Lattnere4068872008-05-09 05:59:00 +0000336
337 if (ResultVal.getBitWidth() != Width)
338 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000339 }
340
Chris Lattner48d7f382008-04-02 04:24:33 +0000341 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000342 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000343
344 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
345 if (Literal.isImaginary)
346 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
347
348 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000349}
350
Steve Naroff87d58b42007-09-16 03:34:24 +0000351Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000352 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000353 Expr *E = (Expr *)Val;
354 assert((E != 0) && "ActOnParenExpr() missing expr");
355 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000356}
357
358/// The UsualUnaryConversions() function is *not* called by this routine.
359/// See C99 6.3.2.1p[2-4] for more details.
360QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
361 SourceLocation OpLoc, bool isSizeof) {
362 // C99 6.5.3.4p1:
363 if (isa<FunctionType>(exprType) && isSizeof)
364 // alignof(function) is allowed.
365 Diag(OpLoc, diag::ext_sizeof_function_type);
366 else if (exprType->isVoidType())
367 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
368 else if (exprType->isIncompleteType()) {
369 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
370 diag::err_alignof_incomplete_type,
371 exprType.getAsString());
372 return QualType(); // error
373 }
374 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
375 return Context.getSizeType();
376}
377
378Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000379ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000380 SourceLocation LPLoc, TypeTy *Ty,
381 SourceLocation RPLoc) {
382 // If error parsing type, ignore.
383 if (Ty == 0) return true;
384
385 // Verify that this is a valid expression.
386 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
387
388 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
389
390 if (resultType.isNull())
391 return true;
392 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
393}
394
Chris Lattner5110ad52007-08-24 21:41:10 +0000395QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000396 DefaultFunctionArrayConversion(V);
397
Chris Lattnera16e42d2007-08-26 05:39:26 +0000398 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000399 if (const ComplexType *CT = V->getType()->getAsComplexType())
400 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000401
402 // Otherwise they pass through real integer and floating point types here.
403 if (V->getType()->isArithmeticType())
404 return V->getType();
405
406 // Reject anything else.
407 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
408 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000409}
410
411
Chris Lattner4b009652007-07-25 00:24:17 +0000412
Steve Naroff87d58b42007-09-16 03:34:24 +0000413Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000414 tok::TokenKind Kind,
415 ExprTy *Input) {
416 UnaryOperator::Opcode Opc;
417 switch (Kind) {
418 default: assert(0 && "Unknown unary op!");
419 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
420 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
421 }
422 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
423 if (result.isNull())
424 return true;
425 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
426}
427
428Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000429ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000430 ExprTy *Idx, SourceLocation RLoc) {
431 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
432
433 // Perform default conversions.
434 DefaultFunctionArrayConversion(LHSExp);
435 DefaultFunctionArrayConversion(RHSExp);
436
437 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
438
439 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000440 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000441 // in the subscript position. As a result, we need to derive the array base
442 // and index from the expression types.
443 Expr *BaseExpr, *IndexExpr;
444 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000445 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000446 BaseExpr = LHSExp;
447 IndexExpr = RHSExp;
448 // FIXME: need to deal with const...
449 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000450 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000451 // Handle the uncommon case of "123[Ptr]".
452 BaseExpr = RHSExp;
453 IndexExpr = LHSExp;
454 // FIXME: need to deal with const...
455 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000456 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
457 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000458 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000459
460 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000461 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
462 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000463 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000464 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000465 // FIXME: need to deal with const...
466 ResultType = VTy->getElementType();
467 } else {
468 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
469 RHSExp->getSourceRange());
470 }
471 // C99 6.5.2.1p1
472 if (!IndexExpr->getType()->isIntegerType())
473 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
474 IndexExpr->getSourceRange());
475
476 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
477 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000478 // void (*)(int)) and pointers to incomplete types. Functions are not
479 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000480 if (!ResultType->isObjectType())
481 return Diag(BaseExpr->getLocStart(),
482 diag::err_typecheck_subscript_not_object,
483 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
484
485 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
486}
487
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000488QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000489CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000490 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000491 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000492
493 // This flag determines whether or not the component is to be treated as a
494 // special name, or a regular GLSL-style component access.
495 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000496
497 // The vector accessor can't exceed the number of elements.
498 const char *compStr = CompName.getName();
499 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000500 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000501 baseType.getAsString(), SourceRange(CompLoc));
502 return QualType();
503 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000504
505 // Check that we've found one of the special components, or that the component
506 // names must come from the same set.
507 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
508 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
509 SpecialComponent = true;
510 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000511 do
512 compStr++;
513 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
514 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
515 do
516 compStr++;
517 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
518 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
519 do
520 compStr++;
521 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
522 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000523
Nate Begemanc8e51f82008-05-09 06:41:27 +0000524 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000525 // We didn't get to the end of the string. This means the component names
526 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000527 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000528 std::string(compStr,compStr+1), SourceRange(CompLoc));
529 return QualType();
530 }
531 // Each component accessor can't exceed the vector type.
532 compStr = CompName.getName();
533 while (*compStr) {
534 if (vecType->isAccessorWithinNumElements(*compStr))
535 compStr++;
536 else
537 break;
538 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000539 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000540 // We didn't get to the end of the string. This means a component accessor
541 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000542 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000543 baseType.getAsString(), SourceRange(CompLoc));
544 return QualType();
545 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000546
547 // If we have a special component name, verify that the current vector length
548 // is an even number, since all special component names return exactly half
549 // the elements.
550 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
551 return QualType();
552 }
553
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000554 // The component accessor looks fine - now we need to compute the actual type.
555 // The vector type is implied by the component accessor. For example,
556 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000557 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
558 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
559 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000560 if (CompSize == 1)
561 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000562
Nate Begemanaf6ed502008-04-18 23:10:10 +0000563 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000564 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000565 // diagostics look bad. We want extended vector types to appear built-in.
566 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
567 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
568 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000569 }
570 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000571}
572
Chris Lattner4b009652007-07-25 00:24:17 +0000573Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000574ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000575 tok::TokenKind OpKind, SourceLocation MemberLoc,
576 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000577 Expr *BaseExpr = static_cast<Expr *>(Base);
578 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000579
580 // Perform default conversions.
581 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000582
Steve Naroff2cb66382007-07-26 03:11:44 +0000583 QualType BaseType = BaseExpr->getType();
584 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000585
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000586 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
587 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000588 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000589 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000590 BaseType = PT->getPointeeType();
591 else
592 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
593 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000594 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000595
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000596 // Handle field access to simple records. This also handles access to fields
597 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000598 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000599 RecordDecl *RDecl = RTy->getDecl();
600 if (RTy->isIncompleteType())
601 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
602 BaseExpr->getSourceRange());
603 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000604 FieldDecl *MemberDecl = RDecl->getMember(&Member);
605 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000606 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
607 SourceRange(MemberLoc));
Eli Friedman76b49832008-02-06 22:48:16 +0000608
609 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000610 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000611 QualType MemberType = MemberDecl->getType();
612 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000613 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000614 MemberType = MemberType.getQualifiedType(combinedQualifiers);
615
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000616 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000617 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000618 }
619
620 // Handle access to Objective C instance variables, such as "Obj->ivar".
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000621 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
622 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000623 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000624 OpKind == tok::arrow);
Chris Lattner52292be2008-07-21 04:42:08 +0000625 return Diag(OpLoc, diag::err_typecheck_member_reference_ivar,
626 IFTy->getDecl()->getName(), Member.getName(),
627 BaseExpr->getSourceRange(), SourceRange(MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +0000628 }
629
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000630 // Handle property access.
Chris Lattnera57cf472008-07-21 04:28:12 +0000631 if (isObjCObjectPointerType(BaseType)) {
632 const PointerType *pointerType = BaseType->getAsPointerType();
Steve Naroff05391d22008-05-30 00:40:33 +0000633 BaseType = pointerType->getPointeeType();
634 ObjCInterfaceDecl *IFace;
Steve Naroffd1f0eb42008-06-05 13:55:23 +0000635 QualType CanonType = BaseType.getCanonicalType();
636 if (isa<ObjCInterfaceType>(CanonType))
637 IFace = dyn_cast<ObjCInterfaceType>(CanonType)->getDecl();
Steve Naroff05391d22008-05-30 00:40:33 +0000638 else
Steve Naroffd1f0eb42008-06-05 13:55:23 +0000639 IFace = dyn_cast<ObjCQualifiedInterfaceType>(CanonType)->getDecl();
Steve Naroff05391d22008-05-30 00:40:33 +0000640 ObjCInterfaceDecl *clsDeclared;
641 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
642 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
643 OpKind==tok::arrow);
644 // Check for properties.
645 if (OpKind==tok::period) {
646 // Before we look for explicit property declarations, we check for
647 // nullary methods (which allow '.' notation).
648 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
649 ObjCMethodDecl *MD = IFace->lookupInstanceMethod(Sel);
650 if (MD)
651 return new ObjCPropertyRefExpr(MD, MD->getResultType(),
652 MemberLoc, BaseExpr);
653 // FIXME: Need to deal with setter methods that take 1 argument. E.g.:
654 // @interface NSBundle : NSObject {}
655 // - (NSString *)bundlePath;
656 // - (void)setBundlePath:(NSString *)x;
657 // @end
658 // void someMethod() { frameworkBundle.bundlePath = 0; }
659 //
Steve Naroff858813d2008-06-03 21:56:14 +0000660 ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member);
Steve Naroffd1f0eb42008-06-05 13:55:23 +0000661
662 if (!PD) { // Lastly, check protocols on qualified interfaces.
663 if (ObjCQualifiedInterfaceType *QIT =
664 dyn_cast<ObjCQualifiedInterfaceType>(CanonType)) {
665 for (unsigned i = 0; i < QIT->getNumProtocols(); i++)
666 if ((PD = QIT->getProtocols(i)->FindPropertyDeclaration(&Member)))
667 break;
668 }
669 }
Steve Naroff858813d2008-06-03 21:56:14 +0000670 if (PD)
671 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Steve Naroff05391d22008-05-30 00:40:33 +0000672 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000673 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000674
675 // Handle 'field access' to vectors, such as 'V.xx'.
676 if (BaseType->isExtVectorType() && OpKind == tok::period) {
677 // Component access limited to variables (reject vec4.rg.g).
678 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
679 !isa<ExtVectorElementExpr>(BaseExpr))
680 return Diag(OpLoc, diag::err_ext_vector_component_access,
681 SourceRange(MemberLoc));
682 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
683 if (ret.isNull())
684 return true;
685 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
686 }
687
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000688 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
689 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000690}
691
Steve Naroff87d58b42007-09-16 03:34:24 +0000692/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000693/// This provides the location of the left/right parens and a list of comma
694/// locations.
695Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000696ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000697 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000698 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
699 Expr *Fn = static_cast<Expr *>(fn);
700 Expr **Args = reinterpret_cast<Expr**>(args);
701 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +0000702 FunctionDecl *FDecl = NULL;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000703
704 // Promote the function operand.
705 UsualUnaryConversions(Fn);
706
707 // If we're directly calling a function, get the declaration for
708 // that function.
709 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
710 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
711 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
712
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000713 // Make the call expr early, before semantic checks. This guarantees cleanup
714 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +0000715 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000716 Context.BoolTy, RParenLoc));
717
Chris Lattner4b009652007-07-25 00:24:17 +0000718 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
719 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000720 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000721 if (PT == 0)
722 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
723 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000724 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
725 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000726 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
727 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000728
729 // We know the result type of the call, set it.
730 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000731
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000732 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000733 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
734 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000735 unsigned NumArgsInProto = Proto->getNumArgs();
736 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000737
Chris Lattner3e254fb2008-04-08 04:40:51 +0000738 // If too few arguments are available (and we don't have default
739 // arguments for the remaining parameters), don't make the call.
740 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +0000741 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000742 // Use default arguments for missing arguments
743 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +0000744 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000745 } else
746 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
747 Fn->getSourceRange());
748 }
749
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000750 // If too many are passed and not variadic, error on the extras and drop
751 // them.
752 if (NumArgs > NumArgsInProto) {
753 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000754 Diag(Args[NumArgsInProto]->getLocStart(),
755 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
756 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000757 Args[NumArgs-1]->getLocEnd()));
758 // This deletes the extra arguments.
759 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000760 }
761 NumArgsToCheck = NumArgsInProto;
762 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000763
Chris Lattner4b009652007-07-25 00:24:17 +0000764 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000765 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +0000766 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000767
768 Expr *Arg;
769 if (i < NumArgs)
770 Arg = Args[i];
771 else
772 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +0000773 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000774
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000775 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +0000776 AssignConvertType ConvTy =
777 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000778 TheCall->setArg(i, Arg);
779
Chris Lattner005ed752008-01-04 18:04:52 +0000780 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
781 ArgType, Arg, "passing"))
782 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000783 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000784
785 // If this is a variadic call, handle args passed through "...".
786 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +0000787 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000788 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
789 Expr *Arg = Args[i];
790 DefaultArgumentPromotion(Arg);
791 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000792 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000793 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000794 } else {
795 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
796
Steve Naroffdb65e052007-08-28 23:30:39 +0000797 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000798 for (unsigned i = 0; i != NumArgs; i++) {
799 Expr *Arg = Args[i];
800 DefaultArgumentPromotion(Arg);
801 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000802 }
Chris Lattner4b009652007-07-25 00:24:17 +0000803 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000804
Chris Lattner2e64c072007-08-10 20:18:51 +0000805 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +0000806 if (FDecl)
807 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +0000808
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000809 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000810}
811
812Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000813ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000814 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000815 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000816 QualType literalType = QualType::getFromOpaquePtr(Ty);
817 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000818 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000819 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000820
Eli Friedman8c2173d2008-05-20 05:22:08 +0000821 if (literalType->isArrayType()) {
822 if (literalType->getAsVariableArrayType())
823 return Diag(LParenLoc,
824 diag::err_variable_object_no_init,
825 SourceRange(LParenLoc,
826 literalExpr->getSourceRange().getEnd()));
827 } else if (literalType->isIncompleteType()) {
828 return Diag(LParenLoc,
829 diag::err_typecheck_decl_incomplete_type,
830 literalType.getAsString(),
831 SourceRange(LParenLoc,
832 literalExpr->getSourceRange().getEnd()));
833 }
834
Steve Narofff0b23542008-01-10 22:15:12 +0000835 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +0000836 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +0000837
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000838 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +0000839 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +0000840 if (CheckForConstantInitializer(literalExpr, literalType))
841 return true;
842 }
Steve Naroffbe37fc02008-01-14 18:19:28 +0000843 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000844}
845
846Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000847ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000848 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000849 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000850
Steve Naroff0acc9c92007-09-15 18:49:24 +0000851 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000852 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000853
Chris Lattner48d7f382008-04-02 04:24:33 +0000854 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
855 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
856 return E;
Chris Lattner4b009652007-07-25 00:24:17 +0000857}
858
Chris Lattnerd1f26b32007-12-20 00:44:32 +0000859bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000860 assert(VectorTy->isVectorType() && "Not a vector type!");
861
862 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000863 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000864 return Diag(R.getBegin(),
865 Ty->isVectorType() ?
866 diag::err_invalid_conversion_between_vectors :
867 diag::err_invalid_conversion_between_vector_and_integer,
868 VectorTy.getAsString().c_str(),
869 Ty.getAsString().c_str(), R);
870 } else
871 return Diag(R.getBegin(),
872 diag::err_invalid_conversion_between_vector_and_scalar,
873 VectorTy.getAsString().c_str(),
874 Ty.getAsString().c_str(), R);
875
876 return false;
877}
878
Chris Lattner4b009652007-07-25 00:24:17 +0000879Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000880ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000881 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000882 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000883
884 Expr *castExpr = static_cast<Expr*>(Op);
885 QualType castType = QualType::getFromOpaquePtr(Ty);
886
Steve Naroff68adb482007-08-31 00:32:44 +0000887 UsualUnaryConversions(castExpr);
888
Chris Lattner4b009652007-07-25 00:24:17 +0000889 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
890 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000891 if (!castType->isVoidType()) { // Cast to void allows any expr type.
Steve Naroff5ad85292008-06-03 12:56:35 +0000892 if (!castType->isScalarType() && !castType->isVectorType()) {
893 // GCC struct/union extension.
894 if (castType == castExpr->getType() &&
Steve Naroff7f1c5b52008-06-03 13:21:30 +0000895 castType->isStructureType() || castType->isUnionType()) {
896 Diag(LParenLoc, diag::ext_typecheck_cast_nonscalar,
897 SourceRange(LParenLoc, RParenLoc));
898 return new CastExpr(castType, castExpr, LParenLoc);
899 } else
Steve Naroff5ad85292008-06-03 12:56:35 +0000900 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
901 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
902 }
Steve Narofff459ee52008-01-24 22:55:05 +0000903 if (!castExpr->getType()->isScalarType() &&
904 !castExpr->getType()->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000905 return Diag(castExpr->getLocStart(),
906 diag::err_typecheck_expect_scalar_operand,
907 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000908
909 if (castExpr->getType()->isVectorType()) {
910 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
911 castExpr->getType(), castType))
912 return true;
913 } else if (castType->isVectorType()) {
914 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
915 castType, castExpr->getType()))
916 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000917 }
Chris Lattner4b009652007-07-25 00:24:17 +0000918 }
919 return new CastExpr(castType, castExpr, LParenLoc);
920}
921
Chris Lattner98a425c2007-11-26 01:40:58 +0000922/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
923/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000924inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
925 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
926 UsualUnaryConversions(cond);
927 UsualUnaryConversions(lex);
928 UsualUnaryConversions(rex);
929 QualType condT = cond->getType();
930 QualType lexT = lex->getType();
931 QualType rexT = rex->getType();
932
933 // first, check the condition.
934 if (!condT->isScalarType()) { // C99 6.5.15p2
935 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
936 condT.getAsString());
937 return QualType();
938 }
Chris Lattner992ae932008-01-06 22:42:25 +0000939
940 // Now check the two expressions.
941
942 // If both operands have arithmetic type, do the usual arithmetic conversions
943 // to find a common type: C99 6.5.15p3,5.
944 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000945 UsualArithmeticConversions(lex, rex);
946 return lex->getType();
947 }
Chris Lattner992ae932008-01-06 22:42:25 +0000948
949 // If both operands are the same structure or union type, the result is that
950 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000951 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +0000952 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +0000953 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +0000954 // "If both the operands have structure or union type, the result has
955 // that type." This implies that CV qualifiers are dropped.
956 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000957 }
Chris Lattner992ae932008-01-06 22:42:25 +0000958
959 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +0000960 // The following || allows only one side to be void (a GCC-ism).
961 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +0000962 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +0000963 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
964 rex->getSourceRange());
965 if (!rexT->isVoidType())
966 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +0000967 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +0000968 ImpCastExprToType(lex, Context.VoidTy);
969 ImpCastExprToType(rex, Context.VoidTy);
970 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +0000971 }
Steve Naroff12ebf272008-01-08 01:11:38 +0000972 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
973 // the type of the other operand."
974 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000975 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000976 return lexT;
977 }
978 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000979 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000980 return rexT;
981 }
Chris Lattner0ac51632008-01-06 22:50:31 +0000982 // Handle the case where both operands are pointers before we handle null
983 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +0000984 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
985 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
986 // get the "pointed to" types
987 QualType lhptee = LHSPT->getPointeeType();
988 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000989
Chris Lattner71225142007-07-31 21:27:01 +0000990 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
991 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +0000992 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +0000993 // Figure out necessary qualifiers (C99 6.5.15p6)
994 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000995 QualType destType = Context.getPointerType(destPointee);
996 ImpCastExprToType(lex, destType); // add qualifiers if necessary
997 ImpCastExprToType(rex, destType); // promote to void*
998 return destType;
999 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001000 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001001 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001002 QualType destType = Context.getPointerType(destPointee);
1003 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1004 ImpCastExprToType(rex, destType); // promote to void*
1005 return destType;
1006 }
Chris Lattner4b009652007-07-25 00:24:17 +00001007
Steve Naroff85f0dc52007-10-15 20:41:53 +00001008 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1009 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001010 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001011 lexT.getAsString(), rexT.getAsString(),
1012 lex->getSourceRange(), rex->getSourceRange());
Eli Friedman33284862008-01-30 17:02:03 +00001013 // In this situation, we assume void* type. No especially good
1014 // reason, but this is what gcc does, and we do have to pick
1015 // to get a consistent AST.
1016 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
1017 ImpCastExprToType(lex, voidPtrTy);
1018 ImpCastExprToType(rex, voidPtrTy);
1019 return voidPtrTy;
Chris Lattner71225142007-07-31 21:27:01 +00001020 }
1021 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001022 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1023 // differently qualified versions of compatible types, the result type is
1024 // a pointer to an appropriately qualified version of the *composite*
1025 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001026 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001027 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001028 QualType compositeType = lexT;
1029 ImpCastExprToType(lex, compositeType);
1030 ImpCastExprToType(rex, compositeType);
1031 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001032 }
Chris Lattner4b009652007-07-25 00:24:17 +00001033 }
Steve Naroff605896f2008-05-31 22:33:45 +00001034 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1035 // evaluates to "struct objc_object *" (and is handled above when comparing
1036 // id with statically typed objects). FIXME: Do we need an ImpCastExprToType?
1037 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1038 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true))
1039 return Context.getObjCIdType();
1040 }
Chris Lattner992ae932008-01-06 22:42:25 +00001041 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001042 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1043 lexT.getAsString(), rexT.getAsString(),
1044 lex->getSourceRange(), rex->getSourceRange());
1045 return QualType();
1046}
1047
Steve Naroff87d58b42007-09-16 03:34:24 +00001048/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001049/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001050Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001051 SourceLocation ColonLoc,
1052 ExprTy *Cond, ExprTy *LHS,
1053 ExprTy *RHS) {
1054 Expr *CondExpr = (Expr *) Cond;
1055 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001056
1057 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1058 // was the condition.
1059 bool isLHSNull = LHSExpr == 0;
1060 if (isLHSNull)
1061 LHSExpr = CondExpr;
1062
Chris Lattner4b009652007-07-25 00:24:17 +00001063 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1064 RHSExpr, QuestionLoc);
1065 if (result.isNull())
1066 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001067 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1068 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001069}
1070
Steve Naroffdb65e052007-08-28 23:30:39 +00001071/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Steve Naroffbbaed752008-01-29 02:42:22 +00001072/// do not have a prototype. Arguments that have type float are promoted to
1073/// double. All other argument types are converted by UsualUnaryConversions().
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001074void Sema::DefaultArgumentPromotion(Expr *&Expr) {
1075 QualType Ty = Expr->getType();
1076 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffdb65e052007-08-28 23:30:39 +00001077
Chris Lattner11216032008-06-27 22:48:56 +00001078 // If this is a 'float' (CVR qualified or typedef) promote to double.
1079 if (const BuiltinType *BT = Ty->getAsBuiltinType())
1080 if (BT->getKind() == BuiltinType::Float)
1081 return ImpCastExprToType(Expr, Context.DoubleTy);
1082
1083 UsualUnaryConversions(Expr);
Steve Naroffdb65e052007-08-28 23:30:39 +00001084}
1085
Chris Lattner4b009652007-07-25 00:24:17 +00001086/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Chris Lattner48d7f382008-04-02 04:24:33 +00001087void Sema::DefaultFunctionArrayConversion(Expr *&E) {
1088 QualType Ty = E->getType();
1089 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001090
Chris Lattner48d7f382008-04-02 04:24:33 +00001091 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
Chris Lattnera05f7d22008-04-02 17:45:06 +00001092 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
Chris Lattner48d7f382008-04-02 04:24:33 +00001093 Ty = E->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001094 }
Chris Lattner48d7f382008-04-02 04:24:33 +00001095 if (Ty->isFunctionType())
1096 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner19eb97e2008-04-02 05:18:44 +00001097 else if (Ty->isArrayType())
1098 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
Chris Lattner4b009652007-07-25 00:24:17 +00001099}
1100
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001101/// UsualUnaryConversions - Performs various conversions that are common to most
Chris Lattner4b009652007-07-25 00:24:17 +00001102/// operators (C99 6.3). The conversions of array and function types are
1103/// sometimes surpressed. For example, the array->pointer conversion doesn't
1104/// apply if the array is an argument to the sizeof or address (&) operators.
1105/// In these instances, this routine should *not* be called.
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001106Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
1107 QualType Ty = Expr->getType();
1108 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001109
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001110 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
Chris Lattnera05f7d22008-04-02 17:45:06 +00001111 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001112 Ty = Expr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001113 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001114 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
Chris Lattnere992d6c2008-01-16 19:17:22 +00001115 ImpCastExprToType(Expr, Context.IntTy);
Chris Lattner4b009652007-07-25 00:24:17 +00001116 else
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001117 DefaultFunctionArrayConversion(Expr);
1118
1119 return Expr;
Chris Lattner4b009652007-07-25 00:24:17 +00001120}
1121
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001122/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +00001123/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1124/// routine returns the first non-arithmetic type found. The client is
1125/// responsible for emitting appropriate error diagnostics.
Chris Lattner48d7f382008-04-02 04:24:33 +00001126/// FIXME: verify the conversion rules for "complex int" are consistent with
1127/// GCC.
Steve Naroff8f708362007-08-24 19:07:16 +00001128QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
1129 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +00001130 if (!isCompAssign) {
1131 UsualUnaryConversions(lhsExpr);
1132 UsualUnaryConversions(rhsExpr);
1133 }
Steve Naroff7438fdf2007-10-18 18:55:53 +00001134 // For conversion purposes, we ignore any qualifiers.
1135 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +00001136 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
1137 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001138
1139 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +00001140 if (lhs == rhs)
1141 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001142
1143 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1144 // The caller can deal with this (e.g. pointer + int).
1145 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001146 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001147
1148 // At this point, we have two different arithmetic types.
1149
1150 // Handle complex types first (C99 6.3.1.8p1).
1151 if (lhs->isComplexType() || rhs->isComplexType()) {
Steve Naroff43001212008-01-15 19:36:10 +00001152 // if we have an integer operand, the result is the complex type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001153 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001154 // convert the rhs to the lhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001155 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001156 return lhs;
Steve Naroff43001212008-01-15 19:36:10 +00001157 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001158 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001159 // convert the lhs to the rhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001160 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001161 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001162 }
Steve Naroff3cf497f2007-08-27 01:27:54 +00001163 // This handles complex/complex, complex/float, or float/complex.
1164 // When both operands are complex, the shorter operand is converted to the
1165 // type of the longer, and that is the type of the result. This corresponds
1166 // to what is done when combining two real floating-point operands.
1167 // The fun begins when size promotion occur across type domains.
1168 // From H&S 6.3.4: When one operand is complex and the other is a real
1169 // floating-point type, the less precise type is converted, within it's
1170 // real or complex domain, to the precision of the other type. For example,
1171 // when combining a "long double" with a "double _Complex", the
1172 // "double _Complex" is promoted to "long double _Complex".
Chris Lattnerd7135b42008-04-06 23:38:49 +00001173 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Naroff45fc9822007-08-27 15:30:22 +00001174
1175 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +00001176 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
1177 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001178 ImpCastExprToType(rhsExpr, rhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001179 } else if (result < 0) { // The right side is bigger, convert lhs.
1180 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
1181 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001182 ImpCastExprToType(lhsExpr, lhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001183 }
1184 // At this point, lhs and rhs have the same rank/size. Now, make sure the
1185 // domains match. This is a requirement for our implementation, C99
1186 // does not require this promotion.
1187 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1188 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001189 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001190 ImpCastExprToType(lhsExpr, rhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001191 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001192 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001193 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001194 ImpCastExprToType(rhsExpr, lhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001195 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001196 }
Chris Lattner4b009652007-07-25 00:24:17 +00001197 }
Steve Naroff3b6157f2007-08-27 21:43:43 +00001198 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +00001199 }
1200 // Now handle "real" floating types (i.e. float, double, long double).
1201 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1202 // if we have an integer operand, the result is the real floating type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001203 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001204 // convert rhs to the lhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001205 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001206 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001207 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001208 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001209 // convert lhs to the rhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001210 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001211 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001212 }
1213 // We have two real floating types, float/complex combos were handled above.
1214 // Convert the smaller operand to the bigger result.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001215 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Naroff45fc9822007-08-27 15:30:22 +00001216
1217 if (result > 0) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001218 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001219 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001220 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001221 if (result < 0) { // convert the lhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001222 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff45fc9822007-08-27 15:30:22 +00001223 return rhs;
1224 }
1225 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001226 }
Steve Naroff43001212008-01-15 19:36:10 +00001227 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
1228 // Handle GCC complex int extension.
Steve Naroff43001212008-01-15 19:36:10 +00001229 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
Eli Friedman50727042008-02-08 01:19:44 +00001230 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
Steve Naroff43001212008-01-15 19:36:10 +00001231
Eli Friedman50727042008-02-08 01:19:44 +00001232 if (lhsComplexInt && rhsComplexInt) {
Chris Lattner51285d82008-04-06 23:55:33 +00001233 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
1234 rhsComplexInt->getElementType()) >= 0) {
Eli Friedman94075c02008-02-08 01:24:30 +00001235 // convert the rhs
1236 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1237 return lhs;
Eli Friedman50727042008-02-08 01:19:44 +00001238 }
1239 if (!isCompAssign)
Eli Friedman94075c02008-02-08 01:24:30 +00001240 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Eli Friedman50727042008-02-08 01:19:44 +00001241 return rhs;
1242 } else if (lhsComplexInt && rhs->isIntegerType()) {
1243 // convert the rhs to the lhs complex type.
1244 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1245 return lhs;
1246 } else if (rhsComplexInt && lhs->isIntegerType()) {
1247 // convert the lhs to the rhs complex type.
1248 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1249 return rhs;
1250 }
Steve Naroff43001212008-01-15 19:36:10 +00001251 }
Chris Lattner4b009652007-07-25 00:24:17 +00001252 // Finally, we have two differing integer types.
Eli Friedman0832dbc2008-06-28 06:23:08 +00001253 // The rules for this case are in C99 6.3.1.8
1254 int compare = Context.getIntegerTypeOrder(lhs, rhs);
1255 bool lhsSigned = lhs->isSignedIntegerType(),
1256 rhsSigned = rhs->isSignedIntegerType();
1257 QualType destType;
1258 if (lhsSigned == rhsSigned) {
1259 // Same signedness; use the higher-ranked type
1260 destType = compare >= 0 ? lhs : rhs;
1261 } else if (compare != (lhsSigned ? 1 : -1)) {
1262 // The unsigned type has greater than or equal rank to the
1263 // signed type, so use the unsigned type
1264 destType = lhsSigned ? rhs : lhs;
1265 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
1266 // The two types are different widths; if we are here, that
1267 // means the signed type is larger than the unsigned type, so
1268 // use the signed type.
1269 destType = lhsSigned ? lhs : rhs;
1270 } else {
1271 // The signed type is higher-ranked than the unsigned type,
1272 // but isn't actually any bigger (like unsigned int and long
1273 // on most 32-bit systems). Use the unsigned type corresponding
1274 // to the signed type.
1275 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00001276 }
Eli Friedman0832dbc2008-06-28 06:23:08 +00001277 if (!isCompAssign) {
1278 ImpCastExprToType(lhsExpr, destType);
1279 ImpCastExprToType(rhsExpr, destType);
1280 }
1281 return destType;
Chris Lattner4b009652007-07-25 00:24:17 +00001282}
1283
1284// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1285// being closely modeled after the C99 spec:-). The odd characteristic of this
1286// routine is it effectively iqnores the qualifiers on the top level pointee.
1287// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1288// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001289Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001290Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1291 QualType lhptee, rhptee;
1292
1293 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001294 lhptee = lhsType->getAsPointerType()->getPointeeType();
1295 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001296
1297 // make sure we operate on the canonical type
1298 lhptee = lhptee.getCanonicalType();
1299 rhptee = rhptee.getCanonicalType();
1300
Chris Lattner005ed752008-01-04 18:04:52 +00001301 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001302
1303 // C99 6.5.16.1p1: This following citation is common to constraints
1304 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1305 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001306 // FIXME: Handle ASQualType
1307 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1308 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001309 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001310
1311 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1312 // incomplete type and the other is a pointer to a qualified or unqualified
1313 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001314 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001315 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001316 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001317
1318 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001319 assert(rhptee->isFunctionType());
1320 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001321 }
1322
1323 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001324 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001325 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001326
1327 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001328 assert(lhptee->isFunctionType());
1329 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001330 }
1331
Chris Lattner4b009652007-07-25 00:24:17 +00001332 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1333 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001334 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1335 rhptee.getUnqualifiedType()))
1336 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001337 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001338}
1339
1340/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1341/// has code to accommodate several GCC extensions when type checking
1342/// pointers. Here are some objectionable examples that GCC considers warnings:
1343///
1344/// int a, *pint;
1345/// short *pshort;
1346/// struct foo *pfoo;
1347///
1348/// pint = pshort; // warning: assignment from incompatible pointer type
1349/// a = pint; // warning: assignment makes integer from pointer without a cast
1350/// pint = a; // warning: assignment makes pointer from integer without a cast
1351/// pint = pfoo; // warning: assignment from incompatible pointer type
1352///
1353/// As a result, the code for dealing with pointers is more complex than the
1354/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001355///
Chris Lattner005ed752008-01-04 18:04:52 +00001356Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001357Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001358 // Get canonical types. We're not formatting these types, just comparing
1359 // them.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001360 lhsType = lhsType.getCanonicalType().getUnqualifiedType();
1361 rhsType = rhsType.getCanonicalType().getUnqualifiedType();
1362
1363 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001364 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001365
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001366 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001367 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001368 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001369 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001370 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001371
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001372 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1373 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001374 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001375 // Relax integer conversions like we do for pointers below.
1376 if (rhsType->isIntegerType())
1377 return IntToPointer;
1378 if (lhsType->isIntegerType())
1379 return PointerToInt;
Chris Lattner1853da22008-01-04 23:18:45 +00001380 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001381 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001382
Nate Begemanc5f0f652008-07-14 18:02:46 +00001383 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001384 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001385 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1386 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001387 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001388
Nate Begemanc5f0f652008-07-14 18:02:46 +00001389 // If we are allowing lax vector conversions, and LHS and RHS are both
1390 // vectors, the total size only needs to be the same. This is a bitcast;
1391 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001392 if (getLangOptions().LaxVectorConversions &&
1393 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001394 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1395 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001396 }
1397 return Incompatible;
1398 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001399
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001400 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001401 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001402
Chris Lattner390564e2008-04-07 06:49:41 +00001403 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001404 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001405 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001406
Chris Lattner390564e2008-04-07 06:49:41 +00001407 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001408 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001409 return Incompatible;
1410 }
1411
Chris Lattner390564e2008-04-07 06:49:41 +00001412 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001413 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001414 if (lhsType == Context.BoolTy)
1415 return Compatible;
1416
1417 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001418 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001419
Chris Lattner390564e2008-04-07 06:49:41 +00001420 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001421 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001422 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001423 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001424
Chris Lattner1853da22008-01-04 23:18:45 +00001425 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001426 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001427 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001428 }
1429 return Incompatible;
1430}
1431
Chris Lattner005ed752008-01-04 18:04:52 +00001432Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001433Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001434 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1435 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001436 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001437 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001438 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001439 return Compatible;
1440 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001441 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001442 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001443 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001444 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001445 //
1446 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1447 // are better understood.
1448 if (!lhsType->isReferenceType())
1449 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001450
Chris Lattner005ed752008-01-04 18:04:52 +00001451 Sema::AssignConvertType result =
1452 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001453
1454 // C99 6.5.16.1p2: The value of the right operand is converted to the
1455 // type of the assignment expression.
1456 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001457 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001458 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001459}
1460
Chris Lattner005ed752008-01-04 18:04:52 +00001461Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001462Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1463 return CheckAssignmentConstraints(lhsType, rhsType);
1464}
1465
Chris Lattner2c8bff72007-12-12 05:47:28 +00001466QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001467 Diag(loc, diag::err_typecheck_invalid_operands,
1468 lex->getType().getAsString(), rex->getType().getAsString(),
1469 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001470 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001471}
1472
1473inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1474 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001475 // For conversion purposes, we ignore any qualifiers.
1476 // For example, "const float" and "float" are equivalent.
1477 QualType lhsType = lex->getType().getCanonicalType().getUnqualifiedType();
1478 QualType rhsType = rex->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001479
Nate Begemanc5f0f652008-07-14 18:02:46 +00001480 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001481 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001482 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001483
Nate Begemanc5f0f652008-07-14 18:02:46 +00001484 // Handle the case of a vector & extvector type of the same size and element
1485 // type. It would be nice if we only had one vector type someday.
1486 if (getLangOptions().LaxVectorConversions)
1487 if (const VectorType *LV = lhsType->getAsVectorType())
1488 if (const VectorType *RV = rhsType->getAsVectorType())
1489 if (LV->getElementType() == RV->getElementType() &&
1490 LV->getNumElements() == RV->getNumElements())
1491 return lhsType->isExtVectorType() ? lhsType : rhsType;
1492
1493 // If the lhs is an extended vector and the rhs is a scalar of the same type
1494 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001495 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001496 QualType eltType = V->getElementType();
1497
1498 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1499 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1500 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001501 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001502 return lhsType;
1503 }
1504 }
1505
Nate Begemanc5f0f652008-07-14 18:02:46 +00001506 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001507 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001508 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001509 QualType eltType = V->getElementType();
1510
1511 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1512 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1513 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001514 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001515 return rhsType;
1516 }
1517 }
1518
Chris Lattner4b009652007-07-25 00:24:17 +00001519 // You cannot convert between vector values of different size.
1520 Diag(loc, diag::err_typecheck_vector_not_convertable,
1521 lex->getType().getAsString(), rex->getType().getAsString(),
1522 lex->getSourceRange(), rex->getSourceRange());
1523 return QualType();
1524}
1525
1526inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001527 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001528{
1529 QualType lhsType = lex->getType(), rhsType = rex->getType();
1530
1531 if (lhsType->isVectorType() || rhsType->isVectorType())
1532 return CheckVectorOperands(loc, lex, rex);
1533
Steve Naroff8f708362007-08-24 19:07:16 +00001534 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001535
Chris Lattner4b009652007-07-25 00:24:17 +00001536 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001537 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001538 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001539}
1540
1541inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001542 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001543{
1544 QualType lhsType = lex->getType(), rhsType = rex->getType();
1545
Steve Naroff8f708362007-08-24 19:07:16 +00001546 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001547
Chris Lattner4b009652007-07-25 00:24:17 +00001548 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001549 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001550 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001551}
1552
1553inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001554 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001555{
1556 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1557 return CheckVectorOperands(loc, lex, rex);
1558
Steve Naroff8f708362007-08-24 19:07:16 +00001559 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001560
Chris Lattner4b009652007-07-25 00:24:17 +00001561 // handle the common case first (both operands are arithmetic).
1562 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001563 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001564
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001565 // Put any potential pointer into PExp
1566 Expr* PExp = lex, *IExp = rex;
1567 if (IExp->getType()->isPointerType())
1568 std::swap(PExp, IExp);
1569
1570 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1571 if (IExp->getType()->isIntegerType()) {
1572 // Check for arithmetic on pointers to incomplete types
1573 if (!PTy->getPointeeType()->isObjectType()) {
1574 if (PTy->getPointeeType()->isVoidType()) {
1575 Diag(loc, diag::ext_gnu_void_ptr,
1576 lex->getSourceRange(), rex->getSourceRange());
1577 } else {
1578 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1579 lex->getType().getAsString(), lex->getSourceRange());
1580 return QualType();
1581 }
1582 }
1583 return PExp->getType();
1584 }
1585 }
1586
Chris Lattner2c8bff72007-12-12 05:47:28 +00001587 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001588}
1589
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001590// C99 6.5.6
1591QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1592 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001593 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1594 return CheckVectorOperands(loc, lex, rex);
1595
Steve Naroff8f708362007-08-24 19:07:16 +00001596 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001597
Chris Lattnerf6da2912007-12-09 21:53:25 +00001598 // Enforce type constraints: C99 6.5.6p3.
1599
1600 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001601 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001602 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001603
1604 // Either ptr - int or ptr - ptr.
1605 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001606 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001607
Chris Lattnerf6da2912007-12-09 21:53:25 +00001608 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001609 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001610 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001611 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001612 Diag(loc, diag::ext_gnu_void_ptr,
1613 lex->getSourceRange(), rex->getSourceRange());
1614 } else {
1615 Diag(loc, diag::err_typecheck_sub_ptr_object,
1616 lex->getType().getAsString(), lex->getSourceRange());
1617 return QualType();
1618 }
1619 }
1620
1621 // The result type of a pointer-int computation is the pointer type.
1622 if (rex->getType()->isIntegerType())
1623 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001624
Chris Lattnerf6da2912007-12-09 21:53:25 +00001625 // Handle pointer-pointer subtractions.
1626 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001627 QualType rpointee = RHSPTy->getPointeeType();
1628
Chris Lattnerf6da2912007-12-09 21:53:25 +00001629 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001630 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001631 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001632 if (rpointee->isVoidType()) {
1633 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001634 Diag(loc, diag::ext_gnu_void_ptr,
1635 lex->getSourceRange(), rex->getSourceRange());
1636 } else {
1637 Diag(loc, diag::err_typecheck_sub_ptr_object,
1638 rex->getType().getAsString(), rex->getSourceRange());
1639 return QualType();
1640 }
1641 }
1642
1643 // Pointee types must be compatible.
Steve Naroff577f9722008-01-29 18:58:14 +00001644 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1645 rpointee.getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001646 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1647 lex->getType().getAsString(), rex->getType().getAsString(),
1648 lex->getSourceRange(), rex->getSourceRange());
1649 return QualType();
1650 }
1651
1652 return Context.getPointerDiffType();
1653 }
1654 }
1655
Chris Lattner2c8bff72007-12-12 05:47:28 +00001656 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001657}
1658
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001659// C99 6.5.7
1660QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1661 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00001662 // C99 6.5.7p2: Each of the operands shall have integer type.
1663 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1664 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001665
Chris Lattner2c8bff72007-12-12 05:47:28 +00001666 // Shifts don't perform usual arithmetic conversions, they just do integer
1667 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001668 if (!isCompAssign)
1669 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001670 UsualUnaryConversions(rex);
1671
1672 // "The type of the result is that of the promoted left operand."
1673 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001674}
1675
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001676// C99 6.5.8
1677QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1678 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001679 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1680 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1681
Chris Lattner254f3bc2007-08-26 01:18:55 +00001682 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001683 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1684 UsualArithmeticConversions(lex, rex);
1685 else {
1686 UsualUnaryConversions(lex);
1687 UsualUnaryConversions(rex);
1688 }
Chris Lattner4b009652007-07-25 00:24:17 +00001689 QualType lType = lex->getType();
1690 QualType rType = rex->getType();
1691
Ted Kremenek486509e2007-10-29 17:13:39 +00001692 // For non-floating point types, check for self-comparisons of the form
1693 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1694 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001695 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001696 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1697 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001698 if (DRL->getDecl() == DRR->getDecl())
1699 Diag(loc, diag::warn_selfcomparison);
1700 }
1701
Chris Lattner254f3bc2007-08-26 01:18:55 +00001702 if (isRelational) {
1703 if (lType->isRealType() && rType->isRealType())
1704 return Context.IntTy;
1705 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001706 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001707 if (lType->isFloatingType()) {
1708 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001709 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001710 }
1711
Chris Lattner254f3bc2007-08-26 01:18:55 +00001712 if (lType->isArithmeticType() && rType->isArithmeticType())
1713 return Context.IntTy;
1714 }
Chris Lattner4b009652007-07-25 00:24:17 +00001715
Chris Lattner22be8422007-08-26 01:10:14 +00001716 bool LHSIsNull = lex->isNullPointerConstant(Context);
1717 bool RHSIsNull = rex->isNullPointerConstant(Context);
1718
Chris Lattner254f3bc2007-08-26 01:18:55 +00001719 // All of the following pointer related warnings are GCC extensions, except
1720 // when handling null pointer constants. One day, we can consider making them
1721 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001722 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001723 QualType LCanPointeeTy =
1724 lType->getAsPointerType()->getPointeeType().getCanonicalType();
1725 QualType RCanPointeeTy =
1726 rType->getAsPointerType()->getPointeeType().getCanonicalType();
Eli Friedman50727042008-02-08 01:19:44 +00001727
Steve Naroff3b435622007-11-13 14:57:38 +00001728 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001729 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1730 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
1731 RCanPointeeTy.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001732 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1733 lType.getAsString(), rType.getAsString(),
1734 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001735 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001736 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001737 return Context.IntTy;
1738 }
Steve Naroff936c4362008-06-03 14:04:54 +00001739 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
1740 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
1741 ImpCastExprToType(rex, lType);
1742 return Context.IntTy;
1743 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001744 }
Steve Naroff936c4362008-06-03 14:04:54 +00001745 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
1746 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001747 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001748 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1749 lType.getAsString(), rType.getAsString(),
1750 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001751 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001752 return Context.IntTy;
1753 }
Steve Naroff936c4362008-06-03 14:04:54 +00001754 if (lType->isIntegerType() &&
1755 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00001756 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001757 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1758 lType.getAsString(), rType.getAsString(),
1759 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001760 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001761 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001762 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001763 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001764}
1765
Nate Begemanc5f0f652008-07-14 18:02:46 +00001766/// CheckVectorCompareOperands - vector comparisons are a clang extension that
1767/// operates on extended vector types. Instead of producing an IntTy result,
1768/// like a scalar comparison, a vector comparison produces a vector of integer
1769/// types.
1770QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
1771 SourceLocation loc,
1772 bool isRelational) {
1773 // Check to make sure we're operating on vectors of the same type and width,
1774 // Allowing one side to be a scalar of element type.
1775 QualType vType = CheckVectorOperands(loc, lex, rex);
1776 if (vType.isNull())
1777 return vType;
1778
1779 QualType lType = lex->getType();
1780 QualType rType = rex->getType();
1781
1782 // For non-floating point types, check for self-comparisons of the form
1783 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1784 // often indicate logic errors in the program.
1785 if (!lType->isFloatingType()) {
1786 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1787 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1788 if (DRL->getDecl() == DRR->getDecl())
1789 Diag(loc, diag::warn_selfcomparison);
1790 }
1791
1792 // Check for comparisons of floating point operands using != and ==.
1793 if (!isRelational && lType->isFloatingType()) {
1794 assert (rType->isFloatingType());
1795 CheckFloatComparison(loc,lex,rex);
1796 }
1797
1798 // Return the type for the comparison, which is the same as vector type for
1799 // integer vectors, or an integer type of identical size and number of
1800 // elements for floating point vectors.
1801 if (lType->isIntegerType())
1802 return lType;
1803
1804 const VectorType *VTy = lType->getAsVectorType();
1805
1806 // FIXME: need to deal with non-32b int / non-64b long long
1807 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
1808 if (TypeSize == 32) {
1809 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
1810 }
1811 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
1812 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
1813}
1814
Chris Lattner4b009652007-07-25 00:24:17 +00001815inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001816 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001817{
1818 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1819 return CheckVectorOperands(loc, lex, rex);
1820
Steve Naroff8f708362007-08-24 19:07:16 +00001821 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001822
1823 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001824 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001825 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001826}
1827
1828inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1829 Expr *&lex, Expr *&rex, SourceLocation loc)
1830{
1831 UsualUnaryConversions(lex);
1832 UsualUnaryConversions(rex);
1833
Eli Friedmanbea3f842008-05-13 20:16:47 +00001834 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00001835 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001836 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001837}
1838
1839inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001840 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001841{
1842 QualType lhsType = lex->getType();
1843 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner4b009652007-07-25 00:24:17 +00001844 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1845
1846 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001847 case Expr::MLV_Valid:
1848 break;
1849 case Expr::MLV_ConstQualified:
1850 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1851 return QualType();
1852 case Expr::MLV_ArrayType:
1853 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1854 lhsType.getAsString(), lex->getSourceRange());
1855 return QualType();
1856 case Expr::MLV_NotObjectType:
1857 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1858 lhsType.getAsString(), lex->getSourceRange());
1859 return QualType();
1860 case Expr::MLV_InvalidExpression:
1861 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1862 lex->getSourceRange());
1863 return QualType();
1864 case Expr::MLV_IncompleteType:
1865 case Expr::MLV_IncompleteVoidType:
1866 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1867 lhsType.getAsString(), lex->getSourceRange());
1868 return QualType();
1869 case Expr::MLV_DuplicateVectorComponents:
1870 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1871 lex->getSourceRange());
1872 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001873 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001874
Chris Lattner005ed752008-01-04 18:04:52 +00001875 AssignConvertType ConvTy;
1876 if (compoundType.isNull())
1877 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1878 else
1879 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1880
1881 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1882 rex, "assigning"))
1883 return QualType();
1884
Chris Lattner4b009652007-07-25 00:24:17 +00001885 // C99 6.5.16p3: The type of an assignment expression is the type of the
1886 // left operand unless the left operand has qualified type, in which case
1887 // it is the unqualified version of the type of the left operand.
1888 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1889 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001890 // C++ 5.17p1: the type of the assignment expression is that of its left
1891 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001892 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001893}
1894
1895inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1896 Expr *&lex, Expr *&rex, SourceLocation loc) {
1897 UsualUnaryConversions(rex);
1898 return rex->getType();
1899}
1900
1901/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1902/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1903QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1904 QualType resType = op->getType();
1905 assert(!resType.isNull() && "no type for increment/decrement expression");
1906
Steve Naroffd30e1932007-08-24 17:20:07 +00001907 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001908 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001909 if (pt->getPointeeType()->isVoidType()) {
1910 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
1911 } else if (!pt->getPointeeType()->isObjectType()) {
1912 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00001913 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1914 resType.getAsString(), op->getSourceRange());
1915 return QualType();
1916 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001917 } else if (!resType->isRealType()) {
1918 if (resType->isComplexType())
1919 // C99 does not support ++/-- on complex types.
1920 Diag(OpLoc, diag::ext_integer_increment_complex,
1921 resType.getAsString(), op->getSourceRange());
1922 else {
1923 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1924 resType.getAsString(), op->getSourceRange());
1925 return QualType();
1926 }
Chris Lattner4b009652007-07-25 00:24:17 +00001927 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001928 // At this point, we know we have a real, complex or pointer type.
1929 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001930 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1931 if (mlval != Expr::MLV_Valid) {
1932 // FIXME: emit a more precise diagnostic...
1933 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1934 op->getSourceRange());
1935 return QualType();
1936 }
1937 return resType;
1938}
1939
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001940/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00001941/// This routine allows us to typecheck complex/recursive expressions
1942/// where the declaration is needed for type checking. Here are some
1943/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
Chris Lattner48d7f382008-04-02 04:24:33 +00001944static ValueDecl *getPrimaryDecl(Expr *E) {
1945 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001946 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001947 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001948 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001949 // Fields cannot be declared with a 'register' storage class.
1950 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00001951 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00001952 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00001953 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001954 case Stmt::ArraySubscriptExprClass: {
1955 // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer.
1956
Chris Lattner48d7f382008-04-02 04:24:33 +00001957 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00001958 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001959 return 0;
1960 else
1961 return VD;
1962 }
Chris Lattner4b009652007-07-25 00:24:17 +00001963 case Stmt::UnaryOperatorClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001964 return getPrimaryDecl(cast<UnaryOperator>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001965 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001966 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001967 case Stmt::ImplicitCastExprClass:
1968 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00001969 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001970 default:
1971 return 0;
1972 }
1973}
1974
1975/// CheckAddressOfOperand - The operand of & must be either a function
1976/// designator or an lvalue designating an object. If it is an lvalue, the
1977/// object cannot be declared with storage class register or be a bit field.
1978/// Note: The usual conversions are *not* applied to the operand of the &
1979/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1980QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001981 if (getLangOptions().C99) {
1982 // Implement C99-only parts of addressof rules.
1983 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
1984 if (uOp->getOpcode() == UnaryOperator::Deref)
1985 // Per C99 6.5.3.2, the address of a deref always returns a valid result
1986 // (assuming the deref expression is valid).
1987 return uOp->getSubExpr()->getType();
1988 }
1989 // Technically, there should be a check for array subscript
1990 // expressions here, but the result of one is always an lvalue anyway.
1991 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001992 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner4b009652007-07-25 00:24:17 +00001993 Expr::isLvalueResult lval = op->isLvalue();
1994
1995 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001996 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1997 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001998 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1999 op->getSourceRange());
2000 return QualType();
2001 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002002 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2003 if (MemExpr->getMemberDecl()->isBitField()) {
2004 Diag(OpLoc, diag::err_typecheck_address_of,
2005 std::string("bit-field"), op->getSourceRange());
2006 return QualType();
2007 }
2008 // Check for Apple extension for accessing vector components.
2009 } else if (isa<ArraySubscriptExpr>(op) &&
2010 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2011 Diag(OpLoc, diag::err_typecheck_address_of,
2012 std::string("vector"), op->getSourceRange());
2013 return QualType();
2014 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002015 // We have an lvalue with a decl. Make sure the decl is not declared
2016 // with the register storage-class specifier.
2017 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2018 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002019 Diag(OpLoc, diag::err_typecheck_address_of,
2020 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002021 return QualType();
2022 }
2023 } else
2024 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002025 }
2026 // If the operand has type "type", the result has type "pointer to type".
2027 return Context.getPointerType(op->getType());
2028}
2029
2030QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2031 UsualUnaryConversions(op);
2032 QualType qType = op->getType();
2033
Chris Lattner7931f4a2007-07-31 16:53:04 +00002034 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002035 // Note that per both C89 and C99, this is always legal, even
2036 // if ptype is an incomplete type or void.
2037 // It would be possible to warn about dereferencing a
2038 // void pointer, but it's completely well-defined,
2039 // and such a warning is unlikely to catch any mistakes.
2040 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002041 }
2042 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2043 qType.getAsString(), op->getSourceRange());
2044 return QualType();
2045}
2046
2047static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2048 tok::TokenKind Kind) {
2049 BinaryOperator::Opcode Opc;
2050 switch (Kind) {
2051 default: assert(0 && "Unknown binop!");
2052 case tok::star: Opc = BinaryOperator::Mul; break;
2053 case tok::slash: Opc = BinaryOperator::Div; break;
2054 case tok::percent: Opc = BinaryOperator::Rem; break;
2055 case tok::plus: Opc = BinaryOperator::Add; break;
2056 case tok::minus: Opc = BinaryOperator::Sub; break;
2057 case tok::lessless: Opc = BinaryOperator::Shl; break;
2058 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2059 case tok::lessequal: Opc = BinaryOperator::LE; break;
2060 case tok::less: Opc = BinaryOperator::LT; break;
2061 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2062 case tok::greater: Opc = BinaryOperator::GT; break;
2063 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2064 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2065 case tok::amp: Opc = BinaryOperator::And; break;
2066 case tok::caret: Opc = BinaryOperator::Xor; break;
2067 case tok::pipe: Opc = BinaryOperator::Or; break;
2068 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2069 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2070 case tok::equal: Opc = BinaryOperator::Assign; break;
2071 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2072 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2073 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2074 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2075 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2076 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2077 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2078 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2079 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2080 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2081 case tok::comma: Opc = BinaryOperator::Comma; break;
2082 }
2083 return Opc;
2084}
2085
2086static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2087 tok::TokenKind Kind) {
2088 UnaryOperator::Opcode Opc;
2089 switch (Kind) {
2090 default: assert(0 && "Unknown unary op!");
2091 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2092 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2093 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2094 case tok::star: Opc = UnaryOperator::Deref; break;
2095 case tok::plus: Opc = UnaryOperator::Plus; break;
2096 case tok::minus: Opc = UnaryOperator::Minus; break;
2097 case tok::tilde: Opc = UnaryOperator::Not; break;
2098 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2099 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2100 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2101 case tok::kw___real: Opc = UnaryOperator::Real; break;
2102 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2103 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2104 }
2105 return Opc;
2106}
2107
2108// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002109Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002110 ExprTy *LHS, ExprTy *RHS) {
2111 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2112 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2113
Steve Naroff87d58b42007-09-16 03:34:24 +00002114 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2115 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002116
2117 QualType ResultTy; // Result type of the binary operator.
2118 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2119
2120 switch (Opc) {
2121 default:
2122 assert(0 && "Unknown binary expr!");
2123 case BinaryOperator::Assign:
2124 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2125 break;
2126 case BinaryOperator::Mul:
2127 case BinaryOperator::Div:
2128 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2129 break;
2130 case BinaryOperator::Rem:
2131 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2132 break;
2133 case BinaryOperator::Add:
2134 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2135 break;
2136 case BinaryOperator::Sub:
2137 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2138 break;
2139 case BinaryOperator::Shl:
2140 case BinaryOperator::Shr:
2141 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2142 break;
2143 case BinaryOperator::LE:
2144 case BinaryOperator::LT:
2145 case BinaryOperator::GE:
2146 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002147 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002148 break;
2149 case BinaryOperator::EQ:
2150 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002151 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00002152 break;
2153 case BinaryOperator::And:
2154 case BinaryOperator::Xor:
2155 case BinaryOperator::Or:
2156 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2157 break;
2158 case BinaryOperator::LAnd:
2159 case BinaryOperator::LOr:
2160 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2161 break;
2162 case BinaryOperator::MulAssign:
2163 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002164 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002165 if (!CompTy.isNull())
2166 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2167 break;
2168 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002169 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002170 if (!CompTy.isNull())
2171 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2172 break;
2173 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002174 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002175 if (!CompTy.isNull())
2176 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2177 break;
2178 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002179 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002180 if (!CompTy.isNull())
2181 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2182 break;
2183 case BinaryOperator::ShlAssign:
2184 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002185 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002186 if (!CompTy.isNull())
2187 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2188 break;
2189 case BinaryOperator::AndAssign:
2190 case BinaryOperator::XorAssign:
2191 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002192 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002193 if (!CompTy.isNull())
2194 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2195 break;
2196 case BinaryOperator::Comma:
2197 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2198 break;
2199 }
2200 if (ResultTy.isNull())
2201 return true;
2202 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00002203 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002204 else
Chris Lattnerf420df12007-08-28 18:36:55 +00002205 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002206}
2207
2208// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002209Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002210 ExprTy *input) {
2211 Expr *Input = (Expr*)input;
2212 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2213 QualType resultType;
2214 switch (Opc) {
2215 default:
2216 assert(0 && "Unimplemented unary expr!");
2217 case UnaryOperator::PreInc:
2218 case UnaryOperator::PreDec:
2219 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2220 break;
2221 case UnaryOperator::AddrOf:
2222 resultType = CheckAddressOfOperand(Input, OpLoc);
2223 break;
2224 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002225 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002226 resultType = CheckIndirectionOperand(Input, OpLoc);
2227 break;
2228 case UnaryOperator::Plus:
2229 case UnaryOperator::Minus:
2230 UsualUnaryConversions(Input);
2231 resultType = Input->getType();
2232 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2233 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2234 resultType.getAsString());
2235 break;
2236 case UnaryOperator::Not: // bitwise complement
2237 UsualUnaryConversions(Input);
2238 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00002239 // C99 6.5.3.3p1. We allow complex as a GCC extension.
2240 if (!resultType->isIntegerType()) {
2241 if (resultType->isComplexType())
2242 // C99 does not support '~' for complex conjugation.
2243 Diag(OpLoc, diag::ext_integer_complement_complex,
2244 resultType.getAsString());
2245 else
2246 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2247 resultType.getAsString());
2248 }
Chris Lattner4b009652007-07-25 00:24:17 +00002249 break;
2250 case UnaryOperator::LNot: // logical negation
2251 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2252 DefaultFunctionArrayConversion(Input);
2253 resultType = Input->getType();
2254 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2255 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2256 resultType.getAsString());
2257 // LNot always has type int. C99 6.5.3.3p5.
2258 resultType = Context.IntTy;
2259 break;
2260 case UnaryOperator::SizeOf:
2261 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
2262 break;
2263 case UnaryOperator::AlignOf:
2264 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
2265 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002266 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002267 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002268 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002269 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002270 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002271 resultType = Input->getType();
2272 break;
2273 }
2274 if (resultType.isNull())
2275 return true;
2276 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2277}
2278
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002279/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2280Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002281 SourceLocation LabLoc,
2282 IdentifierInfo *LabelII) {
2283 // Look up the record for this label identifier.
2284 LabelStmt *&LabelDecl = LabelMap[LabelII];
2285
2286 // If we haven't seen this label yet, create a forward reference.
2287 if (LabelDecl == 0)
2288 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2289
2290 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002291 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2292 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002293}
2294
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002295Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002296 SourceLocation RPLoc) { // "({..})"
2297 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2298 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2299 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2300
2301 // FIXME: there are a variety of strange constraints to enforce here, for
2302 // example, it is not possible to goto into a stmt expression apparently.
2303 // More semantic analysis is needed.
2304
2305 // FIXME: the last statement in the compount stmt has its value used. We
2306 // should not warn about it being unused.
2307
2308 // If there are sub stmts in the compound stmt, take the type of the last one
2309 // as the type of the stmtexpr.
2310 QualType Ty = Context.VoidTy;
2311
2312 if (!Compound->body_empty())
2313 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
2314 Ty = LastExpr->getType();
2315
2316 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2317}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002318
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002319Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002320 SourceLocation TypeLoc,
2321 TypeTy *argty,
2322 OffsetOfComponent *CompPtr,
2323 unsigned NumComponents,
2324 SourceLocation RPLoc) {
2325 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2326 assert(!ArgTy.isNull() && "Missing type argument!");
2327
2328 // We must have at least one component that refers to the type, and the first
2329 // one is known to be a field designator. Verify that the ArgTy represents
2330 // a struct/union/class.
2331 if (!ArgTy->isRecordType())
2332 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2333
2334 // Otherwise, create a compound literal expression as the base, and
2335 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002336 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002337
Chris Lattnerb37522e2007-08-31 21:49:13 +00002338 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2339 // GCC extension, diagnose them.
2340 if (NumComponents != 1)
2341 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2342 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2343
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002344 for (unsigned i = 0; i != NumComponents; ++i) {
2345 const OffsetOfComponent &OC = CompPtr[i];
2346 if (OC.isBrackets) {
2347 // Offset of an array sub-field. TODO: Should we allow vector elements?
2348 const ArrayType *AT = Res->getType()->getAsArrayType();
2349 if (!AT) {
2350 delete Res;
2351 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2352 Res->getType().getAsString());
2353 }
2354
Chris Lattner2af6a802007-08-30 17:59:59 +00002355 // FIXME: C++: Verify that operator[] isn't overloaded.
2356
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002357 // C99 6.5.2.1p1
2358 Expr *Idx = static_cast<Expr*>(OC.U.E);
2359 if (!Idx->getType()->isIntegerType())
2360 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2361 Idx->getSourceRange());
2362
2363 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2364 continue;
2365 }
2366
2367 const RecordType *RC = Res->getType()->getAsRecordType();
2368 if (!RC) {
2369 delete Res;
2370 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2371 Res->getType().getAsString());
2372 }
2373
2374 // Get the decl corresponding to this.
2375 RecordDecl *RD = RC->getDecl();
2376 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2377 if (!MemberDecl)
2378 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2379 OC.U.IdentInfo->getName(),
2380 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002381
2382 // FIXME: C++: Verify that MemberDecl isn't a static field.
2383 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002384 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2385 // matter here.
2386 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002387 }
2388
2389 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2390 BuiltinLoc);
2391}
2392
2393
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002394Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002395 TypeTy *arg1, TypeTy *arg2,
2396 SourceLocation RPLoc) {
2397 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2398 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2399
2400 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2401
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002402 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002403}
2404
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002405Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002406 ExprTy *expr1, ExprTy *expr2,
2407 SourceLocation RPLoc) {
2408 Expr *CondExpr = static_cast<Expr*>(cond);
2409 Expr *LHSExpr = static_cast<Expr*>(expr1);
2410 Expr *RHSExpr = static_cast<Expr*>(expr2);
2411
2412 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2413
2414 // The conditional expression is required to be a constant expression.
2415 llvm::APSInt condEval(32);
2416 SourceLocation ExpLoc;
2417 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2418 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2419 CondExpr->getSourceRange());
2420
2421 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2422 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2423 RHSExpr->getType();
2424 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2425}
2426
Nate Begemanbd881ef2008-01-30 20:50:20 +00002427/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002428/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002429/// The number of arguments has already been validated to match the number of
2430/// arguments in FnType.
2431static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002432 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00002433 for (unsigned i = 0; i != NumParams; ++i) {
2434 QualType ExprTy = Args[i]->getType().getCanonicalType();
2435 QualType ParmTy = FnType->getArgType(i).getCanonicalType();
2436
2437 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002438 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00002439 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002440 return true;
2441}
2442
2443Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2444 SourceLocation *CommaLocs,
2445 SourceLocation BuiltinLoc,
2446 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002447 // __builtin_overload requires at least 2 arguments
2448 if (NumArgs < 2)
2449 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2450 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002451
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002452 // The first argument is required to be a constant expression. It tells us
2453 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002454 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002455 Expr *NParamsExpr = Args[0];
2456 llvm::APSInt constEval(32);
2457 SourceLocation ExpLoc;
2458 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2459 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2460 NParamsExpr->getSourceRange());
2461
2462 // Verify that the number of parameters is > 0
2463 unsigned NumParams = constEval.getZExtValue();
2464 if (NumParams == 0)
2465 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2466 NParamsExpr->getSourceRange());
2467 // Verify that we have at least 1 + NumParams arguments to the builtin.
2468 if ((NumParams + 1) > NumArgs)
2469 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2470 SourceRange(BuiltinLoc, RParenLoc));
2471
2472 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002473 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002474 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002475 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2476 // UsualUnaryConversions will convert the function DeclRefExpr into a
2477 // pointer to function.
2478 Expr *Fn = UsualUnaryConversions(Args[i]);
2479 FunctionTypeProto *FnType = 0;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002480 if (const PointerType *PT = Fn->getType()->getAsPointerType()) {
2481 QualType PointeeType = PT->getPointeeType().getCanonicalType();
2482 FnType = dyn_cast<FunctionTypeProto>(PointeeType);
2483 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002484
2485 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2486 // parameters, and the number of parameters must match the value passed to
2487 // the builtin.
2488 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002489 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2490 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002491
2492 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002493 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002494 // If they match, return a new OverloadExpr.
Nate Begemanc6078c92008-01-31 05:38:29 +00002495 if (ExprsMatchFnType(Args+1, FnType)) {
2496 if (OE)
2497 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2498 OE->getFn()->getSourceRange());
2499 // Remember our match, and continue processing the remaining arguments
2500 // to catch any errors.
2501 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2502 BuiltinLoc, RParenLoc);
2503 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002504 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002505 // Return the newly created OverloadExpr node, if we succeded in matching
2506 // exactly one of the candidate functions.
2507 if (OE)
2508 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002509
2510 // If we didn't find a matching function Expr in the __builtin_overload list
2511 // the return an error.
2512 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002513 for (unsigned i = 0; i != NumParams; ++i) {
2514 if (i != 0) typeNames += ", ";
2515 typeNames += Args[i+1]->getType().getAsString();
2516 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002517
2518 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2519 SourceRange(BuiltinLoc, RParenLoc));
2520}
2521
Anders Carlsson36760332007-10-15 20:28:48 +00002522Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2523 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002524 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002525 Expr *E = static_cast<Expr*>(expr);
2526 QualType T = QualType::getFromOpaquePtr(type);
2527
2528 InitBuiltinVaListType();
2529
Chris Lattner005ed752008-01-04 18:04:52 +00002530 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2531 != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002532 return Diag(E->getLocStart(),
2533 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2534 E->getType().getAsString(),
2535 E->getSourceRange());
2536
2537 // FIXME: Warn if a non-POD type is passed in.
2538
2539 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2540}
2541
Chris Lattner005ed752008-01-04 18:04:52 +00002542bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2543 SourceLocation Loc,
2544 QualType DstType, QualType SrcType,
2545 Expr *SrcExpr, const char *Flavor) {
2546 // Decode the result (notice that AST's are still created for extensions).
2547 bool isInvalid = false;
2548 unsigned DiagKind;
2549 switch (ConvTy) {
2550 default: assert(0 && "Unknown conversion type");
2551 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002552 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002553 DiagKind = diag::ext_typecheck_convert_pointer_int;
2554 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002555 case IntToPointer:
2556 DiagKind = diag::ext_typecheck_convert_int_pointer;
2557 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002558 case IncompatiblePointer:
2559 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2560 break;
2561 case FunctionVoidPointer:
2562 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2563 break;
2564 case CompatiblePointerDiscardsQualifiers:
2565 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2566 break;
2567 case Incompatible:
2568 DiagKind = diag::err_typecheck_convert_incompatible;
2569 isInvalid = true;
2570 break;
2571 }
2572
2573 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2574 SrcExpr->getSourceRange());
2575 return isInvalid;
2576}