blob: 13f7ff9fb711bbce69f60489c4434a4fe3eb1934 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Ted Kremenek588e5eb2007-11-25 00:58:00 +000015#include "SemaUtil.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000017#include "clang/AST/DeclCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000019#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000020#include "clang/AST/ExprObjC.h"
Steve Naroff563477d2007-09-18 23:55:05 +000021#include "clang/Parse/DeclSpec.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Lex/Preprocessor.h"
23#include "clang/Lex/LiteralSupport.h"
24#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "clang/Basic/TargetInfo.h"
Chris Lattner925e60d2007-12-28 05:29:59 +000026#include "llvm/ADT/OwningPtr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000028#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30
Steve Narofff69936d2007-09-16 03:34:24 +000031/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofff69936d2007-09-16 03:34:24 +000038Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnera7ad98f2008-02-11 00:02:17 +000048
49 // Verify that pascal strings aren't too large.
Anders Carlssonee98ac52007-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()));
Reid Spencer5f016e22007-07-11 17:01:13 +000054
Chris Lattnera7ad98f2008-02-11 00:02:17 +000055 QualType StrTy = Context.CharTy;
Eli Friedman8ef1f262008-05-27 07:57:14 +000056 if (Literal.AnyWide) StrTy = Context.getWcharType();
Chris Lattnera7ad98f2008-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
Reid Spencer5f016e22007-07-11 17:01:13 +000066 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
67 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera7ad98f2008-02-11 00:02:17 +000068 Literal.AnyWide, StrTy,
Anders Carlssonee98ac52007-10-15 02:50:23 +000069 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +000070 StringToks[NumStringToks-1].getLocation());
71}
72
73
Steve Naroff08d92e42007-09-15 18:49:24 +000074/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +000075/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +000076/// identifier is used in a function call context.
Steve Naroff08d92e42007-09-15 18:49:24 +000077Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +000078 IdentifierInfo &II,
79 bool HasTrailingLParen) {
Chris Lattner8a934232008-03-31 00:36:02 +000080 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroffb327ce02008-04-02 14:35:35 +000081 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattner8a934232008-03-31 00:36:02 +000082
83 // If this reference is in an Objective-C method, then ivar lookup happens as
84 // well.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +000085 if (getCurMethodDecl()) {
Steve Naroffe8043c32008-04-01 23:04:06 +000086 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattner8a934232008-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 Naroffe8043c32008-04-01 23:04:06 +000092 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +000093 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattner123a11f2008-07-21 04:44:44 +000094 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattner8a934232008-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 Naroff8f0b1022008-06-05 18:14:25 +0000103 if (SD == 0 && !strcmp(II.getName(), "super")) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000104 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000105 getCurMethodDecl()->getClassInterface()));
Steve Naroffe3e9add2008-06-02 23:03:37 +0000106 return new ObjCSuperRefExpr(T, Loc);
107 }
Chris Lattner8a934232008-03-31 00:36:02 +0000108 }
109
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner8a934232008-03-31 00:36:02 +0000114 !getLangOptions().CPlusPlus) // Not in C++.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner8a934232008-03-31 00:36:02 +0000122
Steve Naroffe1223f72007-08-28 03:03:08 +0000123 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner7e669b22008-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 Naroff53a32342007-08-28 18:45:29 +0000128 // Only create DeclRefExpr's for valid Decl's.
Steve Naroff5912a352007-08-28 20:14:24 +0000129 if (VD->isInvalidDecl())
Steve Naroffe1223f72007-08-28 03:03:08 +0000130 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000131 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroffe1223f72007-08-28 03:03:08 +0000132 }
Argyrios Kyrtzidis07952322008-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 Lattner8a934232008-03-31 00:36:02 +0000156
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 if (isa<TypedefDecl>(D))
158 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000159 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian5ef404f2007-12-05 18:16:33 +0000160 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000161 if (isa<NamespaceDecl>(D))
162 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000163
164 assert(0 && "Invalid decl");
Chris Lattnereddbe032007-07-21 04:57:45 +0000165 abort();
Reid Spencer5f016e22007-07-11 17:01:13 +0000166}
167
Steve Narofff69936d2007-09-16 03:34:24 +0000168Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000169 tok::TokenKind Kind) {
170 PreDefinedExpr::IdentType IT;
171
Reid Spencer5f016e22007-07-11 17:01:13 +0000172 switch (Kind) {
Chris Lattner1423ea42008-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;
Reid Spencer5f016e22007-07-11 17:01:13 +0000177 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000178
179 // Verify that this is in a function context.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000180 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattner1423ea42008-01-12 18:39:25 +0000181 return Diag(Loc, diag::err_predef_outside_function);
Anders Carlsson22742662007-07-21 05:21:51 +0000182
Chris Lattnerfa28b302008-01-12 08:14:25 +0000183 // Pre-defined identifiers are of type char[x], where x is the length of the
184 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000185 unsigned Length;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000186 if (getCurFunctionDecl())
187 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattner8f978d52008-01-12 19:32:28 +0000188 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000189 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattner1423ea42008-01-12 18:39:25 +0000190
Chris Lattner8f978d52008-01-12 19:32:28 +0000191 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000192 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000193 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerfa28b302008-01-12 08:14:25 +0000194 return new PreDefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000195}
196
Steve Narofff69936d2007-09-16 03:34:24 +0000197Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerfc62bfd2008-03-01 08:32:21 +0000207
208 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
209
Chris Lattnerc250aae2008-06-07 22:35:38 +0000210 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
211 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000212}
213
Steve Narofff69936d2007-09-16 03:34:24 +0000214Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000218 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000219
Chris Lattner98be4942008-03-05 18:54:05 +0000220 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000221 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner5d661452007-08-26 03:42:43 +0000236 Expr *Res;
237
238 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000239 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000240 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000241 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000242 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000243 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000244 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000245 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000246
247 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
248
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000249 // isExact will be set by GetFloatValue().
250 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000251 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000252 Ty, Tok.getLocation());
253
Chris Lattner5d661452007-08-26 03:42:43 +0000254 } else if (!Literal.isIntegerLiteral()) {
255 return ExprResult(true);
256 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000257 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000258
Neil Boothb9449512007-08-29 22:00:19 +0000259 // long long is a C99 feature.
260 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000261 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000262 Diag(Tok.getLocation(), diag::ext_longlong);
263
Reid Spencer5f016e22007-07-11 17:01:13 +0000264 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000265 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000270 Ty = Context.UnsignedLongLongTy;
271 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000272 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner8cbcb0e2008-05-09 05:59:00 +0000282 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000283 if (!Literal.isLong && !Literal.isLongLong) {
284 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000285 unsigned IntSize = Context.Target.getIntWidth();
286
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000291 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000292 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000293 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000294 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000295 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000296 }
297
298 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000299 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000300 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000306 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000307 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000308 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000309 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000310 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 }
312
313 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000314 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000315 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000321 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000322 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000323 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000324 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000330 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000331 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000332 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000333 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000335
336 if (ResultVal.getBitWidth() != Width)
337 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 }
339
Chris Lattnerf0467b32008-04-02 04:24:33 +0000340 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000341 }
Chris Lattner5d661452007-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;
Reid Spencer5f016e22007-07-11 17:01:13 +0000348}
349
Steve Narofff69936d2007-09-16 03:34:24 +0000350Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000351 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000352 Expr *E = (Expr *)Val;
353 assert((E != 0) && "ActOnParenExpr() missing expr");
354 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofff69936d2007-09-16 03:34:24 +0000378ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner5d794252007-08-24 21:41:10 +0000394QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000395 DefaultFunctionArrayConversion(V);
396
Chris Lattnercc26ed72007-08-26 05:39:26 +0000397 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000398 if (const ComplexType *CT = V->getType()->getAsComplexType())
399 return CT->getElementType();
Chris Lattnercc26ed72007-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 Lattnerdbb36972007-08-24 21:16:53 +0000408}
409
410
Reid Spencer5f016e22007-07-11 17:01:13 +0000411
Steve Narofff69936d2007-09-16 03:34:24 +0000412Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofff69936d2007-09-16 03:34:24 +0000428ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000429 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000430 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000431
432 // Perform default conversions.
433 DefaultFunctionArrayConversion(LHSExp);
434 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000435
Chris Lattner12d9ff62007-07-16 00:14:47 +0000436 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000437
Reid Spencer5f016e22007-07-11 17:01:13 +0000438 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000439 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000440 // in the subscript position. As a result, we need to derive the array base
441 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000442 Expr *BaseExpr, *IndexExpr;
443 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000444 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000445 BaseExpr = LHSExp;
446 IndexExpr = RHSExp;
447 // FIXME: need to deal with const...
448 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000449 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000450 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000451 BaseExpr = RHSExp;
452 IndexExpr = LHSExp;
453 // FIXME: need to deal with const...
454 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000455 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
456 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000457 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000458
459 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +0000460 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
461 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begeman213541a2008-04-18 23:10:10 +0000462 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff608e0ee2007-08-03 22:40:33 +0000463 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000464 // FIXME: need to deal with const...
465 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000467 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
468 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000469 }
470 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000471 if (!IndexExpr->getType()->isIntegerType())
472 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
473 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000474
Chris Lattner12d9ff62007-07-16 00:14:47 +0000475 // 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 Lattnerd805bec2008-04-02 06:59:01 +0000477 // void (*)(int)) and pointers to incomplete types. Functions are not
478 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +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);
Reid Spencer5f016e22007-07-11 17:01:13 +0000485}
486
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000487QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +0000488CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000489 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +0000490 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-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 Naroffe1b31fe2007-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 Begeman213541a2008-04-18 23:10:10 +0000499 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000500 baseType.getAsString(), SourceRange(CompLoc));
501 return QualType();
502 }
Nate Begeman8a997642008-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 Lattner88dca042007-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 Naroffe1b31fe2007-07-27 22:15:19 +0000522
Nate Begeman8a997642008-05-09 06:41:27 +0000523 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-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 Begeman213541a2008-04-18 23:10:10 +0000526 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroffe1b31fe2007-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 Begeman8a997642008-05-09 06:41:27 +0000538 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-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 Begeman213541a2008-04-18 23:10:10 +0000541 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000542 baseType.getAsString(), SourceRange(CompLoc));
543 return QualType();
544 }
Nate Begeman8a997642008-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 Naroffe1b31fe2007-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 Begeman8a997642008-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 Naroffe1b31fe2007-07-27 22:15:19 +0000559 if (CompSize == 1)
560 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000561
Nate Begeman213541a2008-04-18 23:10:10 +0000562 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +0000563 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-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 Naroffbea0b342007-07-29 16:33:31 +0000568 }
569 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000570}
571
Reid Spencer5f016e22007-07-11 17:01:13 +0000572Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000573ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000574 tok::TokenKind OpKind, SourceLocation MemberLoc,
575 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000576 Expr *BaseExpr = static_cast<Expr *>(Base);
577 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +0000578
579 // Perform default conversions.
580 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000581
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000582 QualType BaseType = BaseExpr->getType();
583 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000584
Chris Lattner68a057b2008-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.
Reid Spencer5f016e22007-07-11 17:01:13 +0000587 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000588 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000589 BaseType = PT->getPointeeType();
590 else
591 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
592 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000593 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000594
Chris Lattner68a057b2008-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 Lattnerc8629632007-07-31 19:29:30 +0000597 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-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 Naroffe1b31fe2007-07-27 22:15:19 +0000603 FieldDecl *MemberDecl = RDecl->getMember(&Member);
604 if (!MemberDecl)
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000605 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
606 SourceRange(MemberLoc));
Eli Friedman51019072008-02-06 22:48:16 +0000607
608 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedman64ec0cc2008-02-07 05:24:51 +0000609 // FIXME: Handle address space modifiers
Eli Friedman51019072008-02-06 22:48:16 +0000610 QualType MemberType = MemberDecl->getType();
611 unsigned combinedQualifiers =
Chris Lattnerf46699c2008-02-20 20:55:12 +0000612 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman51019072008-02-06 22:48:16 +0000613 MemberType = MemberType.getQualifiedType(combinedQualifiers);
614
Chris Lattner68a057b2008-07-21 04:36:39 +0000615 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman51019072008-02-06 22:48:16 +0000616 MemberLoc, MemberType);
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000617 }
618
Chris Lattnera38e6b12008-07-21 04:59:05 +0000619 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
620 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +0000621 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
622 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000623 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000624 OpKind == tok::arrow);
Chris Lattner1f719742008-07-21 04:42:08 +0000625 return Diag(OpLoc, diag::err_typecheck_member_reference_ivar,
626 IFTy->getDecl()->getName(), Member.getName(),
627 BaseExpr->getSourceRange(), SourceRange(MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000628 }
629
Chris Lattnera38e6b12008-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.
657 if (const ObjCQualifiedInterfaceType *QIT =
658 dyn_cast<ObjCQualifiedInterfaceType>(IFTy)) {
659 for (unsigned i = 0; i != QIT->getNumProtocols(); ++i)
660 if (ObjCPropertyDecl *PD =
661 QIT->getProtocols(i)->FindPropertyDeclaration(&Member))
662 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc,BaseExpr);
Steve Naroffae784072008-05-30 00:40:33 +0000663 }
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000664 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000665
666 // Handle 'field access' to vectors, such as 'V.xx'.
667 if (BaseType->isExtVectorType() && OpKind == tok::period) {
668 // Component access limited to variables (reject vec4.rg.g).
669 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
670 !isa<ExtVectorElementExpr>(BaseExpr))
671 return Diag(OpLoc, diag::err_ext_vector_component_access,
672 SourceRange(MemberLoc));
673 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
674 if (ret.isNull())
675 return true;
676 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
677 }
678
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000679 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
680 SourceRange(MemberLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000681}
682
Steve Narofff69936d2007-09-16 03:34:24 +0000683/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +0000684/// This provides the location of the left/right parens and a list of comma
685/// locations.
686Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000687ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +0000688 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +0000689 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +0000690 Expr *Fn = static_cast<Expr *>(fn);
691 Expr **Args = reinterpret_cast<Expr**>(args);
692 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +0000693 FunctionDecl *FDecl = NULL;
Chris Lattner04421082008-04-08 04:40:51 +0000694
695 // Promote the function operand.
696 UsualUnaryConversions(Fn);
697
698 // If we're directly calling a function, get the declaration for
699 // that function.
700 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
701 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
702 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
703
Chris Lattner925e60d2007-12-28 05:29:59 +0000704 // Make the call expr early, before semantic checks. This guarantees cleanup
705 // of arguments and function on error.
Chris Lattner8123a952008-04-10 02:22:51 +0000706 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +0000707 Context.BoolTy, RParenLoc));
708
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
710 // type pointer to function".
Chris Lattner925e60d2007-12-28 05:29:59 +0000711 const PointerType *PT = Fn->getType()->getAsPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000712 if (PT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000713 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
714 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner925e60d2007-12-28 05:29:59 +0000715 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
716 if (FuncT == 0)
Chris Lattner74c469f2007-07-21 03:03:59 +0000717 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
718 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner925e60d2007-12-28 05:29:59 +0000719
720 // We know the result type of the call, set it.
721 TheCall->setType(FuncT->getResultType());
Reid Spencer5f016e22007-07-11 17:01:13 +0000722
Chris Lattner925e60d2007-12-28 05:29:59 +0000723 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000724 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
725 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +0000726 unsigned NumArgsInProto = Proto->getNumArgs();
727 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000728
Chris Lattner04421082008-04-08 04:40:51 +0000729 // If too few arguments are available (and we don't have default
730 // arguments for the remaining parameters), don't make the call.
731 if (NumArgs < NumArgsInProto) {
Chris Lattner8123a952008-04-10 02:22:51 +0000732 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner04421082008-04-08 04:40:51 +0000733 // Use default arguments for missing arguments
734 NumArgsToCheck = NumArgsInProto;
Chris Lattner8123a952008-04-10 02:22:51 +0000735 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner04421082008-04-08 04:40:51 +0000736 } else
737 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
738 Fn->getSourceRange());
739 }
740
Chris Lattner925e60d2007-12-28 05:29:59 +0000741 // If too many are passed and not variadic, error on the extras and drop
742 // them.
743 if (NumArgs > NumArgsInProto) {
744 if (!Proto->isVariadic()) {
Chris Lattnerd472b312007-07-21 03:09:58 +0000745 Diag(Args[NumArgsInProto]->getLocStart(),
Chris Lattner74c469f2007-07-21 03:03:59 +0000746 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattnerd472b312007-07-21 03:09:58 +0000747 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner925e60d2007-12-28 05:29:59 +0000748 Args[NumArgs-1]->getLocEnd()));
749 // This deletes the extra arguments.
750 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 }
752 NumArgsToCheck = NumArgsInProto;
753 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000754
Reid Spencer5f016e22007-07-11 17:01:13 +0000755 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +0000756 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner5cf216b2008-01-04 18:04:52 +0000757 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner04421082008-04-08 04:40:51 +0000758
759 Expr *Arg;
760 if (i < NumArgs)
761 Arg = Args[i];
762 else
763 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner5cf216b2008-01-04 18:04:52 +0000764 QualType ArgType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +0000765
Chris Lattner925e60d2007-12-28 05:29:59 +0000766 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000767 AssignConvertType ConvTy =
768 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner925e60d2007-12-28 05:29:59 +0000769 TheCall->setArg(i, Arg);
770
Chris Lattner5cf216b2008-01-04 18:04:52 +0000771 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
772 ArgType, Arg, "passing"))
773 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000774 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000775
776 // If this is a variadic call, handle args passed through "...".
777 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +0000778 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-12-28 05:29:59 +0000779 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
780 Expr *Arg = Args[i];
781 DefaultArgumentPromotion(Arg);
782 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +0000783 }
Steve Naroffb291ab62007-08-28 23:30:39 +0000784 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000785 } else {
786 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
787
Steve Naroffb291ab62007-08-28 23:30:39 +0000788 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +0000789 for (unsigned i = 0; i != NumArgs; i++) {
790 Expr *Arg = Args[i];
791 DefaultArgumentPromotion(Arg);
792 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +0000793 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000794 }
Chris Lattner925e60d2007-12-28 05:29:59 +0000795
Chris Lattner59907c42007-08-10 20:18:51 +0000796 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +0000797 if (FDecl)
798 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +0000799
Chris Lattner925e60d2007-12-28 05:29:59 +0000800 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +0000801}
802
803Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000804ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +0000805 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +0000806 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +0000807 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +0000808 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +0000809 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +0000810 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +0000811
Eli Friedman6223c222008-05-20 05:22:08 +0000812 if (literalType->isArrayType()) {
813 if (literalType->getAsVariableArrayType())
814 return Diag(LParenLoc,
815 diag::err_variable_object_no_init,
816 SourceRange(LParenLoc,
817 literalExpr->getSourceRange().getEnd()));
818 } else if (literalType->isIncompleteType()) {
819 return Diag(LParenLoc,
820 diag::err_typecheck_decl_incomplete_type,
821 literalType.getAsString(),
822 SourceRange(LParenLoc,
823 literalExpr->getSourceRange().getEnd()));
824 }
825
Steve Naroffd0091aa2008-01-10 22:15:12 +0000826 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff58d18212008-01-09 20:58:06 +0000827 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +0000828
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000829 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffe9b12192008-01-14 18:19:28 +0000830 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +0000831 if (CheckForConstantInitializer(literalExpr, literalType))
832 return true;
833 }
Steve Naroffe9b12192008-01-14 18:19:28 +0000834 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +0000835}
836
837Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000838ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000839 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +0000840 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000841
Steve Naroff08d92e42007-09-15 18:49:24 +0000842 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +0000843 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +0000844
Chris Lattnerf0467b32008-04-02 04:24:33 +0000845 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
846 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
847 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +0000848}
849
Chris Lattnerfe23e212007-12-20 00:44:32 +0000850bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +0000851 assert(VectorTy->isVectorType() && "Not a vector type!");
852
853 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +0000854 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +0000855 return Diag(R.getBegin(),
856 Ty->isVectorType() ?
857 diag::err_invalid_conversion_between_vectors :
858 diag::err_invalid_conversion_between_vector_and_integer,
859 VectorTy.getAsString().c_str(),
860 Ty.getAsString().c_str(), R);
861 } else
862 return Diag(R.getBegin(),
863 diag::err_invalid_conversion_between_vector_and_scalar,
864 VectorTy.getAsString().c_str(),
865 Ty.getAsString().c_str(), R);
866
867 return false;
868}
869
Steve Naroff4aa88f82007-07-19 01:06:55 +0000870Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000871ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +0000873 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +0000874
875 Expr *castExpr = static_cast<Expr*>(Op);
876 QualType castType = QualType::getFromOpaquePtr(Ty);
877
Steve Naroff711602b2007-08-31 00:32:44 +0000878 UsualUnaryConversions(castExpr);
879
Chris Lattner75af4802007-07-18 16:00:06 +0000880 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
881 // type needs to be scalar.
Chris Lattner3da2db42007-10-29 04:26:44 +0000882 if (!castType->isVoidType()) { // Cast to void allows any expr type.
Steve Naroff63564b82008-06-03 12:56:35 +0000883 if (!castType->isScalarType() && !castType->isVectorType()) {
884 // GCC struct/union extension.
885 if (castType == castExpr->getType() &&
Steve Naroff0326e042008-06-03 13:21:30 +0000886 castType->isStructureType() || castType->isUnionType()) {
887 Diag(LParenLoc, diag::ext_typecheck_cast_nonscalar,
888 SourceRange(LParenLoc, RParenLoc));
889 return new CastExpr(castType, castExpr, LParenLoc);
890 } else
Steve Naroff63564b82008-06-03 12:56:35 +0000891 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
892 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
893 }
Steve Naroff9412d682008-01-24 22:55:05 +0000894 if (!castExpr->getType()->isScalarType() &&
895 !castExpr->getType()->isVectorType())
Chris Lattner3da2db42007-10-29 04:26:44 +0000896 return Diag(castExpr->getLocStart(),
897 diag::err_typecheck_expect_scalar_operand,
898 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssona64db8f2007-11-27 05:51:55 +0000899
900 if (castExpr->getType()->isVectorType()) {
901 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
902 castExpr->getType(), castType))
903 return true;
904 } else if (castType->isVectorType()) {
905 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
906 castType, castExpr->getType()))
907 return true;
Chris Lattner3da2db42007-10-29 04:26:44 +0000908 }
Steve Naroff16beff82007-07-16 23:25:18 +0000909 }
910 return new CastExpr(castType, castExpr, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000911}
912
Chris Lattnera21ddb32007-11-26 01:40:58 +0000913/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
914/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +0000915inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +0000916 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +0000917 UsualUnaryConversions(cond);
918 UsualUnaryConversions(lex);
919 UsualUnaryConversions(rex);
920 QualType condT = cond->getType();
921 QualType lexT = lex->getType();
922 QualType rexT = rex->getType();
923
Reid Spencer5f016e22007-07-11 17:01:13 +0000924 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +0000925 if (!condT->isScalarType()) { // C99 6.5.15p2
926 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
927 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +0000928 return QualType();
929 }
Chris Lattner70d67a92008-01-06 22:42:25 +0000930
931 // Now check the two expressions.
932
933 // If both operands have arithmetic type, do the usual arithmetic conversions
934 // to find a common type: C99 6.5.15p3,5.
935 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +0000936 UsualArithmeticConversions(lex, rex);
937 return lex->getType();
938 }
Chris Lattner70d67a92008-01-06 22:42:25 +0000939
940 // If both operands are the same structure or union type, the result is that
941 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000942 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +0000943 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +0000944 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +0000945 // "If both the operands have structure or union type, the result has
946 // that type." This implies that CV qualifiers are dropped.
947 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000948 }
Chris Lattner70d67a92008-01-06 22:42:25 +0000949
950 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +0000951 // The following || allows only one side to be void (a GCC-ism).
952 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +0000953 if (!lexT->isVoidType())
Steve Naroffe701c0a2008-05-12 21:44:38 +0000954 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
955 rex->getSourceRange());
956 if (!rexT->isVoidType())
957 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopesd8de7252008-06-04 19:14:12 +0000958 lex->getSourceRange());
Eli Friedman0e724012008-06-04 19:47:51 +0000959 ImpCastExprToType(lex, Context.VoidTy);
960 ImpCastExprToType(rex, Context.VoidTy);
961 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +0000962 }
Steve Naroffb6d54e52008-01-08 01:11:38 +0000963 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
964 // the type of the other operand."
965 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +0000966 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +0000967 return lexT;
968 }
969 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +0000970 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +0000971 return rexT;
972 }
Chris Lattnerbd57d362008-01-06 22:50:31 +0000973 // Handle the case where both operands are pointers before we handle null
974 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000975 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
976 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
977 // get the "pointed to" types
978 QualType lhptee = LHSPT->getPointeeType();
979 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000980
Chris Lattner2dcb6bb2007-07-31 21:27:01 +0000981 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
982 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +0000983 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +0000984 // Figure out necessary qualifiers (C99 6.5.15p6)
985 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +0000986 QualType destType = Context.getPointerType(destPointee);
987 ImpCastExprToType(lex, destType); // add qualifiers if necessary
988 ImpCastExprToType(rex, destType); // promote to void*
989 return destType;
990 }
Chris Lattnerd805bec2008-04-02 06:59:01 +0000991 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +0000992 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +0000993 QualType destType = Context.getPointerType(destPointee);
994 ImpCastExprToType(lex, destType); // add qualifiers if necessary
995 ImpCastExprToType(rex, destType); // promote to void*
996 return destType;
997 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000998
Steve Naroffec0550f2007-10-15 20:41:53 +0000999 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1000 rhptee.getUnqualifiedType())) {
Steve Naroffc0ff1ca2008-02-01 22:44:48 +00001001 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001002 lexT.getAsString(), rexT.getAsString(),
1003 lex->getSourceRange(), rex->getSourceRange());
Eli Friedmanb1284ac2008-01-30 17:02:03 +00001004 // In this situation, we assume void* type. No especially good
1005 // reason, but this is what gcc does, and we do have to pick
1006 // to get a consistent AST.
1007 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
1008 ImpCastExprToType(lex, voidPtrTy);
1009 ImpCastExprToType(rex, voidPtrTy);
1010 return voidPtrTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001011 }
1012 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001013 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1014 // differently qualified versions of compatible types, the result type is
1015 // a pointer to an appropriately qualified version of the *composite*
1016 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00001017 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00001018 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00001019 QualType compositeType = lexT;
1020 ImpCastExprToType(lex, compositeType);
1021 ImpCastExprToType(rex, compositeType);
1022 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001023 }
1024 }
Steve Naroffaa73eec2008-05-31 22:33:45 +00001025 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1026 // evaluates to "struct objc_object *" (and is handled above when comparing
1027 // id with statically typed objects). FIXME: Do we need an ImpCastExprToType?
1028 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1029 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true))
1030 return Context.getObjCIdType();
1031 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001032 // Otherwise, the operands are not compatible.
Reid Spencer5f016e22007-07-11 17:01:13 +00001033 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +00001034 lexT.getAsString(), rexT.getAsString(),
1035 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001036 return QualType();
1037}
1038
Steve Narofff69936d2007-09-16 03:34:24 +00001039/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00001040/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00001041Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001042 SourceLocation ColonLoc,
1043 ExprTy *Cond, ExprTy *LHS,
1044 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00001045 Expr *CondExpr = (Expr *) Cond;
1046 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001047
1048 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1049 // was the condition.
1050 bool isLHSNull = LHSExpr == 0;
1051 if (isLHSNull)
1052 LHSExpr = CondExpr;
1053
Chris Lattner26824902007-07-16 21:39:03 +00001054 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1055 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001056 if (result.isNull())
1057 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001058 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1059 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001060}
1061
Steve Naroffb291ab62007-08-28 23:30:39 +00001062/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Steve Naroffb3c2b882008-01-29 02:42:22 +00001063/// do not have a prototype. Arguments that have type float are promoted to
1064/// double. All other argument types are converted by UsualUnaryConversions().
Chris Lattner925e60d2007-12-28 05:29:59 +00001065void Sema::DefaultArgumentPromotion(Expr *&Expr) {
1066 QualType Ty = Expr->getType();
1067 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffb291ab62007-08-28 23:30:39 +00001068
Chris Lattner3cc5e5b2008-06-27 22:48:56 +00001069 // If this is a 'float' (CVR qualified or typedef) promote to double.
1070 if (const BuiltinType *BT = Ty->getAsBuiltinType())
1071 if (BT->getKind() == BuiltinType::Float)
1072 return ImpCastExprToType(Expr, Context.DoubleTy);
1073
1074 UsualUnaryConversions(Expr);
Steve Naroffb291ab62007-08-28 23:30:39 +00001075}
1076
Steve Narofffa2eaab2007-07-15 02:02:06 +00001077/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Chris Lattnerf0467b32008-04-02 04:24:33 +00001078void Sema::DefaultFunctionArrayConversion(Expr *&E) {
1079 QualType Ty = E->getType();
1080 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
Bill Wendling08ad47c2007-07-17 03:52:31 +00001081
Chris Lattnerf0467b32008-04-02 04:24:33 +00001082 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
Chris Lattner423a3c92008-04-02 17:45:06 +00001083 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
Chris Lattnerf0467b32008-04-02 04:24:33 +00001084 Ty = E->getType();
Bill Wendlingea5e79f2007-07-17 04:16:47 +00001085 }
Chris Lattnerf0467b32008-04-02 04:24:33 +00001086 if (Ty->isFunctionType())
1087 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattnere6327742008-04-02 05:18:44 +00001088 else if (Ty->isArrayType())
1089 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
Reid Spencer5f016e22007-07-11 17:01:13 +00001090}
1091
Nate Begemane2ce1d92008-01-17 17:46:27 +00001092/// UsualUnaryConversions - Performs various conversions that are common to most
Reid Spencer5f016e22007-07-11 17:01:13 +00001093/// operators (C99 6.3). The conversions of array and function types are
1094/// sometimes surpressed. For example, the array->pointer conversion doesn't
1095/// apply if the array is an argument to the sizeof or address (&) operators.
1096/// In these instances, this routine should *not* be called.
Chris Lattner925e60d2007-12-28 05:29:59 +00001097Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
1098 QualType Ty = Expr->getType();
1099 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001100
Chris Lattner925e60d2007-12-28 05:29:59 +00001101 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
Chris Lattner423a3c92008-04-02 17:45:06 +00001102 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
Chris Lattner925e60d2007-12-28 05:29:59 +00001103 Ty = Expr->getType();
Bill Wendlingea5e79f2007-07-17 04:16:47 +00001104 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001105 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
Chris Lattner1e0a3902008-01-16 19:17:22 +00001106 ImpCastExprToType(Expr, Context.IntTy);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001107 else
Chris Lattner925e60d2007-12-28 05:29:59 +00001108 DefaultFunctionArrayConversion(Expr);
1109
1110 return Expr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001111}
1112
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001113/// UsualArithmeticConversions - Performs various conversions that are common to
Reid Spencer5f016e22007-07-11 17:01:13 +00001114/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1115/// routine returns the first non-arithmetic type found. The client is
1116/// responsible for emitting appropriate error diagnostics.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001117/// FIXME: verify the conversion rules for "complex int" are consistent with
1118/// GCC.
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001119QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
1120 bool isCompAssign) {
Steve Naroff8702a0f2007-08-25 19:54:59 +00001121 if (!isCompAssign) {
1122 UsualUnaryConversions(lhsExpr);
1123 UsualUnaryConversions(rhsExpr);
1124 }
Steve Naroff3187e202007-10-18 18:55:53 +00001125 // For conversion purposes, we ignore any qualifiers.
1126 // For example, "const float" and "float" are equivalent.
Steve Narofff68a63f2007-11-10 19:45:54 +00001127 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
1128 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001129
1130 // If both types are identical, no conversion is needed.
Steve Naroff3187e202007-10-18 18:55:53 +00001131 if (lhs == rhs)
1132 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001133
1134 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1135 // The caller can deal with this (e.g. pointer + int).
Steve Naroffa4332e22007-07-17 00:58:39 +00001136 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001137 return lhs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001138
1139 // At this point, we have two different arithmetic types.
1140
1141 // Handle complex types first (C99 6.3.1.8p1).
1142 if (lhs->isComplexType() || rhs->isComplexType()) {
Steve Naroff02f62a92008-01-15 19:36:10 +00001143 // if we have an integer operand, the result is the complex type.
Steve Naroffdfb9bbb2008-01-15 22:21:49 +00001144 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00001145 // convert the rhs to the lhs complex type.
Chris Lattner1e0a3902008-01-16 19:17:22 +00001146 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001147 return lhs;
Steve Naroff02f62a92008-01-15 19:36:10 +00001148 }
Steve Naroffdfb9bbb2008-01-15 22:21:49 +00001149 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00001150 // convert the lhs to the rhs complex type.
Chris Lattner1e0a3902008-01-16 19:17:22 +00001151 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001152 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001153 }
Steve Narofff1448a02007-08-27 01:27:54 +00001154 // This handles complex/complex, complex/float, or float/complex.
1155 // When both operands are complex, the shorter operand is converted to the
1156 // type of the longer, and that is the type of the result. This corresponds
1157 // to what is done when combining two real floating-point operands.
1158 // The fun begins when size promotion occur across type domains.
1159 // From H&S 6.3.4: When one operand is complex and the other is a real
1160 // floating-point type, the less precise type is converted, within it's
1161 // real or complex domain, to the precision of the other type. For example,
1162 // when combining a "long double" with a "double _Complex", the
1163 // "double _Complex" is promoted to "long double _Complex".
Chris Lattnera75cea32008-04-06 23:38:49 +00001164 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Narofffb0d4962007-08-27 15:30:22 +00001165
1166 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff55fe4552007-08-27 21:32:55 +00001167 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
1168 if (!isCompAssign)
Chris Lattner1e0a3902008-01-16 19:17:22 +00001169 ImpCastExprToType(rhsExpr, rhs);
Steve Naroff55fe4552007-08-27 21:32:55 +00001170 } else if (result < 0) { // The right side is bigger, convert lhs.
1171 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
1172 if (!isCompAssign)
Chris Lattner1e0a3902008-01-16 19:17:22 +00001173 ImpCastExprToType(lhsExpr, lhs);
Steve Naroff55fe4552007-08-27 21:32:55 +00001174 }
1175 // At this point, lhs and rhs have the same rank/size. Now, make sure the
1176 // domains match. This is a requirement for our implementation, C99
1177 // does not require this promotion.
1178 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1179 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff29960362007-08-27 21:43:43 +00001180 if (!isCompAssign)
Chris Lattner1e0a3902008-01-16 19:17:22 +00001181 ImpCastExprToType(lhsExpr, rhs);
Steve Naroff29960362007-08-27 21:43:43 +00001182 return rhs;
Steve Naroff55fe4552007-08-27 21:32:55 +00001183 } else { // handle "_Complex double, double".
Steve Naroff29960362007-08-27 21:43:43 +00001184 if (!isCompAssign)
Chris Lattner1e0a3902008-01-16 19:17:22 +00001185 ImpCastExprToType(rhsExpr, lhs);
Steve Naroff29960362007-08-27 21:43:43 +00001186 return lhs;
Steve Naroff55fe4552007-08-27 21:32:55 +00001187 }
Steve Naroffa4332e22007-07-17 00:58:39 +00001188 }
Steve Naroff29960362007-08-27 21:43:43 +00001189 return lhs; // The domain/size match exactly.
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 // Now handle "real" floating types (i.e. float, double, long double).
1192 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1193 // if we have an integer operand, the result is the real floating type.
Steve Naroffdfb9bbb2008-01-15 22:21:49 +00001194 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00001195 // convert rhs to the lhs floating point type.
Chris Lattner1e0a3902008-01-16 19:17:22 +00001196 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001197 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001198 }
Steve Naroffdfb9bbb2008-01-15 22:21:49 +00001199 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00001200 // convert lhs to the rhs floating point type.
Chris Lattner1e0a3902008-01-16 19:17:22 +00001201 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001202 return rhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001203 }
Steve Narofffa2eaab2007-07-15 02:02:06 +00001204 // We have two real floating types, float/complex combos were handled above.
1205 // Convert the smaller operand to the bigger result.
Chris Lattnera75cea32008-04-06 23:38:49 +00001206 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Narofffb0d4962007-08-27 15:30:22 +00001207
1208 if (result > 0) { // convert the rhs
Chris Lattner1e0a3902008-01-16 19:17:22 +00001209 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001210 return lhs;
Steve Naroffa4332e22007-07-17 00:58:39 +00001211 }
Steve Narofffb0d4962007-08-27 15:30:22 +00001212 if (result < 0) { // convert the lhs
Chris Lattner1e0a3902008-01-16 19:17:22 +00001213 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Narofffb0d4962007-08-27 15:30:22 +00001214 return rhs;
1215 }
1216 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Reid Spencer5f016e22007-07-11 17:01:13 +00001217 }
Steve Naroff02f62a92008-01-15 19:36:10 +00001218 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
1219 // Handle GCC complex int extension.
Steve Naroff02f62a92008-01-15 19:36:10 +00001220 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00001221 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
Steve Naroff02f62a92008-01-15 19:36:10 +00001222
Eli Friedman8e54ad02008-02-08 01:19:44 +00001223 if (lhsComplexInt && rhsComplexInt) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00001224 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
1225 rhsComplexInt->getElementType()) >= 0) {
Eli Friedman8c4e5db2008-02-08 01:24:30 +00001226 // convert the rhs
1227 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1228 return lhs;
Eli Friedman8e54ad02008-02-08 01:19:44 +00001229 }
1230 if (!isCompAssign)
Eli Friedman8c4e5db2008-02-08 01:24:30 +00001231 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Eli Friedman8e54ad02008-02-08 01:19:44 +00001232 return rhs;
1233 } else if (lhsComplexInt && rhs->isIntegerType()) {
1234 // convert the rhs to the lhs complex type.
1235 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1236 return lhs;
1237 } else if (rhsComplexInt && lhs->isIntegerType()) {
1238 // convert the lhs to the rhs complex type.
1239 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1240 return rhs;
1241 }
Steve Naroff02f62a92008-01-15 19:36:10 +00001242 }
Steve Narofffa2eaab2007-07-15 02:02:06 +00001243 // Finally, we have two differing integer types.
Eli Friedmanad74a752008-06-28 06:23:08 +00001244 // The rules for this case are in C99 6.3.1.8
1245 int compare = Context.getIntegerTypeOrder(lhs, rhs);
1246 bool lhsSigned = lhs->isSignedIntegerType(),
1247 rhsSigned = rhs->isSignedIntegerType();
1248 QualType destType;
1249 if (lhsSigned == rhsSigned) {
1250 // Same signedness; use the higher-ranked type
1251 destType = compare >= 0 ? lhs : rhs;
1252 } else if (compare != (lhsSigned ? 1 : -1)) {
1253 // The unsigned type has greater than or equal rank to the
1254 // signed type, so use the unsigned type
1255 destType = lhsSigned ? rhs : lhs;
1256 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
1257 // The two types are different widths; if we are here, that
1258 // means the signed type is larger than the unsigned type, so
1259 // use the signed type.
1260 destType = lhsSigned ? lhs : rhs;
1261 } else {
1262 // The signed type is higher-ranked than the unsigned type,
1263 // but isn't actually any bigger (like unsigned int and long
1264 // on most 32-bit systems). Use the unsigned type corresponding
1265 // to the signed type.
1266 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
Steve Naroffa4332e22007-07-17 00:58:39 +00001267 }
Eli Friedmanad74a752008-06-28 06:23:08 +00001268 if (!isCompAssign) {
1269 ImpCastExprToType(lhsExpr, destType);
1270 ImpCastExprToType(rhsExpr, destType);
1271 }
1272 return destType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001273}
1274
1275// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1276// being closely modeled after the C99 spec:-). The odd characteristic of this
1277// routine is it effectively iqnores the qualifiers on the top level pointee.
1278// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1279// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001280Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001281Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1282 QualType lhptee, rhptee;
1283
1284 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001285 lhptee = lhsType->getAsPointerType()->getPointeeType();
1286 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001287
1288 // make sure we operate on the canonical type
1289 lhptee = lhptee.getCanonicalType();
1290 rhptee = rhptee.getCanonicalType();
1291
Chris Lattner5cf216b2008-01-04 18:04:52 +00001292 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001293
1294 // C99 6.5.16.1p1: This following citation is common to constraints
1295 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1296 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00001297 // FIXME: Handle ASQualType
1298 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1299 rhptee.getCVRQualifiers())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001300 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001301
1302 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1303 // incomplete type and the other is a pointer to a qualified or unqualified
1304 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001305 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001306 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001307 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001308
1309 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001310 assert(rhptee->isFunctionType());
1311 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001312 }
1313
1314 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001315 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001316 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001317
1318 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001319 assert(lhptee->isFunctionType());
1320 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001321 }
1322
Reid Spencer5f016e22007-07-11 17:01:13 +00001323 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1324 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001325 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1326 rhptee.getUnqualifiedType()))
1327 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00001328 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001329}
1330
1331/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1332/// has code to accommodate several GCC extensions when type checking
1333/// pointers. Here are some objectionable examples that GCC considers warnings:
1334///
1335/// int a, *pint;
1336/// short *pshort;
1337/// struct foo *pfoo;
1338///
1339/// pint = pshort; // warning: assignment from incompatible pointer type
1340/// a = pint; // warning: assignment makes integer from pointer without a cast
1341/// pint = a; // warning: assignment makes pointer from integer without a cast
1342/// pint = pfoo; // warning: assignment from incompatible pointer type
1343///
1344/// As a result, the code for dealing with pointers is more complex than the
1345/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00001346///
Chris Lattner5cf216b2008-01-04 18:04:52 +00001347Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001348Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00001349 // Get canonical types. We're not formatting these types, just comparing
1350 // them.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001351 lhsType = lhsType.getCanonicalType().getUnqualifiedType();
1352 rhsType = rhsType.getCanonicalType().getUnqualifiedType();
1353
1354 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00001355 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00001356
Anders Carlsson793680e2007-10-12 23:56:29 +00001357 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattner8f8fc7b2008-04-07 06:52:53 +00001358 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001359 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001360 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001361 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001362
Chris Lattnereca7be62008-04-07 05:30:13 +00001363 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1364 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001365 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00001366 // Relax integer conversions like we do for pointers below.
1367 if (rhsType->isIntegerType())
1368 return IntToPointer;
1369 if (lhsType->isIntegerType())
1370 return PointerToInt;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001371 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001372 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00001373
Nate Begemanbe2341d2008-07-14 18:02:46 +00001374 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001375 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00001376 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1377 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00001378 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001379
Nate Begemanbe2341d2008-07-14 18:02:46 +00001380 // If we are allowing lax vector conversions, and LHS and RHS are both
1381 // vectors, the total size only needs to be the same. This is a bitcast;
1382 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00001383 if (getLangOptions().LaxVectorConversions &&
1384 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001385 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1386 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00001387 }
1388 return Incompatible;
1389 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001390
Chris Lattnere8b3e962008-01-04 23:32:24 +00001391 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001393
Chris Lattner78eca282008-04-07 06:49:41 +00001394 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001395 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001396 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001397
Chris Lattner78eca282008-04-07 06:49:41 +00001398 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattnerfc144e22008-01-04 23:18:45 +00001400 return Incompatible;
1401 }
1402
Chris Lattner78eca282008-04-07 06:49:41 +00001403 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001404 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001405 if (lhsType == Context.BoolTy)
1406 return Compatible;
1407
1408 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001409 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00001410
Chris Lattner78eca282008-04-07 06:49:41 +00001411 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattnerfc144e22008-01-04 23:18:45 +00001413 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001414 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001415
Chris Lattnerfc144e22008-01-04 23:18:45 +00001416 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00001417 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001419 }
1420 return Incompatible;
1421}
1422
Chris Lattner5cf216b2008-01-04 18:04:52 +00001423Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001424Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroff529a4ad2007-11-27 17:58:44 +00001425 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1426 // a null pointer constant.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001427 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00001428 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001429 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00001430 return Compatible;
1431 }
Chris Lattner943140e2007-10-16 02:55:40 +00001432 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001433 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001434 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001435 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001436 //
1437 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1438 // are better understood.
1439 if (!lhsType->isReferenceType())
1440 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001441
Chris Lattner5cf216b2008-01-04 18:04:52 +00001442 Sema::AssignConvertType result =
1443 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00001444
1445 // C99 6.5.16.1p2: The value of the right operand is converted to the
1446 // type of the assignment expression.
1447 if (rExpr->getType() != lhsType)
Chris Lattner1e0a3902008-01-16 19:17:22 +00001448 ImpCastExprToType(rExpr, lhsType);
Steve Narofff1120de2007-08-24 22:33:52 +00001449 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001450}
1451
Chris Lattner5cf216b2008-01-04 18:04:52 +00001452Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001453Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1454 return CheckAssignmentConstraints(lhsType, rhsType);
1455}
1456
Chris Lattnerca5eede2007-12-12 05:47:28 +00001457QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001458 Diag(loc, diag::err_typecheck_invalid_operands,
1459 lex->getType().getAsString(), rex->getType().getAsString(),
1460 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerca5eede2007-12-12 05:47:28 +00001461 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001462}
1463
Steve Naroff49b45262007-07-13 16:58:59 +00001464inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1465 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00001466 // For conversion purposes, we ignore any qualifiers.
1467 // For example, "const float" and "float" are equivalent.
1468 QualType lhsType = lex->getType().getCanonicalType().getUnqualifiedType();
1469 QualType rhsType = rex->getType().getCanonicalType().getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001470
Nate Begemanbe2341d2008-07-14 18:02:46 +00001471 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00001472 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001473 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00001474
Nate Begemanbe2341d2008-07-14 18:02:46 +00001475 // Handle the case of a vector & extvector type of the same size and element
1476 // type. It would be nice if we only had one vector type someday.
1477 if (getLangOptions().LaxVectorConversions)
1478 if (const VectorType *LV = lhsType->getAsVectorType())
1479 if (const VectorType *RV = rhsType->getAsVectorType())
1480 if (LV->getElementType() == RV->getElementType() &&
1481 LV->getNumElements() == RV->getNumElements())
1482 return lhsType->isExtVectorType() ? lhsType : rhsType;
1483
1484 // If the lhs is an extended vector and the rhs is a scalar of the same type
1485 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001486 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001487 QualType eltType = V->getElementType();
1488
1489 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1490 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1491 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001492 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001493 return lhsType;
1494 }
1495 }
1496
Nate Begemanbe2341d2008-07-14 18:02:46 +00001497 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00001498 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001499 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001500 QualType eltType = V->getElementType();
1501
1502 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1503 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1504 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001505 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001506 return rhsType;
1507 }
1508 }
1509
Reid Spencer5f016e22007-07-11 17:01:13 +00001510 // You cannot convert between vector values of different size.
1511 Diag(loc, diag::err_typecheck_vector_not_convertable,
1512 lex->getType().getAsString(), rex->getType().getAsString(),
1513 lex->getSourceRange(), rex->getSourceRange());
1514 return QualType();
1515}
1516
1517inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001518 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001519{
Steve Naroff90045e82007-07-13 23:32:42 +00001520 QualType lhsType = lex->getType(), rhsType = rex->getType();
1521
1522 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001524
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001525 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001526
Steve Naroffa4332e22007-07-17 00:58:39 +00001527 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001528 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001529 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001530}
1531
1532inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001533 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001534{
Steve Naroff90045e82007-07-13 23:32:42 +00001535 QualType lhsType = lex->getType(), rhsType = rex->getType();
1536
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001537 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001538
Steve Naroffa4332e22007-07-17 00:58:39 +00001539 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001540 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001541 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001542}
1543
1544inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001545 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001546{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001547 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001548 return CheckVectorOperands(loc, lex, rex);
1549
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001550 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00001551
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001553 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001554 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001555
Eli Friedmand72d16e2008-05-18 18:08:51 +00001556 // Put any potential pointer into PExp
1557 Expr* PExp = lex, *IExp = rex;
1558 if (IExp->getType()->isPointerType())
1559 std::swap(PExp, IExp);
1560
1561 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1562 if (IExp->getType()->isIntegerType()) {
1563 // Check for arithmetic on pointers to incomplete types
1564 if (!PTy->getPointeeType()->isObjectType()) {
1565 if (PTy->getPointeeType()->isVoidType()) {
1566 Diag(loc, diag::ext_gnu_void_ptr,
1567 lex->getSourceRange(), rex->getSourceRange());
1568 } else {
1569 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1570 lex->getType().getAsString(), lex->getSourceRange());
1571 return QualType();
1572 }
1573 }
1574 return PExp->getType();
1575 }
1576 }
1577
Chris Lattnerca5eede2007-12-12 05:47:28 +00001578 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001579}
1580
Chris Lattnereca7be62008-04-07 05:30:13 +00001581// C99 6.5.6
1582QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1583 SourceLocation loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00001584 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001586
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001587 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001588
Chris Lattner6e4ab612007-12-09 21:53:25 +00001589 // Enforce type constraints: C99 6.5.6p3.
1590
1591 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001592 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001593 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001594
1595 // Either ptr - int or ptr - ptr.
1596 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00001597 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00001598
Chris Lattner6e4ab612007-12-09 21:53:25 +00001599 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00001600 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001601 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001602 if (lpointee->isVoidType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001603 Diag(loc, diag::ext_gnu_void_ptr,
1604 lex->getSourceRange(), rex->getSourceRange());
1605 } else {
1606 Diag(loc, diag::err_typecheck_sub_ptr_object,
1607 lex->getType().getAsString(), lex->getSourceRange());
1608 return QualType();
1609 }
1610 }
1611
1612 // The result type of a pointer-int computation is the pointer type.
1613 if (rex->getType()->isIntegerType())
1614 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001615
Chris Lattner6e4ab612007-12-09 21:53:25 +00001616 // Handle pointer-pointer subtractions.
1617 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00001618 QualType rpointee = RHSPTy->getPointeeType();
1619
Chris Lattner6e4ab612007-12-09 21:53:25 +00001620 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00001621 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001622 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001623 if (rpointee->isVoidType()) {
1624 if (!lpointee->isVoidType())
Chris Lattner6e4ab612007-12-09 21:53:25 +00001625 Diag(loc, diag::ext_gnu_void_ptr,
1626 lex->getSourceRange(), rex->getSourceRange());
1627 } else {
1628 Diag(loc, diag::err_typecheck_sub_ptr_object,
1629 rex->getType().getAsString(), rex->getSourceRange());
1630 return QualType();
1631 }
1632 }
1633
1634 // Pointee types must be compatible.
Steve Naroff2565eef2008-01-29 18:58:14 +00001635 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1636 rpointee.getUnqualifiedType())) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001637 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1638 lex->getType().getAsString(), rex->getType().getAsString(),
1639 lex->getSourceRange(), rex->getSourceRange());
1640 return QualType();
1641 }
1642
1643 return Context.getPointerDiffType();
1644 }
1645 }
1646
Chris Lattnerca5eede2007-12-12 05:47:28 +00001647 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001648}
1649
Chris Lattnereca7be62008-04-07 05:30:13 +00001650// C99 6.5.7
1651QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1652 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00001653 // C99 6.5.7p2: Each of the operands shall have integer type.
1654 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1655 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001656
Chris Lattnerca5eede2007-12-12 05:47:28 +00001657 // Shifts don't perform usual arithmetic conversions, they just do integer
1658 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00001659 if (!isCompAssign)
1660 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00001661 UsualUnaryConversions(rex);
1662
1663 // "The type of the result is that of the promoted left operand."
1664 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001665}
1666
Chris Lattnereca7be62008-04-07 05:30:13 +00001667// C99 6.5.8
1668QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1669 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001670 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1671 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1672
Chris Lattnera5937dd2007-08-26 01:18:55 +00001673 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00001674 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1675 UsualArithmeticConversions(lex, rex);
1676 else {
1677 UsualUnaryConversions(lex);
1678 UsualUnaryConversions(rex);
1679 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001680 QualType lType = lex->getType();
1681 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001682
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001683 // For non-floating point types, check for self-comparisons of the form
1684 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1685 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001686 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001687 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1688 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00001689 if (DRL->getDecl() == DRR->getDecl())
1690 Diag(loc, diag::warn_selfcomparison);
1691 }
1692
Chris Lattnera5937dd2007-08-26 01:18:55 +00001693 if (isRelational) {
1694 if (lType->isRealType() && rType->isRealType())
1695 return Context.IntTy;
1696 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001697 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00001698 if (lType->isFloatingType()) {
1699 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001700 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00001701 }
1702
Chris Lattnera5937dd2007-08-26 01:18:55 +00001703 if (lType->isArithmeticType() && rType->isArithmeticType())
1704 return Context.IntTy;
1705 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001706
Chris Lattnerd28f8152007-08-26 01:10:14 +00001707 bool LHSIsNull = lex->isNullPointerConstant(Context);
1708 bool RHSIsNull = rex->isNullPointerConstant(Context);
1709
Chris Lattnera5937dd2007-08-26 01:18:55 +00001710 // All of the following pointer related warnings are GCC extensions, except
1711 // when handling null pointer constants. One day, we can consider making them
1712 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00001713 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00001714 QualType LCanPointeeTy =
1715 lType->getAsPointerType()->getPointeeType().getCanonicalType();
1716 QualType RCanPointeeTy =
1717 rType->getAsPointerType()->getPointeeType().getCanonicalType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00001718
Steve Naroff66296cb2007-11-13 14:57:38 +00001719 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00001720 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1721 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
1722 RCanPointeeTy.getUnqualifiedType())) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001723 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1724 lType.getAsString(), rType.getAsString(),
1725 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001726 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00001727 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001728 return Context.IntTy;
1729 }
Steve Naroff20373222008-06-03 14:04:54 +00001730 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
1731 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
1732 ImpCastExprToType(rex, lType);
1733 return Context.IntTy;
1734 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00001735 }
Steve Naroff20373222008-06-03 14:04:54 +00001736 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
1737 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001738 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001739 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1740 lType.getAsString(), rType.getAsString(),
1741 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00001742 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001743 return Context.IntTy;
1744 }
Steve Naroff20373222008-06-03 14:04:54 +00001745 if (lType->isIntegerType() &&
1746 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00001747 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001748 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1749 lType.getAsString(), rType.getAsString(),
1750 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00001751 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00001752 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001753 }
Chris Lattnerca5eede2007-12-12 05:47:28 +00001754 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001755}
1756
Nate Begemanbe2341d2008-07-14 18:02:46 +00001757/// CheckVectorCompareOperands - vector comparisons are a clang extension that
1758/// operates on extended vector types. Instead of producing an IntTy result,
1759/// like a scalar comparison, a vector comparison produces a vector of integer
1760/// types.
1761QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
1762 SourceLocation loc,
1763 bool isRelational) {
1764 // Check to make sure we're operating on vectors of the same type and width,
1765 // Allowing one side to be a scalar of element type.
1766 QualType vType = CheckVectorOperands(loc, lex, rex);
1767 if (vType.isNull())
1768 return vType;
1769
1770 QualType lType = lex->getType();
1771 QualType rType = rex->getType();
1772
1773 // For non-floating point types, check for self-comparisons of the form
1774 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1775 // often indicate logic errors in the program.
1776 if (!lType->isFloatingType()) {
1777 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1778 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1779 if (DRL->getDecl() == DRR->getDecl())
1780 Diag(loc, diag::warn_selfcomparison);
1781 }
1782
1783 // Check for comparisons of floating point operands using != and ==.
1784 if (!isRelational && lType->isFloatingType()) {
1785 assert (rType->isFloatingType());
1786 CheckFloatComparison(loc,lex,rex);
1787 }
1788
1789 // Return the type for the comparison, which is the same as vector type for
1790 // integer vectors, or an integer type of identical size and number of
1791 // elements for floating point vectors.
1792 if (lType->isIntegerType())
1793 return lType;
1794
1795 const VectorType *VTy = lType->getAsVectorType();
1796
1797 // FIXME: need to deal with non-32b int / non-64b long long
1798 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
1799 if (TypeSize == 32) {
1800 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
1801 }
1802 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
1803 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
1804}
1805
Reid Spencer5f016e22007-07-11 17:01:13 +00001806inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001807 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001808{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001809 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001810 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001811
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001812 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001813
Steve Naroffa4332e22007-07-17 00:58:39 +00001814 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001815 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001816 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001817}
1818
1819inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00001820 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00001821{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001822 UsualUnaryConversions(lex);
1823 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001824
Eli Friedman5773a6c2008-05-13 20:16:47 +00001825 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001826 return Context.IntTy;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001827 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001828}
1829
1830inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00001831 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001832{
1833 QualType lhsType = lex->getType();
1834 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001835 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1836
1837 switch (mlval) { // C99 6.5.16p2
Chris Lattner5cf216b2008-01-04 18:04:52 +00001838 case Expr::MLV_Valid:
1839 break;
1840 case Expr::MLV_ConstQualified:
1841 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1842 return QualType();
1843 case Expr::MLV_ArrayType:
1844 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1845 lhsType.getAsString(), lex->getSourceRange());
1846 return QualType();
1847 case Expr::MLV_NotObjectType:
1848 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1849 lhsType.getAsString(), lex->getSourceRange());
1850 return QualType();
1851 case Expr::MLV_InvalidExpression:
1852 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1853 lex->getSourceRange());
1854 return QualType();
1855 case Expr::MLV_IncompleteType:
1856 case Expr::MLV_IncompleteVoidType:
1857 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1858 lhsType.getAsString(), lex->getSourceRange());
1859 return QualType();
1860 case Expr::MLV_DuplicateVectorComponents:
1861 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1862 lex->getSourceRange());
1863 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001864 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00001865
Chris Lattner5cf216b2008-01-04 18:04:52 +00001866 AssignConvertType ConvTy;
1867 if (compoundType.isNull())
1868 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1869 else
1870 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1871
1872 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1873 rex, "assigning"))
1874 return QualType();
1875
Reid Spencer5f016e22007-07-11 17:01:13 +00001876 // C99 6.5.16p3: The type of an assignment expression is the type of the
1877 // left operand unless the left operand has qualified type, in which case
1878 // it is the unqualified version of the type of the left operand.
1879 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1880 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001881 // C++ 5.17p1: the type of the assignment expression is that of its left
1882 // oprdu.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001883 return lhsType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001884}
1885
1886inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00001887 Expr *&lex, Expr *&rex, SourceLocation loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001888 UsualUnaryConversions(rex);
1889 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001890}
1891
Steve Naroff49b45262007-07-13 16:58:59 +00001892/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1893/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00001894QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00001895 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001896 assert(!resType.isNull() && "no type for increment/decrement expression");
1897
Steve Naroff084f9ed2007-08-24 17:20:07 +00001898 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00001899 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00001900 if (pt->getPointeeType()->isVoidType()) {
1901 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
1902 } else if (!pt->getPointeeType()->isObjectType()) {
1903 // C99 6.5.2.4p2, 6.5.6p2
Reid Spencer5f016e22007-07-11 17:01:13 +00001904 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1905 resType.getAsString(), op->getSourceRange());
1906 return QualType();
1907 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00001908 } else if (!resType->isRealType()) {
1909 if (resType->isComplexType())
1910 // C99 does not support ++/-- on complex types.
1911 Diag(OpLoc, diag::ext_integer_increment_complex,
1912 resType.getAsString(), op->getSourceRange());
1913 else {
1914 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1915 resType.getAsString(), op->getSourceRange());
1916 return QualType();
1917 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001918 }
Steve Naroffdd10e022007-08-23 21:37:33 +00001919 // At this point, we know we have a real, complex or pointer type.
1920 // Now make sure the operand is a modifiable lvalue.
Reid Spencer5f016e22007-07-11 17:01:13 +00001921 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1922 if (mlval != Expr::MLV_Valid) {
1923 // FIXME: emit a more precise diagnostic...
1924 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1925 op->getSourceRange());
1926 return QualType();
1927 }
1928 return resType;
1929}
1930
Anders Carlsson369dee42008-02-01 07:15:58 +00001931/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00001932/// This routine allows us to typecheck complex/recursive expressions
1933/// where the declaration is needed for type checking. Here are some
1934/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
Chris Lattnerf0467b32008-04-02 04:24:33 +00001935static ValueDecl *getPrimaryDecl(Expr *E) {
1936 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001937 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00001938 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001939 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00001940 // Fields cannot be declared with a 'register' storage class.
1941 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001942 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00001943 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00001944 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00001945 case Stmt::ArraySubscriptExprClass: {
1946 // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer.
1947
Chris Lattnerf0467b32008-04-02 04:24:33 +00001948 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlssonf2a4b842008-02-01 16:01:31 +00001949 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00001950 return 0;
1951 else
1952 return VD;
1953 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001954 case Stmt::UnaryOperatorClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00001955 return getPrimaryDecl(cast<UnaryOperator>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00001956 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00001957 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00001958 case Stmt::ImplicitCastExprClass:
1959 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001960 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00001961 default:
1962 return 0;
1963 }
1964}
1965
1966/// CheckAddressOfOperand - The operand of & must be either a function
1967/// designator or an lvalue designating an object. If it is an lvalue, the
1968/// object cannot be declared with storage class register or be a bit field.
1969/// Note: The usual conversions are *not* applied to the operand of the &
1970/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1971QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff08f19672008-01-13 17:10:08 +00001972 if (getLangOptions().C99) {
1973 // Implement C99-only parts of addressof rules.
1974 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
1975 if (uOp->getOpcode() == UnaryOperator::Deref)
1976 // Per C99 6.5.3.2, the address of a deref always returns a valid result
1977 // (assuming the deref expression is valid).
1978 return uOp->getSubExpr()->getType();
1979 }
1980 // Technically, there should be a check for array subscript
1981 // expressions here, but the result of one is always an lvalue anyway.
1982 }
Anders Carlsson369dee42008-02-01 07:15:58 +00001983 ValueDecl *dcl = getPrimaryDecl(op);
Reid Spencer5f016e22007-07-11 17:01:13 +00001984 Expr::isLvalueResult lval = op->isLvalue();
1985
1986 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00001987 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1988 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00001989 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1990 op->getSourceRange());
1991 return QualType();
1992 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00001993 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
1994 if (MemExpr->getMemberDecl()->isBitField()) {
1995 Diag(OpLoc, diag::err_typecheck_address_of,
1996 std::string("bit-field"), op->getSourceRange());
1997 return QualType();
1998 }
1999 // Check for Apple extension for accessing vector components.
2000 } else if (isa<ArraySubscriptExpr>(op) &&
2001 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2002 Diag(OpLoc, diag::err_typecheck_address_of,
2003 std::string("vector"), op->getSourceRange());
2004 return QualType();
2005 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00002006 // We have an lvalue with a decl. Make sure the decl is not declared
2007 // with the register storage-class specifier.
2008 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2009 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroffbcb2b612008-02-29 23:30:25 +00002010 Diag(OpLoc, diag::err_typecheck_address_of,
2011 std::string("register variable"), op->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002012 return QualType();
2013 }
2014 } else
2015 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002016 }
2017 // If the operand has type "type", the result has type "pointer to type".
2018 return Context.getPointerType(op->getType());
2019}
2020
2021QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002022 UsualUnaryConversions(op);
2023 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002024
Chris Lattnerbefee482007-07-31 16:53:04 +00002025 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff08f19672008-01-13 17:10:08 +00002026 // Note that per both C89 and C99, this is always legal, even
2027 // if ptype is an incomplete type or void.
2028 // It would be possible to warn about dereferencing a
2029 // void pointer, but it's completely well-defined,
2030 // and such a warning is unlikely to catch any mistakes.
2031 return PT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002032 }
2033 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2034 qType.getAsString(), op->getSourceRange());
2035 return QualType();
2036}
2037
2038static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2039 tok::TokenKind Kind) {
2040 BinaryOperator::Opcode Opc;
2041 switch (Kind) {
2042 default: assert(0 && "Unknown binop!");
2043 case tok::star: Opc = BinaryOperator::Mul; break;
2044 case tok::slash: Opc = BinaryOperator::Div; break;
2045 case tok::percent: Opc = BinaryOperator::Rem; break;
2046 case tok::plus: Opc = BinaryOperator::Add; break;
2047 case tok::minus: Opc = BinaryOperator::Sub; break;
2048 case tok::lessless: Opc = BinaryOperator::Shl; break;
2049 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2050 case tok::lessequal: Opc = BinaryOperator::LE; break;
2051 case tok::less: Opc = BinaryOperator::LT; break;
2052 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2053 case tok::greater: Opc = BinaryOperator::GT; break;
2054 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2055 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2056 case tok::amp: Opc = BinaryOperator::And; break;
2057 case tok::caret: Opc = BinaryOperator::Xor; break;
2058 case tok::pipe: Opc = BinaryOperator::Or; break;
2059 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2060 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2061 case tok::equal: Opc = BinaryOperator::Assign; break;
2062 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2063 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2064 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2065 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2066 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2067 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2068 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2069 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2070 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2071 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2072 case tok::comma: Opc = BinaryOperator::Comma; break;
2073 }
2074 return Opc;
2075}
2076
2077static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2078 tok::TokenKind Kind) {
2079 UnaryOperator::Opcode Opc;
2080 switch (Kind) {
2081 default: assert(0 && "Unknown unary op!");
2082 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2083 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2084 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2085 case tok::star: Opc = UnaryOperator::Deref; break;
2086 case tok::plus: Opc = UnaryOperator::Plus; break;
2087 case tok::minus: Opc = UnaryOperator::Minus; break;
2088 case tok::tilde: Opc = UnaryOperator::Not; break;
2089 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2090 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2091 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2092 case tok::kw___real: Opc = UnaryOperator::Real; break;
2093 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2094 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2095 }
2096 return Opc;
2097}
2098
2099// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002100Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00002101 ExprTy *LHS, ExprTy *RHS) {
2102 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2103 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2104
Steve Narofff69936d2007-09-16 03:34:24 +00002105 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2106 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00002107
2108 QualType ResultTy; // Result type of the binary operator.
2109 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2110
2111 switch (Opc) {
2112 default:
2113 assert(0 && "Unknown binary expr!");
2114 case BinaryOperator::Assign:
2115 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2116 break;
2117 case BinaryOperator::Mul:
2118 case BinaryOperator::Div:
2119 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2120 break;
2121 case BinaryOperator::Rem:
2122 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2123 break;
2124 case BinaryOperator::Add:
2125 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2126 break;
2127 case BinaryOperator::Sub:
2128 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2129 break;
2130 case BinaryOperator::Shl:
2131 case BinaryOperator::Shr:
2132 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2133 break;
2134 case BinaryOperator::LE:
2135 case BinaryOperator::LT:
2136 case BinaryOperator::GE:
2137 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002138 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002139 break;
2140 case BinaryOperator::EQ:
2141 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002142 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002143 break;
2144 case BinaryOperator::And:
2145 case BinaryOperator::Xor:
2146 case BinaryOperator::Or:
2147 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2148 break;
2149 case BinaryOperator::LAnd:
2150 case BinaryOperator::LOr:
2151 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2152 break;
2153 case BinaryOperator::MulAssign:
2154 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002155 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002156 if (!CompTy.isNull())
2157 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2158 break;
2159 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002160 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002161 if (!CompTy.isNull())
2162 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2163 break;
2164 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002165 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002166 if (!CompTy.isNull())
2167 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2168 break;
2169 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002170 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002171 if (!CompTy.isNull())
2172 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2173 break;
2174 case BinaryOperator::ShlAssign:
2175 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002176 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002177 if (!CompTy.isNull())
2178 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2179 break;
2180 case BinaryOperator::AndAssign:
2181 case BinaryOperator::XorAssign:
2182 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002183 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002184 if (!CompTy.isNull())
2185 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2186 break;
2187 case BinaryOperator::Comma:
2188 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2189 break;
2190 }
2191 if (ResultTy.isNull())
2192 return true;
2193 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002194 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002195 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002196 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002197}
2198
2199// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002200Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00002201 ExprTy *input) {
2202 Expr *Input = (Expr*)input;
2203 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2204 QualType resultType;
2205 switch (Opc) {
2206 default:
2207 assert(0 && "Unimplemented unary expr!");
2208 case UnaryOperator::PreInc:
2209 case UnaryOperator::PreDec:
2210 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2211 break;
2212 case UnaryOperator::AddrOf:
2213 resultType = CheckAddressOfOperand(Input, OpLoc);
2214 break;
2215 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00002216 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002217 resultType = CheckIndirectionOperand(Input, OpLoc);
2218 break;
2219 case UnaryOperator::Plus:
2220 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002221 UsualUnaryConversions(Input);
2222 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002223 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2224 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2225 resultType.getAsString());
2226 break;
2227 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002228 UsualUnaryConversions(Input);
2229 resultType = Input->getType();
Steve Naroff084f9ed2007-08-24 17:20:07 +00002230 // C99 6.5.3.3p1. We allow complex as a GCC extension.
2231 if (!resultType->isIntegerType()) {
2232 if (resultType->isComplexType())
2233 // C99 does not support '~' for complex conjugation.
2234 Diag(OpLoc, diag::ext_integer_complement_complex,
2235 resultType.getAsString());
2236 else
2237 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2238 resultType.getAsString());
2239 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002240 break;
2241 case UnaryOperator::LNot: // logical negation
2242 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002243 DefaultFunctionArrayConversion(Input);
2244 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002245 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2246 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2247 resultType.getAsString());
2248 // LNot always has type int. C99 6.5.3.3p5.
2249 resultType = Context.IntTy;
2250 break;
2251 case UnaryOperator::SizeOf:
2252 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
2253 break;
2254 case UnaryOperator::AlignOf:
2255 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
2256 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00002257 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00002258 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00002259 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00002260 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002261 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00002262 resultType = Input->getType();
2263 break;
2264 }
2265 if (resultType.isNull())
2266 return true;
2267 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2268}
2269
Steve Naroff1b273c42007-09-16 14:56:35 +00002270/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2271Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00002272 SourceLocation LabLoc,
2273 IdentifierInfo *LabelII) {
2274 // Look up the record for this label identifier.
2275 LabelStmt *&LabelDecl = LabelMap[LabelII];
2276
2277 // If we haven't seen this label yet, create a forward reference.
2278 if (LabelDecl == 0)
2279 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2280
2281 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00002282 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2283 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00002284}
2285
Steve Naroff1b273c42007-09-16 14:56:35 +00002286Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002287 SourceLocation RPLoc) { // "({..})"
2288 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2289 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2290 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2291
2292 // FIXME: there are a variety of strange constraints to enforce here, for
2293 // example, it is not possible to goto into a stmt expression apparently.
2294 // More semantic analysis is needed.
2295
2296 // FIXME: the last statement in the compount stmt has its value used. We
2297 // should not warn about it being unused.
2298
2299 // If there are sub stmts in the compound stmt, take the type of the last one
2300 // as the type of the stmtexpr.
2301 QualType Ty = Context.VoidTy;
2302
2303 if (!Compound->body_empty())
2304 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
2305 Ty = LastExpr->getType();
2306
2307 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2308}
Steve Naroffd34e9152007-08-01 22:05:33 +00002309
Steve Naroff1b273c42007-09-16 14:56:35 +00002310Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002311 SourceLocation TypeLoc,
2312 TypeTy *argty,
2313 OffsetOfComponent *CompPtr,
2314 unsigned NumComponents,
2315 SourceLocation RPLoc) {
2316 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2317 assert(!ArgTy.isNull() && "Missing type argument!");
2318
2319 // We must have at least one component that refers to the type, and the first
2320 // one is known to be a field designator. Verify that the ArgTy represents
2321 // a struct/union/class.
2322 if (!ArgTy->isRecordType())
2323 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2324
2325 // Otherwise, create a compound literal expression as the base, and
2326 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00002327 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002328
Chris Lattner9e2b75c2007-08-31 21:49:13 +00002329 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2330 // GCC extension, diagnose them.
2331 if (NumComponents != 1)
2332 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2333 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2334
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002335 for (unsigned i = 0; i != NumComponents; ++i) {
2336 const OffsetOfComponent &OC = CompPtr[i];
2337 if (OC.isBrackets) {
2338 // Offset of an array sub-field. TODO: Should we allow vector elements?
2339 const ArrayType *AT = Res->getType()->getAsArrayType();
2340 if (!AT) {
2341 delete Res;
2342 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2343 Res->getType().getAsString());
2344 }
2345
Chris Lattner704fe352007-08-30 17:59:59 +00002346 // FIXME: C++: Verify that operator[] isn't overloaded.
2347
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002348 // C99 6.5.2.1p1
2349 Expr *Idx = static_cast<Expr*>(OC.U.E);
2350 if (!Idx->getType()->isIntegerType())
2351 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2352 Idx->getSourceRange());
2353
2354 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2355 continue;
2356 }
2357
2358 const RecordType *RC = Res->getType()->getAsRecordType();
2359 if (!RC) {
2360 delete Res;
2361 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2362 Res->getType().getAsString());
2363 }
2364
2365 // Get the decl corresponding to this.
2366 RecordDecl *RD = RC->getDecl();
2367 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2368 if (!MemberDecl)
2369 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2370 OC.U.IdentInfo->getName(),
2371 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00002372
2373 // FIXME: C++: Verify that MemberDecl isn't a static field.
2374 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00002375 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2376 // matter here.
2377 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002378 }
2379
2380 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2381 BuiltinLoc);
2382}
2383
2384
Steve Naroff1b273c42007-09-16 14:56:35 +00002385Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00002386 TypeTy *arg1, TypeTy *arg2,
2387 SourceLocation RPLoc) {
2388 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2389 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2390
2391 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2392
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002393 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00002394}
2395
Steve Naroff1b273c42007-09-16 14:56:35 +00002396Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00002397 ExprTy *expr1, ExprTy *expr2,
2398 SourceLocation RPLoc) {
2399 Expr *CondExpr = static_cast<Expr*>(cond);
2400 Expr *LHSExpr = static_cast<Expr*>(expr1);
2401 Expr *RHSExpr = static_cast<Expr*>(expr2);
2402
2403 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2404
2405 // The conditional expression is required to be a constant expression.
2406 llvm::APSInt condEval(32);
2407 SourceLocation ExpLoc;
2408 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2409 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2410 CondExpr->getSourceRange());
2411
2412 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2413 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2414 RHSExpr->getType();
2415 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2416}
2417
Nate Begeman67295d02008-01-30 20:50:20 +00002418/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00002419/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00002420/// The number of arguments has already been validated to match the number of
2421/// arguments in FnType.
2422static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00002423 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00002424 for (unsigned i = 0; i != NumParams; ++i) {
2425 QualType ExprTy = Args[i]->getType().getCanonicalType();
2426 QualType ParmTy = FnType->getArgType(i).getCanonicalType();
2427
2428 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00002429 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00002430 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00002431 return true;
2432}
2433
2434Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2435 SourceLocation *CommaLocs,
2436 SourceLocation BuiltinLoc,
2437 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00002438 // __builtin_overload requires at least 2 arguments
2439 if (NumArgs < 2)
2440 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2441 SourceRange(BuiltinLoc, RParenLoc));
Nate Begemane2ce1d92008-01-17 17:46:27 +00002442
Nate Begemane2ce1d92008-01-17 17:46:27 +00002443 // The first argument is required to be a constant expression. It tells us
2444 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00002445 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00002446 Expr *NParamsExpr = Args[0];
2447 llvm::APSInt constEval(32);
2448 SourceLocation ExpLoc;
2449 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2450 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2451 NParamsExpr->getSourceRange());
2452
2453 // Verify that the number of parameters is > 0
2454 unsigned NumParams = constEval.getZExtValue();
2455 if (NumParams == 0)
2456 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2457 NParamsExpr->getSourceRange());
2458 // Verify that we have at least 1 + NumParams arguments to the builtin.
2459 if ((NumParams + 1) > NumArgs)
2460 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2461 SourceRange(BuiltinLoc, RParenLoc));
2462
2463 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00002464 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00002465 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00002466 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2467 // UsualUnaryConversions will convert the function DeclRefExpr into a
2468 // pointer to function.
2469 Expr *Fn = UsualUnaryConversions(Args[i]);
2470 FunctionTypeProto *FnType = 0;
Nate Begeman67295d02008-01-30 20:50:20 +00002471 if (const PointerType *PT = Fn->getType()->getAsPointerType()) {
2472 QualType PointeeType = PT->getPointeeType().getCanonicalType();
2473 FnType = dyn_cast<FunctionTypeProto>(PointeeType);
2474 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00002475
2476 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2477 // parameters, and the number of parameters must match the value passed to
2478 // the builtin.
2479 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begeman67295d02008-01-30 20:50:20 +00002480 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2481 Fn->getSourceRange());
Nate Begemane2ce1d92008-01-17 17:46:27 +00002482
2483 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00002484 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00002485 // If they match, return a new OverloadExpr.
Nate Begeman796ef3d2008-01-31 05:38:29 +00002486 if (ExprsMatchFnType(Args+1, FnType)) {
2487 if (OE)
2488 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2489 OE->getFn()->getSourceRange());
2490 // Remember our match, and continue processing the remaining arguments
2491 // to catch any errors.
2492 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2493 BuiltinLoc, RParenLoc);
2494 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00002495 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00002496 // Return the newly created OverloadExpr node, if we succeded in matching
2497 // exactly one of the candidate functions.
2498 if (OE)
2499 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00002500
2501 // If we didn't find a matching function Expr in the __builtin_overload list
2502 // the return an error.
2503 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00002504 for (unsigned i = 0; i != NumParams; ++i) {
2505 if (i != 0) typeNames += ", ";
2506 typeNames += Args[i+1]->getType().getAsString();
2507 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00002508
2509 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2510 SourceRange(BuiltinLoc, RParenLoc));
2511}
2512
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002513Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2514 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00002515 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002516 Expr *E = static_cast<Expr*>(expr);
2517 QualType T = QualType::getFromOpaquePtr(type);
2518
2519 InitBuiltinVaListType();
2520
Chris Lattner5cf216b2008-01-04 18:04:52 +00002521 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2522 != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002523 return Diag(E->getLocStart(),
2524 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2525 E->getType().getAsString(),
2526 E->getSourceRange());
2527
2528 // FIXME: Warn if a non-POD type is passed in.
2529
2530 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2531}
2532
Chris Lattner5cf216b2008-01-04 18:04:52 +00002533bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2534 SourceLocation Loc,
2535 QualType DstType, QualType SrcType,
2536 Expr *SrcExpr, const char *Flavor) {
2537 // Decode the result (notice that AST's are still created for extensions).
2538 bool isInvalid = false;
2539 unsigned DiagKind;
2540 switch (ConvTy) {
2541 default: assert(0 && "Unknown conversion type");
2542 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00002543 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00002544 DiagKind = diag::ext_typecheck_convert_pointer_int;
2545 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00002546 case IntToPointer:
2547 DiagKind = diag::ext_typecheck_convert_int_pointer;
2548 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002549 case IncompatiblePointer:
2550 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2551 break;
2552 case FunctionVoidPointer:
2553 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2554 break;
2555 case CompatiblePointerDiscardsQualifiers:
2556 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2557 break;
2558 case Incompatible:
2559 DiagKind = diag::err_typecheck_convert_incompatible;
2560 isInvalid = true;
2561 break;
2562 }
2563
2564 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2565 SrcExpr->getSourceRange());
2566 return isInvalid;
2567}