blob: 9cb8b98f7043f65a38ab512c3cfaeaa3cac666dd [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();
Chris Lattnered94f762008-07-21 04:44:44 +000094 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +000095 // FIXME: This should use a new expr for a direct reference, don't turn
96 // this into Self->ivar, just return a BareIVarExpr or something.
97 IdentifierInfo &II = Context.Idents.get("self");
98 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
99 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
100 static_cast<Expr*>(SelfExpr.Val), true, true);
101 }
102 }
Steve Naroffe90d4cc2008-06-05 18:14:25 +0000103 if (SD == 0 && !strcmp(II.getName(), "super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000104 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000105 getCurMethodDecl()->getClassInterface()));
Steve Naroff6f786252008-06-02 23:03:37 +0000106 return new ObjCSuperRefExpr(T, Loc);
107 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000108 }
109
Chris Lattner4b009652007-07-25 00:24:17 +0000110 if (D == 0) {
111 // Otherwise, this could be an implicitly declared function reference (legal
112 // in C90, extension in C99).
113 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000114 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000115 D = ImplicitlyDefineFunction(Loc, II, S);
116 else {
117 // If this name wasn't predeclared and if this is not a function call,
118 // diagnose the problem.
119 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
120 }
121 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000122
Steve Naroff91b03f72007-08-28 03:03:08 +0000123 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneree4c3bf2008-02-29 16:48:43 +0000124 // check if referencing an identifier with __attribute__((deprecated)).
125 if (VD->getAttr<DeprecatedAttr>())
126 Diag(Loc, diag::warn_deprecated, VD->getName());
127
Steve Naroffcae537d2007-08-28 18:45:29 +0000128 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000129 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000130 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000131 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000132 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000133
134 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
135 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
136 if (MD->isStatic())
137 // "invalid use of member 'x' in static member function"
138 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
139 FD->getName());
140 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
141 // "invalid use of nonstatic data member 'x'"
142 return Diag(Loc, diag::err_invalid_non_static_member_use,
143 FD->getName());
144
145 if (FD->isInvalidDecl())
146 return true;
147
148 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
149 ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
150 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
151 true, FD, Loc, FD->getType());
152 }
153
154 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
155 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000156
Chris Lattner4b009652007-07-25 00:24:17 +0000157 if (isa<TypedefDecl>(D))
158 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000159 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000160 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000161 if (isa<NamespaceDecl>(D))
162 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000163
164 assert(0 && "Invalid decl");
165 abort();
166}
167
Steve Naroff87d58b42007-09-16 03:34:24 +0000168Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000169 tok::TokenKind Kind) {
170 PreDefinedExpr::IdentType IT;
171
172 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000173 default: assert(0 && "Unknown simple primary expr!");
174 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
175 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
176 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000177 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000178
179 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000180 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000181 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000182
Chris Lattner7e637512008-01-12 08:14:25 +0000183 // Pre-defined identifiers are of type char[x], where x is the length of the
184 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000185 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000186 if (getCurFunctionDecl())
187 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000188 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000189 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000190
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000191 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000192 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000193 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner7e637512008-01-12 08:14:25 +0000194 return new PreDefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000195}
196
Steve Naroff87d58b42007-09-16 03:34:24 +0000197Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000198 llvm::SmallString<16> CharBuffer;
199 CharBuffer.resize(Tok.getLength());
200 const char *ThisTokBegin = &CharBuffer[0];
201 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
202
203 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
204 Tok.getLocation(), PP);
205 if (Literal.hadError())
206 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000207
208 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
209
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000210 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
211 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000212}
213
Steve Naroff87d58b42007-09-16 03:34:24 +0000214Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000215 // fast path for a single digit (which is quite common). A single digit
216 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
217 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000218 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000219
Chris Lattner8cd0e932008-03-05 18:54:05 +0000220 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000221 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000222 Context.IntTy,
223 Tok.getLocation()));
224 }
225 llvm::SmallString<512> IntegerBuffer;
226 IntegerBuffer.resize(Tok.getLength());
227 const char *ThisTokBegin = &IntegerBuffer[0];
228
229 // Get the spelling of the token, which eliminates trigraphs, etc.
230 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
231 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
232 Tok.getLocation(), PP);
233 if (Literal.hadError)
234 return ExprResult(true);
235
Chris Lattner1de66eb2007-08-26 03:42:43 +0000236 Expr *Res;
237
238 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000239 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000240 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000241 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000242 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000243 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000244 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000245 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000246
247 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
248
Ted Kremenekddedbe22007-11-29 00:56:49 +0000249 // isExact will be set by GetFloatValue().
250 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000251 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000252 Ty, Tok.getLocation());
253
Chris Lattner1de66eb2007-08-26 03:42:43 +0000254 } else if (!Literal.isIntegerLiteral()) {
255 return ExprResult(true);
256 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000257 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000258
Neil Booth7421e9c2007-08-29 22:00:19 +0000259 // long long is a C99 feature.
260 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000261 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000262 Diag(Tok.getLocation(), diag::ext_longlong);
263
Chris Lattner4b009652007-07-25 00:24:17 +0000264 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000265 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000266
267 if (Literal.GetIntegerValue(ResultVal)) {
268 // If this value didn't fit into uintmax_t, warn and force to ull.
269 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000270 Ty = Context.UnsignedLongLongTy;
271 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000272 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000273 } else {
274 // If this value fits into a ULL, try to figure out what else it fits into
275 // according to the rules of C99 6.4.4.1p5.
276
277 // Octal, Hexadecimal, and integers with a U suffix are allowed to
278 // be an unsigned int.
279 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
280
281 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000282 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000283 if (!Literal.isLong && !Literal.isLongLong) {
284 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000285 unsigned IntSize = Context.Target.getIntWidth();
286
Chris Lattner4b009652007-07-25 00:24:17 +0000287 // Does it fit in a unsigned int?
288 if (ResultVal.isIntN(IntSize)) {
289 // Does it fit in a signed int?
290 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000291 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000292 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000293 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000294 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000295 }
Chris Lattner4b009652007-07-25 00:24:17 +0000296 }
297
298 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000299 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000300 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000301
302 // Does it fit in a unsigned long?
303 if (ResultVal.isIntN(LongSize)) {
304 // Does it fit in a signed long?
305 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000306 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000307 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000308 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000309 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000310 }
Chris Lattner4b009652007-07-25 00:24:17 +0000311 }
312
313 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000314 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000315 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000316
317 // Does it fit in a unsigned long long?
318 if (ResultVal.isIntN(LongLongSize)) {
319 // Does it fit in a signed long long?
320 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000321 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000322 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000323 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000324 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000325 }
326 }
327
328 // If we still couldn't decide a type, we probably have something that
329 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000330 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000331 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000332 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000333 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000334 }
Chris Lattnere4068872008-05-09 05:59:00 +0000335
336 if (ResultVal.getBitWidth() != Width)
337 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000338 }
339
Chris Lattner48d7f382008-04-02 04:24:33 +0000340 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000341 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000342
343 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
344 if (Literal.isImaginary)
345 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
346
347 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000348}
349
Steve Naroff87d58b42007-09-16 03:34:24 +0000350Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000351 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000352 Expr *E = (Expr *)Val;
353 assert((E != 0) && "ActOnParenExpr() missing expr");
354 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000355}
356
357/// The UsualUnaryConversions() function is *not* called by this routine.
358/// See C99 6.3.2.1p[2-4] for more details.
359QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
360 SourceLocation OpLoc, bool isSizeof) {
361 // C99 6.5.3.4p1:
362 if (isa<FunctionType>(exprType) && isSizeof)
363 // alignof(function) is allowed.
364 Diag(OpLoc, diag::ext_sizeof_function_type);
365 else if (exprType->isVoidType())
366 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
367 else if (exprType->isIncompleteType()) {
368 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
369 diag::err_alignof_incomplete_type,
370 exprType.getAsString());
371 return QualType(); // error
372 }
373 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
374 return Context.getSizeType();
375}
376
377Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000378ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000379 SourceLocation LPLoc, TypeTy *Ty,
380 SourceLocation RPLoc) {
381 // If error parsing type, ignore.
382 if (Ty == 0) return true;
383
384 // Verify that this is a valid expression.
385 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
386
387 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
388
389 if (resultType.isNull())
390 return true;
391 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
392}
393
Chris Lattner5110ad52007-08-24 21:41:10 +0000394QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000395 DefaultFunctionArrayConversion(V);
396
Chris Lattnera16e42d2007-08-26 05:39:26 +0000397 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000398 if (const ComplexType *CT = V->getType()->getAsComplexType())
399 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000400
401 // Otherwise they pass through real integer and floating point types here.
402 if (V->getType()->isArithmeticType())
403 return V->getType();
404
405 // Reject anything else.
406 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
407 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000408}
409
410
Chris Lattner4b009652007-07-25 00:24:17 +0000411
Steve Naroff87d58b42007-09-16 03:34:24 +0000412Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000413 tok::TokenKind Kind,
414 ExprTy *Input) {
415 UnaryOperator::Opcode Opc;
416 switch (Kind) {
417 default: assert(0 && "Unknown unary op!");
418 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
419 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
420 }
421 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
422 if (result.isNull())
423 return true;
424 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
425}
426
427Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000428ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000429 ExprTy *Idx, SourceLocation RLoc) {
430 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
431
432 // Perform default conversions.
433 DefaultFunctionArrayConversion(LHSExp);
434 DefaultFunctionArrayConversion(RHSExp);
435
436 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
437
438 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000439 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000440 // in the subscript position. As a result, we need to derive the array base
441 // and index from the expression types.
442 Expr *BaseExpr, *IndexExpr;
443 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000444 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000445 BaseExpr = LHSExp;
446 IndexExpr = RHSExp;
447 // FIXME: need to deal with const...
448 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000449 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000450 // Handle the uncommon case of "123[Ptr]".
451 BaseExpr = RHSExp;
452 IndexExpr = LHSExp;
453 // FIXME: need to deal with const...
454 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000455 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
456 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000457 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000458
459 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000460 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
461 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000462 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000463 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000464 // FIXME: need to deal with const...
465 ResultType = VTy->getElementType();
466 } else {
467 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
468 RHSExp->getSourceRange());
469 }
470 // C99 6.5.2.1p1
471 if (!IndexExpr->getType()->isIntegerType())
472 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
473 IndexExpr->getSourceRange());
474
475 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
476 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000477 // void (*)(int)) and pointers to incomplete types. Functions are not
478 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000479 if (!ResultType->isObjectType())
480 return Diag(BaseExpr->getLocStart(),
481 diag::err_typecheck_subscript_not_object,
482 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
483
484 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
485}
486
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000487QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000488CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000489 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000490 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000491
492 // This flag determines whether or not the component is to be treated as a
493 // special name, or a regular GLSL-style component access.
494 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000495
496 // The vector accessor can't exceed the number of elements.
497 const char *compStr = CompName.getName();
498 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000499 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000500 baseType.getAsString(), SourceRange(CompLoc));
501 return QualType();
502 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000503
504 // Check that we've found one of the special components, or that the component
505 // names must come from the same set.
506 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
507 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
508 SpecialComponent = true;
509 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000510 do
511 compStr++;
512 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
513 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
514 do
515 compStr++;
516 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
517 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
518 do
519 compStr++;
520 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
521 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000522
Nate Begemanc8e51f82008-05-09 06:41:27 +0000523 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000524 // We didn't get to the end of the string. This means the component names
525 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000526 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000527 std::string(compStr,compStr+1), SourceRange(CompLoc));
528 return QualType();
529 }
530 // Each component accessor can't exceed the vector type.
531 compStr = CompName.getName();
532 while (*compStr) {
533 if (vecType->isAccessorWithinNumElements(*compStr))
534 compStr++;
535 else
536 break;
537 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000538 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000539 // We didn't get to the end of the string. This means a component accessor
540 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000541 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000542 baseType.getAsString(), SourceRange(CompLoc));
543 return QualType();
544 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000545
546 // If we have a special component name, verify that the current vector length
547 // is an even number, since all special component names return exactly half
548 // the elements.
549 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
550 return QualType();
551 }
552
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000553 // The component accessor looks fine - now we need to compute the actual type.
554 // The vector type is implied by the component accessor. For example,
555 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000556 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
557 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
558 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000559 if (CompSize == 1)
560 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000561
Nate Begemanaf6ed502008-04-18 23:10:10 +0000562 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000563 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000564 // diagostics look bad. We want extended vector types to appear built-in.
565 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
566 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
567 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000568 }
569 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000570}
571
Chris Lattner4b009652007-07-25 00:24:17 +0000572Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000573ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000574 tok::TokenKind OpKind, SourceLocation MemberLoc,
575 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000576 Expr *BaseExpr = static_cast<Expr *>(Base);
577 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000578
579 // Perform default conversions.
580 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000581
Steve Naroff2cb66382007-07-26 03:11:44 +0000582 QualType BaseType = BaseExpr->getType();
583 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000584
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000585 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
586 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000587 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000588 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000589 BaseType = PT->getPointeeType();
590 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000591 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
592 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000593 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000594
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000595 // Handle field access to simple records. This also handles access to fields
596 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000597 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000598 RecordDecl *RDecl = RTy->getDecl();
599 if (RTy->isIncompleteType())
600 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
601 BaseExpr->getSourceRange());
602 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000603 FieldDecl *MemberDecl = RDecl->getMember(&Member);
604 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000605 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
606 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000607
608 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000609 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000610 QualType MemberType = MemberDecl->getType();
611 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000612 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000613 MemberType = MemberType.getQualifiedType(combinedQualifiers);
614
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000615 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000616 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000617 }
618
Chris Lattnere9d71612008-07-21 04:59:05 +0000619 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
620 // (*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 Lattner7d5a8762008-07-21 05:35:34 +0000625 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000626 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000627 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000628 }
629
Chris Lattnere9d71612008-07-21 04:59:05 +0000630 // Handle Objective-C property access, which is "Obj.property" where Obj is a
631 // pointer to a (potentially qualified) interface type.
632 const PointerType *PTy;
633 const ObjCInterfaceType *IFTy;
634 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
635 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
636 ObjCInterfaceDecl *IFace = IFTy->getDecl();
637
638 // Before we look for explicit property declarations, we check for
639 // nullary methods (which allow '.' notation).
640 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
641
642 if (ObjCMethodDecl *MD = IFace->lookupInstanceMethod(Sel))
643 return new ObjCPropertyRefExpr(MD, MD->getResultType(),
644 MemberLoc, BaseExpr);
645
646 // FIXME: Need to deal with setter methods that take 1 argument. E.g.:
647 // @interface NSBundle : NSObject {}
648 // - (NSString *)bundlePath;
649 // - (void)setBundlePath:(NSString *)x;
650 // @end
651 // void someMethod() { frameworkBundle.bundlePath = 0; }
652 //
653 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
654 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
655
656 // Lastly, check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000657 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
658 E = IFTy->qual_end(); I != E; ++I)
659 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
660 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000661 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000662
663 // Handle 'field access' to vectors, such as 'V.xx'.
664 if (BaseType->isExtVectorType() && OpKind == tok::period) {
665 // Component access limited to variables (reject vec4.rg.g).
666 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
667 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +0000668 return Diag(MemberLoc, diag::err_ext_vector_component_access,
669 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000670 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
671 if (ret.isNull())
672 return true;
673 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
674 }
675
Chris Lattner7d5a8762008-07-21 05:35:34 +0000676 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
677 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000678}
679
Steve Naroff87d58b42007-09-16 03:34:24 +0000680/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000681/// This provides the location of the left/right parens and a list of comma
682/// locations.
683Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000684ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000685 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000686 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
687 Expr *Fn = static_cast<Expr *>(fn);
688 Expr **Args = reinterpret_cast<Expr**>(args);
689 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +0000690 FunctionDecl *FDecl = NULL;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000691
692 // Promote the function operand.
693 UsualUnaryConversions(Fn);
694
695 // If we're directly calling a function, get the declaration for
696 // that function.
697 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
698 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
699 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
700
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000701 // Make the call expr early, before semantic checks. This guarantees cleanup
702 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +0000703 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000704 Context.BoolTy, RParenLoc));
705
Chris Lattner4b009652007-07-25 00:24:17 +0000706 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
707 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000708 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000709 if (PT == 0)
710 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
711 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000712 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
713 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000714 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
715 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000716
717 // We know the result type of the call, set it.
718 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000719
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000720 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000721 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
722 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000723 unsigned NumArgsInProto = Proto->getNumArgs();
724 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000725
Chris Lattner3e254fb2008-04-08 04:40:51 +0000726 // If too few arguments are available (and we don't have default
727 // arguments for the remaining parameters), don't make the call.
728 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +0000729 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000730 // Use default arguments for missing arguments
731 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +0000732 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000733 } else
734 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
735 Fn->getSourceRange());
736 }
737
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000738 // If too many are passed and not variadic, error on the extras and drop
739 // them.
740 if (NumArgs > NumArgsInProto) {
741 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000742 Diag(Args[NumArgsInProto]->getLocStart(),
743 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
744 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000745 Args[NumArgs-1]->getLocEnd()));
746 // This deletes the extra arguments.
747 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000748 }
749 NumArgsToCheck = NumArgsInProto;
750 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000751
Chris Lattner4b009652007-07-25 00:24:17 +0000752 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000753 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +0000754 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000755
756 Expr *Arg;
757 if (i < NumArgs)
758 Arg = Args[i];
759 else
760 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +0000761 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000762
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000763 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +0000764 AssignConvertType ConvTy =
765 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000766 TheCall->setArg(i, Arg);
767
Chris Lattner005ed752008-01-04 18:04:52 +0000768 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
769 ArgType, Arg, "passing"))
770 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000771 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000772
773 // If this is a variadic call, handle args passed through "...".
774 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +0000775 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000776 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
777 Expr *Arg = Args[i];
778 DefaultArgumentPromotion(Arg);
779 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000780 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000781 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000782 } else {
783 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
784
Steve Naroffdb65e052007-08-28 23:30:39 +0000785 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000786 for (unsigned i = 0; i != NumArgs; i++) {
787 Expr *Arg = Args[i];
788 DefaultArgumentPromotion(Arg);
789 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000790 }
Chris Lattner4b009652007-07-25 00:24:17 +0000791 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000792
Chris Lattner2e64c072007-08-10 20:18:51 +0000793 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +0000794 if (FDecl)
795 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +0000796
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000797 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000798}
799
800Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000801ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000802 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000803 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000804 QualType literalType = QualType::getFromOpaquePtr(Ty);
805 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000806 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000807 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000808
Eli Friedman8c2173d2008-05-20 05:22:08 +0000809 if (literalType->isArrayType()) {
810 if (literalType->getAsVariableArrayType())
811 return Diag(LParenLoc,
812 diag::err_variable_object_no_init,
813 SourceRange(LParenLoc,
814 literalExpr->getSourceRange().getEnd()));
815 } else if (literalType->isIncompleteType()) {
816 return Diag(LParenLoc,
817 diag::err_typecheck_decl_incomplete_type,
818 literalType.getAsString(),
819 SourceRange(LParenLoc,
820 literalExpr->getSourceRange().getEnd()));
821 }
822
Steve Narofff0b23542008-01-10 22:15:12 +0000823 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +0000824 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +0000825
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000826 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +0000827 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +0000828 if (CheckForConstantInitializer(literalExpr, literalType))
829 return true;
830 }
Steve Naroffbe37fc02008-01-14 18:19:28 +0000831 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000832}
833
834Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000835ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000836 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000837 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000838
Steve Naroff0acc9c92007-09-15 18:49:24 +0000839 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000840 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000841
Chris Lattner48d7f382008-04-02 04:24:33 +0000842 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
843 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
844 return E;
Chris Lattner4b009652007-07-25 00:24:17 +0000845}
846
Chris Lattnerd1f26b32007-12-20 00:44:32 +0000847bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000848 assert(VectorTy->isVectorType() && "Not a vector type!");
849
850 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000851 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000852 return Diag(R.getBegin(),
853 Ty->isVectorType() ?
854 diag::err_invalid_conversion_between_vectors :
855 diag::err_invalid_conversion_between_vector_and_integer,
856 VectorTy.getAsString().c_str(),
857 Ty.getAsString().c_str(), R);
858 } else
859 return Diag(R.getBegin(),
860 diag::err_invalid_conversion_between_vector_and_scalar,
861 VectorTy.getAsString().c_str(),
862 Ty.getAsString().c_str(), R);
863
864 return false;
865}
866
Chris Lattner4b009652007-07-25 00:24:17 +0000867Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000868ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000869 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000870 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000871
872 Expr *castExpr = static_cast<Expr*>(Op);
873 QualType castType = QualType::getFromOpaquePtr(Ty);
874
Steve Naroff68adb482007-08-31 00:32:44 +0000875 UsualUnaryConversions(castExpr);
876
Chris Lattner4b009652007-07-25 00:24:17 +0000877 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
878 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000879 if (!castType->isVoidType()) { // Cast to void allows any expr type.
Steve Naroff5ad85292008-06-03 12:56:35 +0000880 if (!castType->isScalarType() && !castType->isVectorType()) {
881 // GCC struct/union extension.
882 if (castType == castExpr->getType() &&
Steve Naroff7f1c5b52008-06-03 13:21:30 +0000883 castType->isStructureType() || castType->isUnionType()) {
884 Diag(LParenLoc, diag::ext_typecheck_cast_nonscalar,
885 SourceRange(LParenLoc, RParenLoc));
886 return new CastExpr(castType, castExpr, LParenLoc);
887 } else
Steve Naroff5ad85292008-06-03 12:56:35 +0000888 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
889 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
890 }
Steve Narofff459ee52008-01-24 22:55:05 +0000891 if (!castExpr->getType()->isScalarType() &&
892 !castExpr->getType()->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000893 return Diag(castExpr->getLocStart(),
894 diag::err_typecheck_expect_scalar_operand,
895 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000896
897 if (castExpr->getType()->isVectorType()) {
898 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
899 castExpr->getType(), castType))
900 return true;
901 } else if (castType->isVectorType()) {
902 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
903 castType, castExpr->getType()))
904 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000905 }
Chris Lattner4b009652007-07-25 00:24:17 +0000906 }
907 return new CastExpr(castType, castExpr, LParenLoc);
908}
909
Chris Lattner98a425c2007-11-26 01:40:58 +0000910/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
911/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000912inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
913 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
914 UsualUnaryConversions(cond);
915 UsualUnaryConversions(lex);
916 UsualUnaryConversions(rex);
917 QualType condT = cond->getType();
918 QualType lexT = lex->getType();
919 QualType rexT = rex->getType();
920
921 // first, check the condition.
922 if (!condT->isScalarType()) { // C99 6.5.15p2
923 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
924 condT.getAsString());
925 return QualType();
926 }
Chris Lattner992ae932008-01-06 22:42:25 +0000927
928 // Now check the two expressions.
929
930 // If both operands have arithmetic type, do the usual arithmetic conversions
931 // to find a common type: C99 6.5.15p3,5.
932 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000933 UsualArithmeticConversions(lex, rex);
934 return lex->getType();
935 }
Chris Lattner992ae932008-01-06 22:42:25 +0000936
937 // If both operands are the same structure or union type, the result is that
938 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000939 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +0000940 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +0000941 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +0000942 // "If both the operands have structure or union type, the result has
943 // that type." This implies that CV qualifiers are dropped.
944 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000945 }
Chris Lattner992ae932008-01-06 22:42:25 +0000946
947 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +0000948 // The following || allows only one side to be void (a GCC-ism).
949 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +0000950 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +0000951 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
952 rex->getSourceRange());
953 if (!rexT->isVoidType())
954 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +0000955 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +0000956 ImpCastExprToType(lex, Context.VoidTy);
957 ImpCastExprToType(rex, Context.VoidTy);
958 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +0000959 }
Steve Naroff12ebf272008-01-08 01:11:38 +0000960 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
961 // the type of the other operand."
962 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000963 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000964 return lexT;
965 }
966 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000967 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000968 return rexT;
969 }
Chris Lattner0ac51632008-01-06 22:50:31 +0000970 // Handle the case where both operands are pointers before we handle null
971 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +0000972 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
973 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
974 // get the "pointed to" types
975 QualType lhptee = LHSPT->getPointeeType();
976 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000977
Chris Lattner71225142007-07-31 21:27:01 +0000978 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
979 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +0000980 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +0000981 // Figure out necessary qualifiers (C99 6.5.15p6)
982 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000983 QualType destType = Context.getPointerType(destPointee);
984 ImpCastExprToType(lex, destType); // add qualifiers if necessary
985 ImpCastExprToType(rex, destType); // promote to void*
986 return destType;
987 }
Chris Lattner9db553e2008-04-02 06:59:01 +0000988 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +0000989 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000990 QualType destType = Context.getPointerType(destPointee);
991 ImpCastExprToType(lex, destType); // add qualifiers if necessary
992 ImpCastExprToType(rex, destType); // promote to void*
993 return destType;
994 }
Chris Lattner4b009652007-07-25 00:24:17 +0000995
Steve Naroff85f0dc52007-10-15 20:41:53 +0000996 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
997 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +0000998 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +0000999 lexT.getAsString(), rexT.getAsString(),
1000 lex->getSourceRange(), rex->getSourceRange());
Eli Friedman33284862008-01-30 17:02:03 +00001001 // In this situation, we assume void* type. No especially good
1002 // reason, but this is what gcc does, and we do have to pick
1003 // to get a consistent AST.
1004 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
1005 ImpCastExprToType(lex, voidPtrTy);
1006 ImpCastExprToType(rex, voidPtrTy);
1007 return voidPtrTy;
Chris Lattner71225142007-07-31 21:27:01 +00001008 }
1009 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001010 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1011 // differently qualified versions of compatible types, the result type is
1012 // a pointer to an appropriately qualified version of the *composite*
1013 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001014 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001015 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001016 QualType compositeType = lexT;
1017 ImpCastExprToType(lex, compositeType);
1018 ImpCastExprToType(rex, compositeType);
1019 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001020 }
Chris Lattner4b009652007-07-25 00:24:17 +00001021 }
Steve Naroff605896f2008-05-31 22:33:45 +00001022 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1023 // evaluates to "struct objc_object *" (and is handled above when comparing
1024 // id with statically typed objects). FIXME: Do we need an ImpCastExprToType?
1025 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1026 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true))
1027 return Context.getObjCIdType();
1028 }
Chris Lattner992ae932008-01-06 22:42:25 +00001029 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001030 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1031 lexT.getAsString(), rexT.getAsString(),
1032 lex->getSourceRange(), rex->getSourceRange());
1033 return QualType();
1034}
1035
Steve Naroff87d58b42007-09-16 03:34:24 +00001036/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001037/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001038Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001039 SourceLocation ColonLoc,
1040 ExprTy *Cond, ExprTy *LHS,
1041 ExprTy *RHS) {
1042 Expr *CondExpr = (Expr *) Cond;
1043 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001044
1045 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1046 // was the condition.
1047 bool isLHSNull = LHSExpr == 0;
1048 if (isLHSNull)
1049 LHSExpr = CondExpr;
1050
Chris Lattner4b009652007-07-25 00:24:17 +00001051 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1052 RHSExpr, QuestionLoc);
1053 if (result.isNull())
1054 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001055 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1056 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001057}
1058
Steve Naroffdb65e052007-08-28 23:30:39 +00001059/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Steve Naroffbbaed752008-01-29 02:42:22 +00001060/// do not have a prototype. Arguments that have type float are promoted to
1061/// double. All other argument types are converted by UsualUnaryConversions().
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001062void Sema::DefaultArgumentPromotion(Expr *&Expr) {
1063 QualType Ty = Expr->getType();
1064 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffdb65e052007-08-28 23:30:39 +00001065
Chris Lattner11216032008-06-27 22:48:56 +00001066 // If this is a 'float' (CVR qualified or typedef) promote to double.
1067 if (const BuiltinType *BT = Ty->getAsBuiltinType())
1068 if (BT->getKind() == BuiltinType::Float)
1069 return ImpCastExprToType(Expr, Context.DoubleTy);
1070
1071 UsualUnaryConversions(Expr);
Steve Naroffdb65e052007-08-28 23:30:39 +00001072}
1073
Chris Lattner4b009652007-07-25 00:24:17 +00001074/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Chris Lattner48d7f382008-04-02 04:24:33 +00001075void Sema::DefaultFunctionArrayConversion(Expr *&E) {
1076 QualType Ty = E->getType();
1077 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001078
Chris Lattner48d7f382008-04-02 04:24:33 +00001079 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
Chris Lattnera05f7d22008-04-02 17:45:06 +00001080 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
Chris Lattner48d7f382008-04-02 04:24:33 +00001081 Ty = E->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001082 }
Chris Lattner48d7f382008-04-02 04:24:33 +00001083 if (Ty->isFunctionType())
1084 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner19eb97e2008-04-02 05:18:44 +00001085 else if (Ty->isArrayType())
1086 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
Chris Lattner4b009652007-07-25 00:24:17 +00001087}
1088
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001089/// UsualUnaryConversions - Performs various conversions that are common to most
Chris Lattner4b009652007-07-25 00:24:17 +00001090/// operators (C99 6.3). The conversions of array and function types are
1091/// sometimes surpressed. For example, the array->pointer conversion doesn't
1092/// apply if the array is an argument to the sizeof or address (&) operators.
1093/// In these instances, this routine should *not* be called.
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001094Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
1095 QualType Ty = Expr->getType();
1096 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001097
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001098 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
Chris Lattnera05f7d22008-04-02 17:45:06 +00001099 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001100 Ty = Expr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001101 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001102 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
Chris Lattnere992d6c2008-01-16 19:17:22 +00001103 ImpCastExprToType(Expr, Context.IntTy);
Chris Lattner4b009652007-07-25 00:24:17 +00001104 else
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001105 DefaultFunctionArrayConversion(Expr);
1106
1107 return Expr;
Chris Lattner4b009652007-07-25 00:24:17 +00001108}
1109
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001110/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +00001111/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1112/// routine returns the first non-arithmetic type found. The client is
1113/// responsible for emitting appropriate error diagnostics.
Chris Lattner48d7f382008-04-02 04:24:33 +00001114/// FIXME: verify the conversion rules for "complex int" are consistent with
1115/// GCC.
Steve Naroff8f708362007-08-24 19:07:16 +00001116QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
1117 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +00001118 if (!isCompAssign) {
1119 UsualUnaryConversions(lhsExpr);
1120 UsualUnaryConversions(rhsExpr);
1121 }
Steve Naroff7438fdf2007-10-18 18:55:53 +00001122 // For conversion purposes, we ignore any qualifiers.
1123 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +00001124 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
1125 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001126
1127 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +00001128 if (lhs == rhs)
1129 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001130
1131 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1132 // The caller can deal with this (e.g. pointer + int).
1133 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001134 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001135
1136 // At this point, we have two different arithmetic types.
1137
1138 // Handle complex types first (C99 6.3.1.8p1).
1139 if (lhs->isComplexType() || rhs->isComplexType()) {
Steve Naroff43001212008-01-15 19:36:10 +00001140 // if we have an integer operand, the result is the complex type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001141 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001142 // convert the rhs to the lhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001143 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001144 return lhs;
Steve Naroff43001212008-01-15 19:36:10 +00001145 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001146 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001147 // convert the lhs to the rhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001148 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001149 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001150 }
Steve Naroff3cf497f2007-08-27 01:27:54 +00001151 // This handles complex/complex, complex/float, or float/complex.
1152 // When both operands are complex, the shorter operand is converted to the
1153 // type of the longer, and that is the type of the result. This corresponds
1154 // to what is done when combining two real floating-point operands.
1155 // The fun begins when size promotion occur across type domains.
1156 // From H&S 6.3.4: When one operand is complex and the other is a real
1157 // floating-point type, the less precise type is converted, within it's
1158 // real or complex domain, to the precision of the other type. For example,
1159 // when combining a "long double" with a "double _Complex", the
1160 // "double _Complex" is promoted to "long double _Complex".
Chris Lattnerd7135b42008-04-06 23:38:49 +00001161 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Naroff45fc9822007-08-27 15:30:22 +00001162
1163 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +00001164 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
1165 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001166 ImpCastExprToType(rhsExpr, rhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001167 } else if (result < 0) { // The right side is bigger, convert lhs.
1168 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
1169 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001170 ImpCastExprToType(lhsExpr, lhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001171 }
1172 // At this point, lhs and rhs have the same rank/size. Now, make sure the
1173 // domains match. This is a requirement for our implementation, C99
1174 // does not require this promotion.
1175 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1176 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001177 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001178 ImpCastExprToType(lhsExpr, rhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001179 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001180 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001181 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001182 ImpCastExprToType(rhsExpr, lhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001183 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001184 }
Chris Lattner4b009652007-07-25 00:24:17 +00001185 }
Steve Naroff3b6157f2007-08-27 21:43:43 +00001186 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +00001187 }
1188 // Now handle "real" floating types (i.e. float, double, long double).
1189 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1190 // if we have an integer operand, the result is the real floating type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001191 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001192 // convert rhs to the lhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001193 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001194 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001195 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001196 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001197 // convert lhs to the rhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001198 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001199 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001200 }
1201 // We have two real floating types, float/complex combos were handled above.
1202 // Convert the smaller operand to the bigger result.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001203 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Naroff45fc9822007-08-27 15:30:22 +00001204
1205 if (result > 0) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001206 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001207 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001208 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001209 if (result < 0) { // convert the lhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001210 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff45fc9822007-08-27 15:30:22 +00001211 return rhs;
1212 }
1213 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001214 }
Steve Naroff43001212008-01-15 19:36:10 +00001215 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
1216 // Handle GCC complex int extension.
Steve Naroff43001212008-01-15 19:36:10 +00001217 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
Eli Friedman50727042008-02-08 01:19:44 +00001218 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
Steve Naroff43001212008-01-15 19:36:10 +00001219
Eli Friedman50727042008-02-08 01:19:44 +00001220 if (lhsComplexInt && rhsComplexInt) {
Chris Lattner51285d82008-04-06 23:55:33 +00001221 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
1222 rhsComplexInt->getElementType()) >= 0) {
Eli Friedman94075c02008-02-08 01:24:30 +00001223 // convert the rhs
1224 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1225 return lhs;
Eli Friedman50727042008-02-08 01:19:44 +00001226 }
1227 if (!isCompAssign)
Eli Friedman94075c02008-02-08 01:24:30 +00001228 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Eli Friedman50727042008-02-08 01:19:44 +00001229 return rhs;
1230 } else if (lhsComplexInt && rhs->isIntegerType()) {
1231 // convert the rhs to the lhs complex type.
1232 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1233 return lhs;
1234 } else if (rhsComplexInt && lhs->isIntegerType()) {
1235 // convert the lhs to the rhs complex type.
1236 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1237 return rhs;
1238 }
Steve Naroff43001212008-01-15 19:36:10 +00001239 }
Chris Lattner4b009652007-07-25 00:24:17 +00001240 // Finally, we have two differing integer types.
Eli Friedman0832dbc2008-06-28 06:23:08 +00001241 // The rules for this case are in C99 6.3.1.8
1242 int compare = Context.getIntegerTypeOrder(lhs, rhs);
1243 bool lhsSigned = lhs->isSignedIntegerType(),
1244 rhsSigned = rhs->isSignedIntegerType();
1245 QualType destType;
1246 if (lhsSigned == rhsSigned) {
1247 // Same signedness; use the higher-ranked type
1248 destType = compare >= 0 ? lhs : rhs;
1249 } else if (compare != (lhsSigned ? 1 : -1)) {
1250 // The unsigned type has greater than or equal rank to the
1251 // signed type, so use the unsigned type
1252 destType = lhsSigned ? rhs : lhs;
1253 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
1254 // The two types are different widths; if we are here, that
1255 // means the signed type is larger than the unsigned type, so
1256 // use the signed type.
1257 destType = lhsSigned ? lhs : rhs;
1258 } else {
1259 // The signed type is higher-ranked than the unsigned type,
1260 // but isn't actually any bigger (like unsigned int and long
1261 // on most 32-bit systems). Use the unsigned type corresponding
1262 // to the signed type.
1263 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00001264 }
Eli Friedman0832dbc2008-06-28 06:23:08 +00001265 if (!isCompAssign) {
1266 ImpCastExprToType(lhsExpr, destType);
1267 ImpCastExprToType(rhsExpr, destType);
1268 }
1269 return destType;
Chris Lattner4b009652007-07-25 00:24:17 +00001270}
1271
1272// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1273// being closely modeled after the C99 spec:-). The odd characteristic of this
1274// routine is it effectively iqnores the qualifiers on the top level pointee.
1275// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1276// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001277Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001278Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1279 QualType lhptee, rhptee;
1280
1281 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001282 lhptee = lhsType->getAsPointerType()->getPointeeType();
1283 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001284
1285 // make sure we operate on the canonical type
1286 lhptee = lhptee.getCanonicalType();
1287 rhptee = rhptee.getCanonicalType();
1288
Chris Lattner005ed752008-01-04 18:04:52 +00001289 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001290
1291 // C99 6.5.16.1p1: This following citation is common to constraints
1292 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1293 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001294 // FIXME: Handle ASQualType
1295 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1296 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001297 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001298
1299 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1300 // incomplete type and the other is a pointer to a qualified or unqualified
1301 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001302 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001303 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001304 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001305
1306 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001307 assert(rhptee->isFunctionType());
1308 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001309 }
1310
1311 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001312 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001313 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001314
1315 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001316 assert(lhptee->isFunctionType());
1317 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001318 }
1319
Chris Lattner4b009652007-07-25 00:24:17 +00001320 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1321 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001322 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1323 rhptee.getUnqualifiedType()))
1324 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001325 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001326}
1327
1328/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1329/// has code to accommodate several GCC extensions when type checking
1330/// pointers. Here are some objectionable examples that GCC considers warnings:
1331///
1332/// int a, *pint;
1333/// short *pshort;
1334/// struct foo *pfoo;
1335///
1336/// pint = pshort; // warning: assignment from incompatible pointer type
1337/// a = pint; // warning: assignment makes integer from pointer without a cast
1338/// pint = a; // warning: assignment makes pointer from integer without a cast
1339/// pint = pfoo; // warning: assignment from incompatible pointer type
1340///
1341/// As a result, the code for dealing with pointers is more complex than the
1342/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001343///
Chris Lattner005ed752008-01-04 18:04:52 +00001344Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001345Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001346 // Get canonical types. We're not formatting these types, just comparing
1347 // them.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001348 lhsType = lhsType.getCanonicalType().getUnqualifiedType();
1349 rhsType = rhsType.getCanonicalType().getUnqualifiedType();
1350
1351 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001352 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001353
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001354 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001355 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001356 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001357 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001358 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001359
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001360 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1361 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001362 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001363 // Relax integer conversions like we do for pointers below.
1364 if (rhsType->isIntegerType())
1365 return IntToPointer;
1366 if (lhsType->isIntegerType())
1367 return PointerToInt;
Chris Lattner1853da22008-01-04 23:18:45 +00001368 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001369 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001370
Nate Begemanc5f0f652008-07-14 18:02:46 +00001371 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001372 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001373 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1374 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001375 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001376
Nate Begemanc5f0f652008-07-14 18:02:46 +00001377 // If we are allowing lax vector conversions, and LHS and RHS are both
1378 // vectors, the total size only needs to be the same. This is a bitcast;
1379 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001380 if (getLangOptions().LaxVectorConversions &&
1381 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001382 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1383 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001384 }
1385 return Incompatible;
1386 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001387
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001388 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001389 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001390
Chris Lattner390564e2008-04-07 06:49:41 +00001391 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001392 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001393 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001394
Chris Lattner390564e2008-04-07 06:49:41 +00001395 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001396 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001397 return Incompatible;
1398 }
1399
Chris Lattner390564e2008-04-07 06:49:41 +00001400 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001401 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001402 if (lhsType == Context.BoolTy)
1403 return Compatible;
1404
1405 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001406 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001407
Chris Lattner390564e2008-04-07 06:49:41 +00001408 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001409 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001410 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001411 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001412
Chris Lattner1853da22008-01-04 23:18:45 +00001413 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001414 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001415 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001416 }
1417 return Incompatible;
1418}
1419
Chris Lattner005ed752008-01-04 18:04:52 +00001420Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001421Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001422 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1423 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001424 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001425 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001426 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001427 return Compatible;
1428 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001429 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001430 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001431 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001432 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001433 //
1434 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1435 // are better understood.
1436 if (!lhsType->isReferenceType())
1437 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001438
Chris Lattner005ed752008-01-04 18:04:52 +00001439 Sema::AssignConvertType result =
1440 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001441
1442 // C99 6.5.16.1p2: The value of the right operand is converted to the
1443 // type of the assignment expression.
1444 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001445 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001446 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001447}
1448
Chris Lattner005ed752008-01-04 18:04:52 +00001449Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001450Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1451 return CheckAssignmentConstraints(lhsType, rhsType);
1452}
1453
Chris Lattner2c8bff72007-12-12 05:47:28 +00001454QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001455 Diag(loc, diag::err_typecheck_invalid_operands,
1456 lex->getType().getAsString(), rex->getType().getAsString(),
1457 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001458 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001459}
1460
1461inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1462 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001463 // For conversion purposes, we ignore any qualifiers.
1464 // For example, "const float" and "float" are equivalent.
1465 QualType lhsType = lex->getType().getCanonicalType().getUnqualifiedType();
1466 QualType rhsType = rex->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001467
Nate Begemanc5f0f652008-07-14 18:02:46 +00001468 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001469 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001470 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001471
Nate Begemanc5f0f652008-07-14 18:02:46 +00001472 // Handle the case of a vector & extvector type of the same size and element
1473 // type. It would be nice if we only had one vector type someday.
1474 if (getLangOptions().LaxVectorConversions)
1475 if (const VectorType *LV = lhsType->getAsVectorType())
1476 if (const VectorType *RV = rhsType->getAsVectorType())
1477 if (LV->getElementType() == RV->getElementType() &&
1478 LV->getNumElements() == RV->getNumElements())
1479 return lhsType->isExtVectorType() ? lhsType : rhsType;
1480
1481 // If the lhs is an extended vector and the rhs is a scalar of the same type
1482 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001483 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001484 QualType eltType = V->getElementType();
1485
1486 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1487 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1488 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001489 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001490 return lhsType;
1491 }
1492 }
1493
Nate Begemanc5f0f652008-07-14 18:02:46 +00001494 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001495 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001496 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001497 QualType eltType = V->getElementType();
1498
1499 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1500 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1501 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001502 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001503 return rhsType;
1504 }
1505 }
1506
Chris Lattner4b009652007-07-25 00:24:17 +00001507 // You cannot convert between vector values of different size.
1508 Diag(loc, diag::err_typecheck_vector_not_convertable,
1509 lex->getType().getAsString(), rex->getType().getAsString(),
1510 lex->getSourceRange(), rex->getSourceRange());
1511 return QualType();
1512}
1513
1514inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001515 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001516{
1517 QualType lhsType = lex->getType(), rhsType = rex->getType();
1518
1519 if (lhsType->isVectorType() || rhsType->isVectorType())
1520 return CheckVectorOperands(loc, lex, rex);
1521
Steve Naroff8f708362007-08-24 19:07:16 +00001522 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001523
Chris Lattner4b009652007-07-25 00:24:17 +00001524 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001525 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001526 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001527}
1528
1529inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001530 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001531{
1532 QualType lhsType = lex->getType(), rhsType = rex->getType();
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()->isIntegerType() && rex->getType()->isIntegerType())
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::CheckAdditionOperands( // C99 6.5.6
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 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1545 return CheckVectorOperands(loc, lex, rex);
1546
Steve Naroff8f708362007-08-24 19:07:16 +00001547 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001548
Chris Lattner4b009652007-07-25 00:24:17 +00001549 // handle the common case first (both operands are arithmetic).
1550 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001551 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001552
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001553 // Put any potential pointer into PExp
1554 Expr* PExp = lex, *IExp = rex;
1555 if (IExp->getType()->isPointerType())
1556 std::swap(PExp, IExp);
1557
1558 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1559 if (IExp->getType()->isIntegerType()) {
1560 // Check for arithmetic on pointers to incomplete types
1561 if (!PTy->getPointeeType()->isObjectType()) {
1562 if (PTy->getPointeeType()->isVoidType()) {
1563 Diag(loc, diag::ext_gnu_void_ptr,
1564 lex->getSourceRange(), rex->getSourceRange());
1565 } else {
1566 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1567 lex->getType().getAsString(), lex->getSourceRange());
1568 return QualType();
1569 }
1570 }
1571 return PExp->getType();
1572 }
1573 }
1574
Chris Lattner2c8bff72007-12-12 05:47:28 +00001575 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001576}
1577
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001578// C99 6.5.6
1579QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1580 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001581 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1582 return CheckVectorOperands(loc, lex, rex);
1583
Steve Naroff8f708362007-08-24 19:07:16 +00001584 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001585
Chris Lattnerf6da2912007-12-09 21:53:25 +00001586 // Enforce type constraints: C99 6.5.6p3.
1587
1588 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001589 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001590 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001591
1592 // Either ptr - int or ptr - ptr.
1593 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001594 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001595
Chris Lattnerf6da2912007-12-09 21:53:25 +00001596 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001597 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001598 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001599 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001600 Diag(loc, diag::ext_gnu_void_ptr,
1601 lex->getSourceRange(), rex->getSourceRange());
1602 } else {
1603 Diag(loc, diag::err_typecheck_sub_ptr_object,
1604 lex->getType().getAsString(), lex->getSourceRange());
1605 return QualType();
1606 }
1607 }
1608
1609 // The result type of a pointer-int computation is the pointer type.
1610 if (rex->getType()->isIntegerType())
1611 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001612
Chris Lattnerf6da2912007-12-09 21:53:25 +00001613 // Handle pointer-pointer subtractions.
1614 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001615 QualType rpointee = RHSPTy->getPointeeType();
1616
Chris Lattnerf6da2912007-12-09 21:53:25 +00001617 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001618 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001619 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001620 if (rpointee->isVoidType()) {
1621 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001622 Diag(loc, diag::ext_gnu_void_ptr,
1623 lex->getSourceRange(), rex->getSourceRange());
1624 } else {
1625 Diag(loc, diag::err_typecheck_sub_ptr_object,
1626 rex->getType().getAsString(), rex->getSourceRange());
1627 return QualType();
1628 }
1629 }
1630
1631 // Pointee types must be compatible.
Steve Naroff577f9722008-01-29 18:58:14 +00001632 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1633 rpointee.getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001634 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1635 lex->getType().getAsString(), rex->getType().getAsString(),
1636 lex->getSourceRange(), rex->getSourceRange());
1637 return QualType();
1638 }
1639
1640 return Context.getPointerDiffType();
1641 }
1642 }
1643
Chris Lattner2c8bff72007-12-12 05:47:28 +00001644 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001645}
1646
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001647// C99 6.5.7
1648QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1649 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00001650 // C99 6.5.7p2: Each of the operands shall have integer type.
1651 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1652 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001653
Chris Lattner2c8bff72007-12-12 05:47:28 +00001654 // Shifts don't perform usual arithmetic conversions, they just do integer
1655 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001656 if (!isCompAssign)
1657 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001658 UsualUnaryConversions(rex);
1659
1660 // "The type of the result is that of the promoted left operand."
1661 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001662}
1663
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001664// C99 6.5.8
1665QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1666 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001667 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1668 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1669
Chris Lattner254f3bc2007-08-26 01:18:55 +00001670 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001671 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1672 UsualArithmeticConversions(lex, rex);
1673 else {
1674 UsualUnaryConversions(lex);
1675 UsualUnaryConversions(rex);
1676 }
Chris Lattner4b009652007-07-25 00:24:17 +00001677 QualType lType = lex->getType();
1678 QualType rType = rex->getType();
1679
Ted Kremenek486509e2007-10-29 17:13:39 +00001680 // For non-floating point types, check for self-comparisons of the form
1681 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1682 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001683 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001684 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1685 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001686 if (DRL->getDecl() == DRR->getDecl())
1687 Diag(loc, diag::warn_selfcomparison);
1688 }
1689
Chris Lattner254f3bc2007-08-26 01:18:55 +00001690 if (isRelational) {
1691 if (lType->isRealType() && rType->isRealType())
1692 return Context.IntTy;
1693 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001694 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001695 if (lType->isFloatingType()) {
1696 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001697 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001698 }
1699
Chris Lattner254f3bc2007-08-26 01:18:55 +00001700 if (lType->isArithmeticType() && rType->isArithmeticType())
1701 return Context.IntTy;
1702 }
Chris Lattner4b009652007-07-25 00:24:17 +00001703
Chris Lattner22be8422007-08-26 01:10:14 +00001704 bool LHSIsNull = lex->isNullPointerConstant(Context);
1705 bool RHSIsNull = rex->isNullPointerConstant(Context);
1706
Chris Lattner254f3bc2007-08-26 01:18:55 +00001707 // All of the following pointer related warnings are GCC extensions, except
1708 // when handling null pointer constants. One day, we can consider making them
1709 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001710 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001711 QualType LCanPointeeTy =
1712 lType->getAsPointerType()->getPointeeType().getCanonicalType();
1713 QualType RCanPointeeTy =
1714 rType->getAsPointerType()->getPointeeType().getCanonicalType();
Eli Friedman50727042008-02-08 01:19:44 +00001715
Steve Naroff3b435622007-11-13 14:57:38 +00001716 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001717 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1718 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
1719 RCanPointeeTy.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001720 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1721 lType.getAsString(), rType.getAsString(),
1722 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001723 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001724 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001725 return Context.IntTy;
1726 }
Steve Naroff936c4362008-06-03 14:04:54 +00001727 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
1728 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
1729 ImpCastExprToType(rex, lType);
1730 return Context.IntTy;
1731 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001732 }
Steve Naroff936c4362008-06-03 14:04:54 +00001733 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
1734 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001735 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001736 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1737 lType.getAsString(), rType.getAsString(),
1738 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001739 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001740 return Context.IntTy;
1741 }
Steve Naroff936c4362008-06-03 14:04:54 +00001742 if (lType->isIntegerType() &&
1743 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00001744 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001745 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1746 lType.getAsString(), rType.getAsString(),
1747 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001748 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001749 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001750 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001751 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001752}
1753
Nate Begemanc5f0f652008-07-14 18:02:46 +00001754/// CheckVectorCompareOperands - vector comparisons are a clang extension that
1755/// operates on extended vector types. Instead of producing an IntTy result,
1756/// like a scalar comparison, a vector comparison produces a vector of integer
1757/// types.
1758QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
1759 SourceLocation loc,
1760 bool isRelational) {
1761 // Check to make sure we're operating on vectors of the same type and width,
1762 // Allowing one side to be a scalar of element type.
1763 QualType vType = CheckVectorOperands(loc, lex, rex);
1764 if (vType.isNull())
1765 return vType;
1766
1767 QualType lType = lex->getType();
1768 QualType rType = rex->getType();
1769
1770 // For non-floating point types, check for self-comparisons of the form
1771 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1772 // often indicate logic errors in the program.
1773 if (!lType->isFloatingType()) {
1774 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1775 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1776 if (DRL->getDecl() == DRR->getDecl())
1777 Diag(loc, diag::warn_selfcomparison);
1778 }
1779
1780 // Check for comparisons of floating point operands using != and ==.
1781 if (!isRelational && lType->isFloatingType()) {
1782 assert (rType->isFloatingType());
1783 CheckFloatComparison(loc,lex,rex);
1784 }
1785
1786 // Return the type for the comparison, which is the same as vector type for
1787 // integer vectors, or an integer type of identical size and number of
1788 // elements for floating point vectors.
1789 if (lType->isIntegerType())
1790 return lType;
1791
1792 const VectorType *VTy = lType->getAsVectorType();
1793
1794 // FIXME: need to deal with non-32b int / non-64b long long
1795 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
1796 if (TypeSize == 32) {
1797 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
1798 }
1799 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
1800 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
1801}
1802
Chris Lattner4b009652007-07-25 00:24:17 +00001803inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001804 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001805{
1806 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1807 return CheckVectorOperands(loc, lex, rex);
1808
Steve Naroff8f708362007-08-24 19:07:16 +00001809 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001810
1811 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001812 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001813 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001814}
1815
1816inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1817 Expr *&lex, Expr *&rex, SourceLocation loc)
1818{
1819 UsualUnaryConversions(lex);
1820 UsualUnaryConversions(rex);
1821
Eli Friedmanbea3f842008-05-13 20:16:47 +00001822 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00001823 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001824 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001825}
1826
1827inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001828 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001829{
1830 QualType lhsType = lex->getType();
1831 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner4b009652007-07-25 00:24:17 +00001832 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1833
1834 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001835 case Expr::MLV_Valid:
1836 break;
1837 case Expr::MLV_ConstQualified:
1838 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1839 return QualType();
1840 case Expr::MLV_ArrayType:
1841 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1842 lhsType.getAsString(), lex->getSourceRange());
1843 return QualType();
1844 case Expr::MLV_NotObjectType:
1845 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1846 lhsType.getAsString(), lex->getSourceRange());
1847 return QualType();
1848 case Expr::MLV_InvalidExpression:
1849 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1850 lex->getSourceRange());
1851 return QualType();
1852 case Expr::MLV_IncompleteType:
1853 case Expr::MLV_IncompleteVoidType:
1854 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1855 lhsType.getAsString(), lex->getSourceRange());
1856 return QualType();
1857 case Expr::MLV_DuplicateVectorComponents:
1858 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1859 lex->getSourceRange());
1860 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001861 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001862
Chris Lattner005ed752008-01-04 18:04:52 +00001863 AssignConvertType ConvTy;
1864 if (compoundType.isNull())
1865 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1866 else
1867 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1868
1869 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1870 rex, "assigning"))
1871 return QualType();
1872
Chris Lattner4b009652007-07-25 00:24:17 +00001873 // C99 6.5.16p3: The type of an assignment expression is the type of the
1874 // left operand unless the left operand has qualified type, in which case
1875 // it is the unqualified version of the type of the left operand.
1876 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1877 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001878 // C++ 5.17p1: the type of the assignment expression is that of its left
1879 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001880 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001881}
1882
1883inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1884 Expr *&lex, Expr *&rex, SourceLocation loc) {
1885 UsualUnaryConversions(rex);
1886 return rex->getType();
1887}
1888
1889/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1890/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1891QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1892 QualType resType = op->getType();
1893 assert(!resType.isNull() && "no type for increment/decrement expression");
1894
Steve Naroffd30e1932007-08-24 17:20:07 +00001895 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001896 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001897 if (pt->getPointeeType()->isVoidType()) {
1898 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
1899 } else if (!pt->getPointeeType()->isObjectType()) {
1900 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00001901 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1902 resType.getAsString(), op->getSourceRange());
1903 return QualType();
1904 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001905 } else if (!resType->isRealType()) {
1906 if (resType->isComplexType())
1907 // C99 does not support ++/-- on complex types.
1908 Diag(OpLoc, diag::ext_integer_increment_complex,
1909 resType.getAsString(), op->getSourceRange());
1910 else {
1911 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1912 resType.getAsString(), op->getSourceRange());
1913 return QualType();
1914 }
Chris Lattner4b009652007-07-25 00:24:17 +00001915 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001916 // At this point, we know we have a real, complex or pointer type.
1917 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001918 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1919 if (mlval != Expr::MLV_Valid) {
1920 // FIXME: emit a more precise diagnostic...
1921 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1922 op->getSourceRange());
1923 return QualType();
1924 }
1925 return resType;
1926}
1927
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001928/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00001929/// This routine allows us to typecheck complex/recursive expressions
1930/// where the declaration is needed for type checking. Here are some
1931/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
Chris Lattner48d7f382008-04-02 04:24:33 +00001932static ValueDecl *getPrimaryDecl(Expr *E) {
1933 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001934 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001935 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001936 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001937 // Fields cannot be declared with a 'register' storage class.
1938 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00001939 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00001940 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00001941 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001942 case Stmt::ArraySubscriptExprClass: {
1943 // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer.
1944
Chris Lattner48d7f382008-04-02 04:24:33 +00001945 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00001946 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001947 return 0;
1948 else
1949 return VD;
1950 }
Chris Lattner4b009652007-07-25 00:24:17 +00001951 case Stmt::UnaryOperatorClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001952 return getPrimaryDecl(cast<UnaryOperator>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001953 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001954 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001955 case Stmt::ImplicitCastExprClass:
1956 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00001957 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001958 default:
1959 return 0;
1960 }
1961}
1962
1963/// CheckAddressOfOperand - The operand of & must be either a function
1964/// designator or an lvalue designating an object. If it is an lvalue, the
1965/// object cannot be declared with storage class register or be a bit field.
1966/// Note: The usual conversions are *not* applied to the operand of the &
1967/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1968QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001969 if (getLangOptions().C99) {
1970 // Implement C99-only parts of addressof rules.
1971 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
1972 if (uOp->getOpcode() == UnaryOperator::Deref)
1973 // Per C99 6.5.3.2, the address of a deref always returns a valid result
1974 // (assuming the deref expression is valid).
1975 return uOp->getSubExpr()->getType();
1976 }
1977 // Technically, there should be a check for array subscript
1978 // expressions here, but the result of one is always an lvalue anyway.
1979 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001980 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner4b009652007-07-25 00:24:17 +00001981 Expr::isLvalueResult lval = op->isLvalue();
1982
1983 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001984 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1985 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001986 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1987 op->getSourceRange());
1988 return QualType();
1989 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00001990 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
1991 if (MemExpr->getMemberDecl()->isBitField()) {
1992 Diag(OpLoc, diag::err_typecheck_address_of,
1993 std::string("bit-field"), op->getSourceRange());
1994 return QualType();
1995 }
1996 // Check for Apple extension for accessing vector components.
1997 } else if (isa<ArraySubscriptExpr>(op) &&
1998 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
1999 Diag(OpLoc, diag::err_typecheck_address_of,
2000 std::string("vector"), op->getSourceRange());
2001 return QualType();
2002 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002003 // We have an lvalue with a decl. Make sure the decl is not declared
2004 // with the register storage-class specifier.
2005 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2006 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002007 Diag(OpLoc, diag::err_typecheck_address_of,
2008 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002009 return QualType();
2010 }
2011 } else
2012 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002013 }
2014 // If the operand has type "type", the result has type "pointer to type".
2015 return Context.getPointerType(op->getType());
2016}
2017
2018QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2019 UsualUnaryConversions(op);
2020 QualType qType = op->getType();
2021
Chris Lattner7931f4a2007-07-31 16:53:04 +00002022 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002023 // Note that per both C89 and C99, this is always legal, even
2024 // if ptype is an incomplete type or void.
2025 // It would be possible to warn about dereferencing a
2026 // void pointer, but it's completely well-defined,
2027 // and such a warning is unlikely to catch any mistakes.
2028 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002029 }
2030 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2031 qType.getAsString(), op->getSourceRange());
2032 return QualType();
2033}
2034
2035static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2036 tok::TokenKind Kind) {
2037 BinaryOperator::Opcode Opc;
2038 switch (Kind) {
2039 default: assert(0 && "Unknown binop!");
2040 case tok::star: Opc = BinaryOperator::Mul; break;
2041 case tok::slash: Opc = BinaryOperator::Div; break;
2042 case tok::percent: Opc = BinaryOperator::Rem; break;
2043 case tok::plus: Opc = BinaryOperator::Add; break;
2044 case tok::minus: Opc = BinaryOperator::Sub; break;
2045 case tok::lessless: Opc = BinaryOperator::Shl; break;
2046 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2047 case tok::lessequal: Opc = BinaryOperator::LE; break;
2048 case tok::less: Opc = BinaryOperator::LT; break;
2049 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2050 case tok::greater: Opc = BinaryOperator::GT; break;
2051 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2052 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2053 case tok::amp: Opc = BinaryOperator::And; break;
2054 case tok::caret: Opc = BinaryOperator::Xor; break;
2055 case tok::pipe: Opc = BinaryOperator::Or; break;
2056 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2057 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2058 case tok::equal: Opc = BinaryOperator::Assign; break;
2059 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2060 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2061 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2062 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2063 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2064 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2065 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2066 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2067 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2068 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2069 case tok::comma: Opc = BinaryOperator::Comma; break;
2070 }
2071 return Opc;
2072}
2073
2074static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2075 tok::TokenKind Kind) {
2076 UnaryOperator::Opcode Opc;
2077 switch (Kind) {
2078 default: assert(0 && "Unknown unary op!");
2079 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2080 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2081 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2082 case tok::star: Opc = UnaryOperator::Deref; break;
2083 case tok::plus: Opc = UnaryOperator::Plus; break;
2084 case tok::minus: Opc = UnaryOperator::Minus; break;
2085 case tok::tilde: Opc = UnaryOperator::Not; break;
2086 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2087 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2088 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2089 case tok::kw___real: Opc = UnaryOperator::Real; break;
2090 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2091 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2092 }
2093 return Opc;
2094}
2095
2096// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002097Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002098 ExprTy *LHS, ExprTy *RHS) {
2099 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2100 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2101
Steve Naroff87d58b42007-09-16 03:34:24 +00002102 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2103 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002104
2105 QualType ResultTy; // Result type of the binary operator.
2106 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2107
2108 switch (Opc) {
2109 default:
2110 assert(0 && "Unknown binary expr!");
2111 case BinaryOperator::Assign:
2112 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2113 break;
2114 case BinaryOperator::Mul:
2115 case BinaryOperator::Div:
2116 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2117 break;
2118 case BinaryOperator::Rem:
2119 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2120 break;
2121 case BinaryOperator::Add:
2122 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2123 break;
2124 case BinaryOperator::Sub:
2125 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2126 break;
2127 case BinaryOperator::Shl:
2128 case BinaryOperator::Shr:
2129 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2130 break;
2131 case BinaryOperator::LE:
2132 case BinaryOperator::LT:
2133 case BinaryOperator::GE:
2134 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002135 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002136 break;
2137 case BinaryOperator::EQ:
2138 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002139 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00002140 break;
2141 case BinaryOperator::And:
2142 case BinaryOperator::Xor:
2143 case BinaryOperator::Or:
2144 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2145 break;
2146 case BinaryOperator::LAnd:
2147 case BinaryOperator::LOr:
2148 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2149 break;
2150 case BinaryOperator::MulAssign:
2151 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002152 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002153 if (!CompTy.isNull())
2154 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2155 break;
2156 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002157 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002158 if (!CompTy.isNull())
2159 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2160 break;
2161 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002162 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002163 if (!CompTy.isNull())
2164 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2165 break;
2166 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002167 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002168 if (!CompTy.isNull())
2169 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2170 break;
2171 case BinaryOperator::ShlAssign:
2172 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002173 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002174 if (!CompTy.isNull())
2175 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2176 break;
2177 case BinaryOperator::AndAssign:
2178 case BinaryOperator::XorAssign:
2179 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002180 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002181 if (!CompTy.isNull())
2182 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2183 break;
2184 case BinaryOperator::Comma:
2185 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2186 break;
2187 }
2188 if (ResultTy.isNull())
2189 return true;
2190 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00002191 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002192 else
Chris Lattnerf420df12007-08-28 18:36:55 +00002193 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002194}
2195
2196// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002197Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002198 ExprTy *input) {
2199 Expr *Input = (Expr*)input;
2200 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2201 QualType resultType;
2202 switch (Opc) {
2203 default:
2204 assert(0 && "Unimplemented unary expr!");
2205 case UnaryOperator::PreInc:
2206 case UnaryOperator::PreDec:
2207 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2208 break;
2209 case UnaryOperator::AddrOf:
2210 resultType = CheckAddressOfOperand(Input, OpLoc);
2211 break;
2212 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002213 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002214 resultType = CheckIndirectionOperand(Input, OpLoc);
2215 break;
2216 case UnaryOperator::Plus:
2217 case UnaryOperator::Minus:
2218 UsualUnaryConversions(Input);
2219 resultType = Input->getType();
2220 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2221 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2222 resultType.getAsString());
2223 break;
2224 case UnaryOperator::Not: // bitwise complement
2225 UsualUnaryConversions(Input);
2226 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00002227 // C99 6.5.3.3p1. We allow complex as a GCC extension.
2228 if (!resultType->isIntegerType()) {
2229 if (resultType->isComplexType())
2230 // C99 does not support '~' for complex conjugation.
2231 Diag(OpLoc, diag::ext_integer_complement_complex,
2232 resultType.getAsString());
2233 else
2234 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2235 resultType.getAsString());
2236 }
Chris Lattner4b009652007-07-25 00:24:17 +00002237 break;
2238 case UnaryOperator::LNot: // logical negation
2239 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2240 DefaultFunctionArrayConversion(Input);
2241 resultType = Input->getType();
2242 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2243 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2244 resultType.getAsString());
2245 // LNot always has type int. C99 6.5.3.3p5.
2246 resultType = Context.IntTy;
2247 break;
2248 case UnaryOperator::SizeOf:
2249 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
2250 break;
2251 case UnaryOperator::AlignOf:
2252 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
2253 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002254 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002255 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002256 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002257 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002258 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002259 resultType = Input->getType();
2260 break;
2261 }
2262 if (resultType.isNull())
2263 return true;
2264 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2265}
2266
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002267/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2268Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002269 SourceLocation LabLoc,
2270 IdentifierInfo *LabelII) {
2271 // Look up the record for this label identifier.
2272 LabelStmt *&LabelDecl = LabelMap[LabelII];
2273
2274 // If we haven't seen this label yet, create a forward reference.
2275 if (LabelDecl == 0)
2276 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2277
2278 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002279 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2280 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002281}
2282
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002283Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002284 SourceLocation RPLoc) { // "({..})"
2285 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2286 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2287 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2288
2289 // FIXME: there are a variety of strange constraints to enforce here, for
2290 // example, it is not possible to goto into a stmt expression apparently.
2291 // More semantic analysis is needed.
2292
2293 // FIXME: the last statement in the compount stmt has its value used. We
2294 // should not warn about it being unused.
2295
2296 // If there are sub stmts in the compound stmt, take the type of the last one
2297 // as the type of the stmtexpr.
2298 QualType Ty = Context.VoidTy;
2299
2300 if (!Compound->body_empty())
2301 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
2302 Ty = LastExpr->getType();
2303
2304 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2305}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002306
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002307Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002308 SourceLocation TypeLoc,
2309 TypeTy *argty,
2310 OffsetOfComponent *CompPtr,
2311 unsigned NumComponents,
2312 SourceLocation RPLoc) {
2313 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2314 assert(!ArgTy.isNull() && "Missing type argument!");
2315
2316 // We must have at least one component that refers to the type, and the first
2317 // one is known to be a field designator. Verify that the ArgTy represents
2318 // a struct/union/class.
2319 if (!ArgTy->isRecordType())
2320 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2321
2322 // Otherwise, create a compound literal expression as the base, and
2323 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002324 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002325
Chris Lattnerb37522e2007-08-31 21:49:13 +00002326 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2327 // GCC extension, diagnose them.
2328 if (NumComponents != 1)
2329 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2330 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2331
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002332 for (unsigned i = 0; i != NumComponents; ++i) {
2333 const OffsetOfComponent &OC = CompPtr[i];
2334 if (OC.isBrackets) {
2335 // Offset of an array sub-field. TODO: Should we allow vector elements?
2336 const ArrayType *AT = Res->getType()->getAsArrayType();
2337 if (!AT) {
2338 delete Res;
2339 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2340 Res->getType().getAsString());
2341 }
2342
Chris Lattner2af6a802007-08-30 17:59:59 +00002343 // FIXME: C++: Verify that operator[] isn't overloaded.
2344
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002345 // C99 6.5.2.1p1
2346 Expr *Idx = static_cast<Expr*>(OC.U.E);
2347 if (!Idx->getType()->isIntegerType())
2348 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2349 Idx->getSourceRange());
2350
2351 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2352 continue;
2353 }
2354
2355 const RecordType *RC = Res->getType()->getAsRecordType();
2356 if (!RC) {
2357 delete Res;
2358 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2359 Res->getType().getAsString());
2360 }
2361
2362 // Get the decl corresponding to this.
2363 RecordDecl *RD = RC->getDecl();
2364 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2365 if (!MemberDecl)
2366 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2367 OC.U.IdentInfo->getName(),
2368 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002369
2370 // FIXME: C++: Verify that MemberDecl isn't a static field.
2371 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002372 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2373 // matter here.
2374 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002375 }
2376
2377 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2378 BuiltinLoc);
2379}
2380
2381
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002382Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002383 TypeTy *arg1, TypeTy *arg2,
2384 SourceLocation RPLoc) {
2385 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2386 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2387
2388 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2389
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002390 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002391}
2392
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002393Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002394 ExprTy *expr1, ExprTy *expr2,
2395 SourceLocation RPLoc) {
2396 Expr *CondExpr = static_cast<Expr*>(cond);
2397 Expr *LHSExpr = static_cast<Expr*>(expr1);
2398 Expr *RHSExpr = static_cast<Expr*>(expr2);
2399
2400 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2401
2402 // The conditional expression is required to be a constant expression.
2403 llvm::APSInt condEval(32);
2404 SourceLocation ExpLoc;
2405 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2406 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2407 CondExpr->getSourceRange());
2408
2409 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2410 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2411 RHSExpr->getType();
2412 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2413}
2414
Nate Begemanbd881ef2008-01-30 20:50:20 +00002415/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002416/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002417/// The number of arguments has already been validated to match the number of
2418/// arguments in FnType.
2419static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002420 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00002421 for (unsigned i = 0; i != NumParams; ++i) {
2422 QualType ExprTy = Args[i]->getType().getCanonicalType();
2423 QualType ParmTy = FnType->getArgType(i).getCanonicalType();
2424
2425 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002426 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00002427 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002428 return true;
2429}
2430
2431Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2432 SourceLocation *CommaLocs,
2433 SourceLocation BuiltinLoc,
2434 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002435 // __builtin_overload requires at least 2 arguments
2436 if (NumArgs < 2)
2437 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2438 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002439
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002440 // The first argument is required to be a constant expression. It tells us
2441 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002442 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002443 Expr *NParamsExpr = Args[0];
2444 llvm::APSInt constEval(32);
2445 SourceLocation ExpLoc;
2446 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2447 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2448 NParamsExpr->getSourceRange());
2449
2450 // Verify that the number of parameters is > 0
2451 unsigned NumParams = constEval.getZExtValue();
2452 if (NumParams == 0)
2453 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2454 NParamsExpr->getSourceRange());
2455 // Verify that we have at least 1 + NumParams arguments to the builtin.
2456 if ((NumParams + 1) > NumArgs)
2457 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2458 SourceRange(BuiltinLoc, RParenLoc));
2459
2460 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002461 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002462 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002463 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2464 // UsualUnaryConversions will convert the function DeclRefExpr into a
2465 // pointer to function.
2466 Expr *Fn = UsualUnaryConversions(Args[i]);
2467 FunctionTypeProto *FnType = 0;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002468 if (const PointerType *PT = Fn->getType()->getAsPointerType()) {
2469 QualType PointeeType = PT->getPointeeType().getCanonicalType();
2470 FnType = dyn_cast<FunctionTypeProto>(PointeeType);
2471 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002472
2473 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2474 // parameters, and the number of parameters must match the value passed to
2475 // the builtin.
2476 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002477 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2478 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002479
2480 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002481 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002482 // If they match, return a new OverloadExpr.
Nate Begemanc6078c92008-01-31 05:38:29 +00002483 if (ExprsMatchFnType(Args+1, FnType)) {
2484 if (OE)
2485 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2486 OE->getFn()->getSourceRange());
2487 // Remember our match, and continue processing the remaining arguments
2488 // to catch any errors.
2489 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2490 BuiltinLoc, RParenLoc);
2491 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002492 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002493 // Return the newly created OverloadExpr node, if we succeded in matching
2494 // exactly one of the candidate functions.
2495 if (OE)
2496 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002497
2498 // If we didn't find a matching function Expr in the __builtin_overload list
2499 // the return an error.
2500 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002501 for (unsigned i = 0; i != NumParams; ++i) {
2502 if (i != 0) typeNames += ", ";
2503 typeNames += Args[i+1]->getType().getAsString();
2504 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002505
2506 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2507 SourceRange(BuiltinLoc, RParenLoc));
2508}
2509
Anders Carlsson36760332007-10-15 20:28:48 +00002510Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2511 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002512 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002513 Expr *E = static_cast<Expr*>(expr);
2514 QualType T = QualType::getFromOpaquePtr(type);
2515
2516 InitBuiltinVaListType();
2517
Chris Lattner005ed752008-01-04 18:04:52 +00002518 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2519 != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002520 return Diag(E->getLocStart(),
2521 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2522 E->getType().getAsString(),
2523 E->getSourceRange());
2524
2525 // FIXME: Warn if a non-POD type is passed in.
2526
2527 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2528}
2529
Chris Lattner005ed752008-01-04 18:04:52 +00002530bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2531 SourceLocation Loc,
2532 QualType DstType, QualType SrcType,
2533 Expr *SrcExpr, const char *Flavor) {
2534 // Decode the result (notice that AST's are still created for extensions).
2535 bool isInvalid = false;
2536 unsigned DiagKind;
2537 switch (ConvTy) {
2538 default: assert(0 && "Unknown conversion type");
2539 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002540 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002541 DiagKind = diag::ext_typecheck_convert_pointer_int;
2542 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002543 case IntToPointer:
2544 DiagKind = diag::ext_typecheck_convert_int_pointer;
2545 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002546 case IncompatiblePointer:
2547 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2548 break;
2549 case FunctionVoidPointer:
2550 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2551 break;
2552 case CompatiblePointerDiscardsQualifiers:
2553 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2554 break;
2555 case Incompatible:
2556 DiagKind = diag::err_typecheck_convert_incompatible;
2557 isInvalid = true;
2558 break;
2559 }
2560
2561 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2562 SrcExpr->getSourceRange());
2563 return isInvalid;
2564}