blob: 4dcc68431845565345a894b9a91dbb61ea248166 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Ted Kremenek30c66752007-11-25 00:58:00 +000015#include "SemaUtil.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/Expr.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000018#include "clang/AST/ExprCXX.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000019#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Chris Lattner83bd5eb2007-12-28 05:29:59 +000024#include "llvm/ADT/OwningPtr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000026#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Steve Naroff87d58b42007-09-16 03:34:24 +000029/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000030/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
31/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
32/// multiple tokens. However, the common case is that StringToks points to one
33/// string.
34///
35Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000036Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000037 assert(NumStringToks && "Must have at least one string!");
38
39 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
40 if (Literal.hadError)
41 return ExprResult(true);
42
43 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
44 for (unsigned i = 0; i != NumStringToks; ++i)
45 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +000046
47 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000048 if (Literal.Pascal && Literal.GetStringLength() > 256)
49 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
50 SourceRange(StringToks[0].getLocation(),
51 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000052
Chris Lattnera6dcce32008-02-11 00:02:17 +000053 QualType StrTy = Context.CharTy;
54 // FIXME: handle wchar_t
55 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
56
57 // Get an array type for the string, according to C99 6.4.5. This includes
58 // the nul terminator character as well as the string length for pascal
59 // strings.
60 StrTy = Context.getConstantArrayType(StrTy,
61 llvm::APInt(32, Literal.GetStringLength()+1),
62 ArrayType::Normal, 0);
63
Chris Lattner4b009652007-07-25 00:24:17 +000064 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
65 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +000066 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000067 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000068 StringToks[NumStringToks-1].getLocation());
69}
70
71
Steve Naroff0acc9c92007-09-15 18:49:24 +000072/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000073/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +000074/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000075Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000076 IdentifierInfo &II,
77 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +000078 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +000079 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +000080
81 // If this reference is in an Objective-C method, then ivar lookup happens as
82 // well.
83 if (CurMethodDecl) {
Steve Naroffe57c21a2008-04-01 23:04:06 +000084 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +000085 // There are two cases to handle here. 1) scoped lookup could have failed,
86 // in which case we should look for an ivar. 2) scoped lookup could have
87 // found a decl, but that decl is outside the current method (i.e. a global
88 // variable). In these two cases, we do a lookup for an ivar with this
89 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +000090 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +000091 ObjCInterfaceDecl *IFace = CurMethodDecl->getClassInterface(), *DeclClass;
92 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II, DeclClass)) {
93 // FIXME: This should use a new expr for a direct reference, don't turn
94 // this into Self->ivar, just return a BareIVarExpr or something.
95 IdentifierInfo &II = Context.Idents.get("self");
96 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
97 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
98 static_cast<Expr*>(SelfExpr.Val), true, true);
99 }
100 }
101 }
102
Chris Lattner4b009652007-07-25 00:24:17 +0000103 if (D == 0) {
104 // Otherwise, this could be an implicitly declared function reference (legal
105 // in C90, extension in C99).
106 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000107 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000108 D = ImplicitlyDefineFunction(Loc, II, S);
109 else {
110 // If this name wasn't predeclared and if this is not a function call,
111 // diagnose the problem.
112 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
113 }
114 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000115
Steve Naroff91b03f72007-08-28 03:03:08 +0000116 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneree4c3bf2008-02-29 16:48:43 +0000117 // check if referencing an identifier with __attribute__((deprecated)).
118 if (VD->getAttr<DeprecatedAttr>())
119 Diag(Loc, diag::warn_deprecated, VD->getName());
120
Steve Naroffcae537d2007-08-28 18:45:29 +0000121 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000122 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000123 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000124 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000125 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000126
Chris Lattner4b009652007-07-25 00:24:17 +0000127 if (isa<TypedefDecl>(D))
128 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000129 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000130 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000131 if (isa<NamespaceDecl>(D))
132 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000133
134 assert(0 && "Invalid decl");
135 abort();
136}
137
Steve Naroff87d58b42007-09-16 03:34:24 +0000138Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000139 tok::TokenKind Kind) {
140 PreDefinedExpr::IdentType IT;
141
142 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000143 default: assert(0 && "Unknown simple primary expr!");
144 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
145 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
146 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000147 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000148
149 // Verify that this is in a function context.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000150 if (CurFunctionDecl == 0 && CurMethodDecl == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000151 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000152
Chris Lattner7e637512008-01-12 08:14:25 +0000153 // Pre-defined identifiers are of type char[x], where x is the length of the
154 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000155 unsigned Length;
156 if (CurFunctionDecl)
157 Length = CurFunctionDecl->getIdentifier()->getLength();
158 else
Fariborz Jahaniandcecd5c2008-01-17 17:37:26 +0000159 Length = CurMethodDecl->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000160
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000161 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000162 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000163 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner7e637512008-01-12 08:14:25 +0000164 return new PreDefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000165}
166
Steve Naroff87d58b42007-09-16 03:34:24 +0000167Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000168 llvm::SmallString<16> CharBuffer;
169 CharBuffer.resize(Tok.getLength());
170 const char *ThisTokBegin = &CharBuffer[0];
171 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
172
173 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
174 Tok.getLocation(), PP);
175 if (Literal.hadError())
176 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000177
178 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
179
180 return new CharacterLiteral(Literal.getValue(), type, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000181}
182
Steve Naroff87d58b42007-09-16 03:34:24 +0000183Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000184 // fast path for a single digit (which is quite common). A single digit
185 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
186 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000187 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000188
Chris Lattner8cd0e932008-03-05 18:54:05 +0000189 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000190 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000191 Context.IntTy,
192 Tok.getLocation()));
193 }
194 llvm::SmallString<512> IntegerBuffer;
195 IntegerBuffer.resize(Tok.getLength());
196 const char *ThisTokBegin = &IntegerBuffer[0];
197
198 // Get the spelling of the token, which eliminates trigraphs, etc.
199 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
200 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
201 Tok.getLocation(), PP);
202 if (Literal.hadError)
203 return ExprResult(true);
204
Chris Lattner1de66eb2007-08-26 03:42:43 +0000205 Expr *Res;
206
207 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000208 QualType Ty;
209 const llvm::fltSemantics *Format;
Chris Lattner858eece2007-09-22 18:29:59 +0000210
211 if (Literal.isFloat) {
212 Ty = Context.FloatTy;
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000213 Format = Context.Target.getFloatFormat();
214 } else if (!Literal.isLong) {
Chris Lattner858eece2007-09-22 18:29:59 +0000215 Ty = Context.DoubleTy;
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000216 Format = Context.Target.getDoubleFormat();
217 } else {
218 Ty = Context.LongDoubleTy;
219 Format = Context.Target.getLongDoubleFormat();
Chris Lattner858eece2007-09-22 18:29:59 +0000220 }
221
Ted Kremenekddedbe22007-11-29 00:56:49 +0000222 // isExact will be set by GetFloatValue().
223 bool isExact = false;
224
225 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
226 Ty, Tok.getLocation());
227
Chris Lattner1de66eb2007-08-26 03:42:43 +0000228 } else if (!Literal.isIntegerLiteral()) {
229 return ExprResult(true);
230 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000231 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000232
Neil Booth7421e9c2007-08-29 22:00:19 +0000233 // long long is a C99 feature.
234 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000235 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000236 Diag(Tok.getLocation(), diag::ext_longlong);
237
Chris Lattner4b009652007-07-25 00:24:17 +0000238 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000239 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000240
241 if (Literal.GetIntegerValue(ResultVal)) {
242 // If this value didn't fit into uintmax_t, warn and force to ull.
243 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000244 Ty = Context.UnsignedLongLongTy;
245 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000246 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000247 } else {
248 // If this value fits into a ULL, try to figure out what else it fits into
249 // according to the rules of C99 6.4.4.1p5.
250
251 // Octal, Hexadecimal, and integers with a U suffix are allowed to
252 // be an unsigned int.
253 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
254
255 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000256 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000257 if (!Literal.isLong && !Literal.isLongLong) {
258 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000259 unsigned IntSize = Context.Target.getIntWidth();
260
Chris Lattner4b009652007-07-25 00:24:17 +0000261 // Does it fit in a unsigned int?
262 if (ResultVal.isIntN(IntSize)) {
263 // Does it fit in a signed int?
264 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000265 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000266 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000267 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000268 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000269 }
Chris Lattner4b009652007-07-25 00:24:17 +0000270 }
271
272 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000273 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000274 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000275
276 // Does it fit in a unsigned long?
277 if (ResultVal.isIntN(LongSize)) {
278 // Does it fit in a signed long?
279 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000280 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000281 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000282 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000283 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000284 }
Chris Lattner4b009652007-07-25 00:24:17 +0000285 }
286
287 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000288 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000289 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000290
291 // Does it fit in a unsigned long long?
292 if (ResultVal.isIntN(LongLongSize)) {
293 // Does it fit in a signed long long?
294 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000295 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000296 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000297 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000298 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000299 }
300 }
301
302 // If we still couldn't decide a type, we probably have something that
303 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000304 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000305 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000306 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000307 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000308 }
Chris Lattnere4068872008-05-09 05:59:00 +0000309
310 if (ResultVal.getBitWidth() != Width)
311 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000312 }
313
Chris Lattner48d7f382008-04-02 04:24:33 +0000314 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000315 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000316
317 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
318 if (Literal.isImaginary)
319 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
320
321 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000322}
323
Steve Naroff87d58b42007-09-16 03:34:24 +0000324Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000325 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000326 Expr *E = (Expr *)Val;
327 assert((E != 0) && "ActOnParenExpr() missing expr");
328 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000329}
330
331/// The UsualUnaryConversions() function is *not* called by this routine.
332/// See C99 6.3.2.1p[2-4] for more details.
333QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
334 SourceLocation OpLoc, bool isSizeof) {
335 // C99 6.5.3.4p1:
336 if (isa<FunctionType>(exprType) && isSizeof)
337 // alignof(function) is allowed.
338 Diag(OpLoc, diag::ext_sizeof_function_type);
339 else if (exprType->isVoidType())
340 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
341 else if (exprType->isIncompleteType()) {
342 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
343 diag::err_alignof_incomplete_type,
344 exprType.getAsString());
345 return QualType(); // error
346 }
347 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
348 return Context.getSizeType();
349}
350
351Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000352ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000353 SourceLocation LPLoc, TypeTy *Ty,
354 SourceLocation RPLoc) {
355 // If error parsing type, ignore.
356 if (Ty == 0) return true;
357
358 // Verify that this is a valid expression.
359 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
360
361 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
362
363 if (resultType.isNull())
364 return true;
365 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
366}
367
Chris Lattner5110ad52007-08-24 21:41:10 +0000368QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000369 DefaultFunctionArrayConversion(V);
370
Chris Lattnera16e42d2007-08-26 05:39:26 +0000371 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000372 if (const ComplexType *CT = V->getType()->getAsComplexType())
373 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000374
375 // Otherwise they pass through real integer and floating point types here.
376 if (V->getType()->isArithmeticType())
377 return V->getType();
378
379 // Reject anything else.
380 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
381 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000382}
383
384
Chris Lattner4b009652007-07-25 00:24:17 +0000385
Steve Naroff87d58b42007-09-16 03:34:24 +0000386Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000387 tok::TokenKind Kind,
388 ExprTy *Input) {
389 UnaryOperator::Opcode Opc;
390 switch (Kind) {
391 default: assert(0 && "Unknown unary op!");
392 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
393 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
394 }
395 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
396 if (result.isNull())
397 return true;
398 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
399}
400
401Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000402ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000403 ExprTy *Idx, SourceLocation RLoc) {
404 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
405
406 // Perform default conversions.
407 DefaultFunctionArrayConversion(LHSExp);
408 DefaultFunctionArrayConversion(RHSExp);
409
410 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
411
412 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000413 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000414 // in the subscript position. As a result, we need to derive the array base
415 // and index from the expression types.
416 Expr *BaseExpr, *IndexExpr;
417 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000418 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000419 BaseExpr = LHSExp;
420 IndexExpr = RHSExp;
421 // FIXME: need to deal with const...
422 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000423 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000424 // Handle the uncommon case of "123[Ptr]".
425 BaseExpr = RHSExp;
426 IndexExpr = LHSExp;
427 // FIXME: need to deal with const...
428 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000429 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
430 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000431 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000432
433 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman506806b2008-02-19 01:11:03 +0000434 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000435 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000436 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000437 // FIXME: need to deal with const...
438 ResultType = VTy->getElementType();
439 } else {
440 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
441 RHSExp->getSourceRange());
442 }
443 // C99 6.5.2.1p1
444 if (!IndexExpr->getType()->isIntegerType())
445 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
446 IndexExpr->getSourceRange());
447
448 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
449 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000450 // void (*)(int)) and pointers to incomplete types. Functions are not
451 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000452 if (!ResultType->isObjectType())
453 return Diag(BaseExpr->getLocStart(),
454 diag::err_typecheck_subscript_not_object,
455 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
456
457 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
458}
459
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000460QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000461CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000462 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000463 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000464
465 // The vector accessor can't exceed the number of elements.
466 const char *compStr = CompName.getName();
467 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000468 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000469 baseType.getAsString(), SourceRange(CompLoc));
470 return QualType();
471 }
472 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000473 if (vecType->getPointAccessorIdx(*compStr) != -1) {
474 do
475 compStr++;
476 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
477 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
478 do
479 compStr++;
480 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
481 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
482 do
483 compStr++;
484 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
485 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000486
487 if (*compStr) {
488 // We didn't get to the end of the string. This means the component names
489 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000490 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000491 std::string(compStr,compStr+1), SourceRange(CompLoc));
492 return QualType();
493 }
494 // Each component accessor can't exceed the vector type.
495 compStr = CompName.getName();
496 while (*compStr) {
497 if (vecType->isAccessorWithinNumElements(*compStr))
498 compStr++;
499 else
500 break;
501 }
502 if (*compStr) {
503 // We didn't get to the end of the string. This means a component accessor
504 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000505 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000506 baseType.getAsString(), SourceRange(CompLoc));
507 return QualType();
508 }
509 // The component accessor looks fine - now we need to compute the actual type.
510 // The vector type is implied by the component accessor. For example,
511 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
512 unsigned CompSize = strlen(CompName.getName());
513 if (CompSize == 1)
514 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000515
Nate Begemanaf6ed502008-04-18 23:10:10 +0000516 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000517 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000518 // diagostics look bad. We want extended vector types to appear built-in.
519 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
520 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
521 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000522 }
523 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000524}
525
Chris Lattner4b009652007-07-25 00:24:17 +0000526Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000527ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000528 tok::TokenKind OpKind, SourceLocation MemberLoc,
529 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000530 Expr *BaseExpr = static_cast<Expr *>(Base);
531 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000532
533 // Perform default conversions.
534 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000535
Steve Naroff2cb66382007-07-26 03:11:44 +0000536 QualType BaseType = BaseExpr->getType();
537 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000538
Chris Lattner4b009652007-07-25 00:24:17 +0000539 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000540 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000541 BaseType = PT->getPointeeType();
542 else
543 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
544 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000545 }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000546 // The base type is either a record or an ExtVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000547 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000548 RecordDecl *RDecl = RTy->getDecl();
549 if (RTy->isIncompleteType())
550 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
551 BaseExpr->getSourceRange());
552 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000553 FieldDecl *MemberDecl = RDecl->getMember(&Member);
554 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000555 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
556 SourceRange(MemberLoc));
Eli Friedman76b49832008-02-06 22:48:16 +0000557
558 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000559 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000560 QualType MemberType = MemberDecl->getType();
561 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000562 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000563 MemberType = MemberType.getQualifiedType(combinedQualifiers);
564
565 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl,
566 MemberLoc, MemberType);
Nate Begemanaf6ed502008-04-18 23:10:10 +0000567 } else if (BaseType->isExtVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000568 // Component access limited to variables (reject vec4.rg.g).
Nate Begeman78a2a312008-03-17 17:22:18 +0000569 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000570 return Diag(OpLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000571 SourceRange(MemberLoc));
Nate Begemanaf6ed502008-04-18 23:10:10 +0000572 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000573 if (ret.isNull())
574 return true;
Nate Begemanaf6ed502008-04-18 23:10:10 +0000575 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Ted Kremenek42730c52008-01-07 19:49:32 +0000576 } else if (BaseType->isObjCInterfaceType()) {
577 ObjCInterfaceDecl *IFace;
578 if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
579 IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000580 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000581 IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
582 ObjCInterfaceDecl *clsDeclared;
583 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000584 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
585 OpKind==tok::arrow);
586 }
587 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
588 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000589}
590
Steve Naroff87d58b42007-09-16 03:34:24 +0000591/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000592/// This provides the location of the left/right parens and a list of comma
593/// locations.
594Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000595ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000596 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000597 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
598 Expr *Fn = static_cast<Expr *>(fn);
599 Expr **Args = reinterpret_cast<Expr**>(args);
600 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +0000601 FunctionDecl *FDecl = NULL;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000602
603 // Promote the function operand.
604 UsualUnaryConversions(Fn);
605
606 // If we're directly calling a function, get the declaration for
607 // that function.
608 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
609 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
610 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
611
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000612 // Make the call expr early, before semantic checks. This guarantees cleanup
613 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +0000614 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000615 Context.BoolTy, RParenLoc));
616
Chris Lattner4b009652007-07-25 00:24:17 +0000617 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
618 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000619 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000620 if (PT == 0)
621 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
622 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000623 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
624 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000625 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
626 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000627
628 // We know the result type of the call, set it.
629 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000630
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000631 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000632 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
633 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000634 unsigned NumArgsInProto = Proto->getNumArgs();
635 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000636
Chris Lattner3e254fb2008-04-08 04:40:51 +0000637 // If too few arguments are available (and we don't have default
638 // arguments for the remaining parameters), don't make the call.
639 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +0000640 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000641 // Use default arguments for missing arguments
642 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +0000643 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000644 } else
645 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
646 Fn->getSourceRange());
647 }
648
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000649 // If too many are passed and not variadic, error on the extras and drop
650 // them.
651 if (NumArgs > NumArgsInProto) {
652 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000653 Diag(Args[NumArgsInProto]->getLocStart(),
654 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
655 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000656 Args[NumArgs-1]->getLocEnd()));
657 // This deletes the extra arguments.
658 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000659 }
660 NumArgsToCheck = NumArgsInProto;
661 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000662
Chris Lattner4b009652007-07-25 00:24:17 +0000663 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000664 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +0000665 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000666
667 Expr *Arg;
668 if (i < NumArgs)
669 Arg = Args[i];
670 else
671 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +0000672 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000673
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000674 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +0000675 AssignConvertType ConvTy =
676 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000677 TheCall->setArg(i, Arg);
678
Chris Lattner005ed752008-01-04 18:04:52 +0000679 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
680 ArgType, Arg, "passing"))
681 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000682 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000683
684 // If this is a variadic call, handle args passed through "...".
685 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +0000686 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000687 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
688 Expr *Arg = Args[i];
689 DefaultArgumentPromotion(Arg);
690 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000691 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000692 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000693 } else {
694 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
695
Steve Naroffdb65e052007-08-28 23:30:39 +0000696 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000697 for (unsigned i = 0; i != NumArgs; i++) {
698 Expr *Arg = Args[i];
699 DefaultArgumentPromotion(Arg);
700 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000701 }
Chris Lattner4b009652007-07-25 00:24:17 +0000702 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000703
Chris Lattner2e64c072007-08-10 20:18:51 +0000704 // Do special checking on direct calls to functions.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000705 if (FDecl && CheckFunctionCall(FDecl, TheCall.get()))
706 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000707
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000708 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000709}
710
711Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000712ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000713 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000714 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000715 QualType literalType = QualType::getFromOpaquePtr(Ty);
716 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000717 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000718 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000719
Steve Naroffcb69fb72007-12-10 22:44:33 +0000720 // FIXME: add more semantic analysis (C99 6.5.2.5).
Steve Narofff0b23542008-01-10 22:15:12 +0000721 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +0000722 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +0000723
724 bool isFileScope = !CurFunctionDecl && !CurMethodDecl;
725 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +0000726 if (CheckForConstantInitializer(literalExpr, literalType))
727 return true;
728 }
Steve Naroffbe37fc02008-01-14 18:19:28 +0000729 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000730}
731
732Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000733ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000734 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000735 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000736
Steve Naroff0acc9c92007-09-15 18:49:24 +0000737 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000738 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000739
Chris Lattner48d7f382008-04-02 04:24:33 +0000740 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
741 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
742 return E;
Chris Lattner4b009652007-07-25 00:24:17 +0000743}
744
Chris Lattnerd1f26b32007-12-20 00:44:32 +0000745bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000746 assert(VectorTy->isVectorType() && "Not a vector type!");
747
748 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000749 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000750 return Diag(R.getBegin(),
751 Ty->isVectorType() ?
752 diag::err_invalid_conversion_between_vectors :
753 diag::err_invalid_conversion_between_vector_and_integer,
754 VectorTy.getAsString().c_str(),
755 Ty.getAsString().c_str(), R);
756 } else
757 return Diag(R.getBegin(),
758 diag::err_invalid_conversion_between_vector_and_scalar,
759 VectorTy.getAsString().c_str(),
760 Ty.getAsString().c_str(), R);
761
762 return false;
763}
764
Chris Lattner4b009652007-07-25 00:24:17 +0000765Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000766ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000767 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000768 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000769
770 Expr *castExpr = static_cast<Expr*>(Op);
771 QualType castType = QualType::getFromOpaquePtr(Ty);
772
Steve Naroff68adb482007-08-31 00:32:44 +0000773 UsualUnaryConversions(castExpr);
774
Chris Lattner4b009652007-07-25 00:24:17 +0000775 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
776 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000777 if (!castType->isVoidType()) { // Cast to void allows any expr type.
Steve Narofff459ee52008-01-24 22:55:05 +0000778 if (!castType->isScalarType() && !castType->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000779 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
780 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Steve Narofff459ee52008-01-24 22:55:05 +0000781 if (!castExpr->getType()->isScalarType() &&
782 !castExpr->getType()->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000783 return Diag(castExpr->getLocStart(),
784 diag::err_typecheck_expect_scalar_operand,
785 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000786
787 if (castExpr->getType()->isVectorType()) {
788 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
789 castExpr->getType(), castType))
790 return true;
791 } else if (castType->isVectorType()) {
792 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
793 castType, castExpr->getType()))
794 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000795 }
Chris Lattner4b009652007-07-25 00:24:17 +0000796 }
797 return new CastExpr(castType, castExpr, LParenLoc);
798}
799
Chris Lattner98a425c2007-11-26 01:40:58 +0000800/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
801/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000802inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
803 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
804 UsualUnaryConversions(cond);
805 UsualUnaryConversions(lex);
806 UsualUnaryConversions(rex);
807 QualType condT = cond->getType();
808 QualType lexT = lex->getType();
809 QualType rexT = rex->getType();
810
811 // first, check the condition.
812 if (!condT->isScalarType()) { // C99 6.5.15p2
813 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
814 condT.getAsString());
815 return QualType();
816 }
Chris Lattner992ae932008-01-06 22:42:25 +0000817
818 // Now check the two expressions.
819
820 // If both operands have arithmetic type, do the usual arithmetic conversions
821 // to find a common type: C99 6.5.15p3,5.
822 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000823 UsualArithmeticConversions(lex, rex);
824 return lex->getType();
825 }
Chris Lattner992ae932008-01-06 22:42:25 +0000826
827 // If both operands are the same structure or union type, the result is that
828 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000829 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +0000830 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +0000831 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +0000832 // "If both the operands have structure or union type, the result has
833 // that type." This implies that CV qualifiers are dropped.
834 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000835 }
Chris Lattner992ae932008-01-06 22:42:25 +0000836
837 // C99 6.5.15p5: "If both operands have void type, the result has void type."
838 if (lexT->isVoidType() && rexT->isVoidType())
839 return lexT.getUnqualifiedType();
Steve Naroff12ebf272008-01-08 01:11:38 +0000840
841 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
842 // the type of the other operand."
843 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000844 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000845 return lexT;
846 }
847 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000848 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000849 return rexT;
850 }
Chris Lattner0ac51632008-01-06 22:50:31 +0000851 // Handle the case where both operands are pointers before we handle null
852 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +0000853 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
854 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
855 // get the "pointed to" types
856 QualType lhptee = LHSPT->getPointeeType();
857 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000858
Chris Lattner71225142007-07-31 21:27:01 +0000859 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
860 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +0000861 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +0000862 // Figure out necessary qualifiers (C99 6.5.15p6)
863 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000864 QualType destType = Context.getPointerType(destPointee);
865 ImpCastExprToType(lex, destType); // add qualifiers if necessary
866 ImpCastExprToType(rex, destType); // promote to void*
867 return destType;
868 }
Chris Lattner9db553e2008-04-02 06:59:01 +0000869 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +0000870 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000871 QualType destType = Context.getPointerType(destPointee);
872 ImpCastExprToType(lex, destType); // add qualifiers if necessary
873 ImpCastExprToType(rex, destType); // promote to void*
874 return destType;
875 }
Chris Lattner4b009652007-07-25 00:24:17 +0000876
Steve Naroff85f0dc52007-10-15 20:41:53 +0000877 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
878 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +0000879 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +0000880 lexT.getAsString(), rexT.getAsString(),
881 lex->getSourceRange(), rex->getSourceRange());
Eli Friedman33284862008-01-30 17:02:03 +0000882 // In this situation, we assume void* type. No especially good
883 // reason, but this is what gcc does, and we do have to pick
884 // to get a consistent AST.
885 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
886 ImpCastExprToType(lex, voidPtrTy);
887 ImpCastExprToType(rex, voidPtrTy);
888 return voidPtrTy;
Chris Lattner71225142007-07-31 21:27:01 +0000889 }
890 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000891 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
892 // differently qualified versions of compatible types, the result type is
893 // a pointer to an appropriately qualified version of the *composite*
894 // type.
Chris Lattner0ac51632008-01-06 22:50:31 +0000895 // FIXME: Need to return the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +0000896 // FIXME: Need to add qualifiers
Chris Lattner0ac51632008-01-06 22:50:31 +0000897 return lexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000898 }
Chris Lattner4b009652007-07-25 00:24:17 +0000899 }
Chris Lattner71225142007-07-31 21:27:01 +0000900
Chris Lattner992ae932008-01-06 22:42:25 +0000901 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +0000902 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
903 lexT.getAsString(), rexT.getAsString(),
904 lex->getSourceRange(), rex->getSourceRange());
905 return QualType();
906}
907
Steve Naroff87d58b42007-09-16 03:34:24 +0000908/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000909/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000910Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000911 SourceLocation ColonLoc,
912 ExprTy *Cond, ExprTy *LHS,
913 ExprTy *RHS) {
914 Expr *CondExpr = (Expr *) Cond;
915 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000916
917 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
918 // was the condition.
919 bool isLHSNull = LHSExpr == 0;
920 if (isLHSNull)
921 LHSExpr = CondExpr;
922
Chris Lattner4b009652007-07-25 00:24:17 +0000923 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
924 RHSExpr, QuestionLoc);
925 if (result.isNull())
926 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000927 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
928 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000929}
930
Steve Naroffdb65e052007-08-28 23:30:39 +0000931/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Steve Naroffbbaed752008-01-29 02:42:22 +0000932/// do not have a prototype. Arguments that have type float are promoted to
933/// double. All other argument types are converted by UsualUnaryConversions().
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000934void Sema::DefaultArgumentPromotion(Expr *&Expr) {
935 QualType Ty = Expr->getType();
936 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffdb65e052007-08-28 23:30:39 +0000937
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000938 if (Ty == Context.FloatTy)
Chris Lattnere992d6c2008-01-16 19:17:22 +0000939 ImpCastExprToType(Expr, Context.DoubleTy);
Steve Naroffbbaed752008-01-29 02:42:22 +0000940 else
941 UsualUnaryConversions(Expr);
Steve Naroffdb65e052007-08-28 23:30:39 +0000942}
943
Chris Lattner4b009652007-07-25 00:24:17 +0000944/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Chris Lattner48d7f382008-04-02 04:24:33 +0000945void Sema::DefaultFunctionArrayConversion(Expr *&E) {
946 QualType Ty = E->getType();
947 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000948
Chris Lattner48d7f382008-04-02 04:24:33 +0000949 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
Chris Lattnera05f7d22008-04-02 17:45:06 +0000950 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
Chris Lattner48d7f382008-04-02 04:24:33 +0000951 Ty = E->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000952 }
Chris Lattner48d7f382008-04-02 04:24:33 +0000953 if (Ty->isFunctionType())
954 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner19eb97e2008-04-02 05:18:44 +0000955 else if (Ty->isArrayType())
956 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
Chris Lattner4b009652007-07-25 00:24:17 +0000957}
958
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000959/// UsualUnaryConversions - Performs various conversions that are common to most
Chris Lattner4b009652007-07-25 00:24:17 +0000960/// operators (C99 6.3). The conversions of array and function types are
961/// sometimes surpressed. For example, the array->pointer conversion doesn't
962/// apply if the array is an argument to the sizeof or address (&) operators.
963/// In these instances, this routine should *not* be called.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000964Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
965 QualType Ty = Expr->getType();
966 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000967
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000968 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
Chris Lattnera05f7d22008-04-02 17:45:06 +0000969 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000970 Ty = Expr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000971 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000972 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
Chris Lattnere992d6c2008-01-16 19:17:22 +0000973 ImpCastExprToType(Expr, Context.IntTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000974 else
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000975 DefaultFunctionArrayConversion(Expr);
976
977 return Expr;
Chris Lattner4b009652007-07-25 00:24:17 +0000978}
979
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000980/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000981/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
982/// routine returns the first non-arithmetic type found. The client is
983/// responsible for emitting appropriate error diagnostics.
Chris Lattner48d7f382008-04-02 04:24:33 +0000984/// FIXME: verify the conversion rules for "complex int" are consistent with
985/// GCC.
Steve Naroff8f708362007-08-24 19:07:16 +0000986QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
987 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000988 if (!isCompAssign) {
989 UsualUnaryConversions(lhsExpr);
990 UsualUnaryConversions(rhsExpr);
991 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000992 // For conversion purposes, we ignore any qualifiers.
993 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000994 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
995 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000996
997 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000998 if (lhs == rhs)
999 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001000
1001 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1002 // The caller can deal with this (e.g. pointer + int).
1003 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001004 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001005
1006 // At this point, we have two different arithmetic types.
1007
1008 // Handle complex types first (C99 6.3.1.8p1).
1009 if (lhs->isComplexType() || rhs->isComplexType()) {
Steve Naroff43001212008-01-15 19:36:10 +00001010 // if we have an integer operand, the result is the complex type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001011 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001012 // convert the rhs to the lhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001013 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001014 return lhs;
Steve Naroff43001212008-01-15 19:36:10 +00001015 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001016 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001017 // convert the lhs to the rhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001018 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001019 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001020 }
Steve Naroff3cf497f2007-08-27 01:27:54 +00001021 // This handles complex/complex, complex/float, or float/complex.
1022 // When both operands are complex, the shorter operand is converted to the
1023 // type of the longer, and that is the type of the result. This corresponds
1024 // to what is done when combining two real floating-point operands.
1025 // The fun begins when size promotion occur across type domains.
1026 // From H&S 6.3.4: When one operand is complex and the other is a real
1027 // floating-point type, the less precise type is converted, within it's
1028 // real or complex domain, to the precision of the other type. For example,
1029 // when combining a "long double" with a "double _Complex", the
1030 // "double _Complex" is promoted to "long double _Complex".
Chris Lattnerd7135b42008-04-06 23:38:49 +00001031 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Naroff45fc9822007-08-27 15:30:22 +00001032
1033 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +00001034 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
1035 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001036 ImpCastExprToType(rhsExpr, rhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001037 } else if (result < 0) { // The right side is bigger, convert lhs.
1038 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
1039 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001040 ImpCastExprToType(lhsExpr, lhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001041 }
1042 // At this point, lhs and rhs have the same rank/size. Now, make sure the
1043 // domains match. This is a requirement for our implementation, C99
1044 // does not require this promotion.
1045 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1046 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001047 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001048 ImpCastExprToType(lhsExpr, rhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001049 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001050 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001051 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001052 ImpCastExprToType(rhsExpr, lhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001053 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001054 }
Chris Lattner4b009652007-07-25 00:24:17 +00001055 }
Steve Naroff3b6157f2007-08-27 21:43:43 +00001056 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +00001057 }
1058 // Now handle "real" floating types (i.e. float, double, long double).
1059 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1060 // if we have an integer operand, the result is the real floating type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001061 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001062 // convert rhs to the lhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001063 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001064 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001065 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001066 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001067 // convert lhs to the rhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001068 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001069 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001070 }
1071 // We have two real floating types, float/complex combos were handled above.
1072 // Convert the smaller operand to the bigger result.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001073 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Naroff45fc9822007-08-27 15:30:22 +00001074
1075 if (result > 0) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001076 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001077 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001078 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001079 if (result < 0) { // convert the lhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001080 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff45fc9822007-08-27 15:30:22 +00001081 return rhs;
1082 }
1083 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001084 }
Steve Naroff43001212008-01-15 19:36:10 +00001085 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
1086 // Handle GCC complex int extension.
Steve Naroff43001212008-01-15 19:36:10 +00001087 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
Eli Friedman50727042008-02-08 01:19:44 +00001088 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
Steve Naroff43001212008-01-15 19:36:10 +00001089
Eli Friedman50727042008-02-08 01:19:44 +00001090 if (lhsComplexInt && rhsComplexInt) {
Chris Lattner51285d82008-04-06 23:55:33 +00001091 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
1092 rhsComplexInt->getElementType()) >= 0) {
Eli Friedman94075c02008-02-08 01:24:30 +00001093 // convert the rhs
1094 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1095 return lhs;
Eli Friedman50727042008-02-08 01:19:44 +00001096 }
1097 if (!isCompAssign)
Eli Friedman94075c02008-02-08 01:24:30 +00001098 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Eli Friedman50727042008-02-08 01:19:44 +00001099 return rhs;
1100 } else if (lhsComplexInt && rhs->isIntegerType()) {
1101 // convert the rhs to the lhs complex type.
1102 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1103 return lhs;
1104 } else if (rhsComplexInt && lhs->isIntegerType()) {
1105 // convert the lhs to the rhs complex type.
1106 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1107 return rhs;
1108 }
Steve Naroff43001212008-01-15 19:36:10 +00001109 }
Chris Lattner4b009652007-07-25 00:24:17 +00001110 // Finally, we have two differing integer types.
Chris Lattner51285d82008-04-06 23:55:33 +00001111 if (Context.getIntegerTypeOrder(lhs, rhs) >= 0) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001112 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001113 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001114 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001115 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff8f708362007-08-24 19:07:16 +00001116 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001117}
1118
1119// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1120// being closely modeled after the C99 spec:-). The odd characteristic of this
1121// routine is it effectively iqnores the qualifiers on the top level pointee.
1122// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1123// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001124Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001125Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1126 QualType lhptee, rhptee;
1127
1128 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001129 lhptee = lhsType->getAsPointerType()->getPointeeType();
1130 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001131
1132 // make sure we operate on the canonical type
1133 lhptee = lhptee.getCanonicalType();
1134 rhptee = rhptee.getCanonicalType();
1135
Chris Lattner005ed752008-01-04 18:04:52 +00001136 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001137
1138 // C99 6.5.16.1p1: This following citation is common to constraints
1139 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1140 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001141 // FIXME: Handle ASQualType
1142 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1143 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001144 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001145
1146 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1147 // incomplete type and the other is a pointer to a qualified or unqualified
1148 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001149 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001150 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001151 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001152
1153 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001154 assert(rhptee->isFunctionType());
1155 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001156 }
1157
1158 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001159 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001160 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001161
1162 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001163 assert(lhptee->isFunctionType());
1164 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001165 }
1166
Chris Lattner4b009652007-07-25 00:24:17 +00001167 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1168 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001169 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1170 rhptee.getUnqualifiedType()))
1171 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001172 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001173}
1174
1175/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1176/// has code to accommodate several GCC extensions when type checking
1177/// pointers. Here are some objectionable examples that GCC considers warnings:
1178///
1179/// int a, *pint;
1180/// short *pshort;
1181/// struct foo *pfoo;
1182///
1183/// pint = pshort; // warning: assignment from incompatible pointer type
1184/// a = pint; // warning: assignment makes integer from pointer without a cast
1185/// pint = a; // warning: assignment makes pointer from integer without a cast
1186/// pint = pfoo; // warning: assignment from incompatible pointer type
1187///
1188/// As a result, the code for dealing with pointers is more complex than the
1189/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001190///
Chris Lattner005ed752008-01-04 18:04:52 +00001191Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001192Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001193 // Get canonical types. We're not formatting these types, just comparing
1194 // them.
1195 lhsType = lhsType.getCanonicalType();
1196 rhsType = rhsType.getCanonicalType();
1197
1198 if (lhsType.getUnqualifiedType() == rhsType.getUnqualifiedType())
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001199 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001200
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001201 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001202 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001203 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001204 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001205 }
Chris Lattner1853da22008-01-04 23:18:45 +00001206
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001207 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1208 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001209 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001210 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001211 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001212
Chris Lattner390564e2008-04-07 06:49:41 +00001213 if (isa<VectorType>(lhsType) || isa<VectorType>(rhsType)) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001214 // For ExtVector, allow vector splats; float -> <n x float>
1215 if (const ExtVectorType *LV = dyn_cast<ExtVectorType>(lhsType)) {
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001216 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1217 return Compatible;
1218 }
1219
1220 // If LHS and RHS are both vectors of integer or both vectors of floating
1221 // point types, and the total vector length is the same, allow the
1222 // conversion. This is a bitcast; no bits are changed but the result type
1223 // is different.
1224 if (getLangOptions().LaxVectorConversions &&
1225 lhsType->isVectorType() && rhsType->isVectorType()) {
1226 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1227 (lhsType->isRealFloatingType() && rhsType->isRealFloatingType())) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001228 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Nate Begemanec2d1062007-12-30 02:59:45 +00001229 return Compatible;
1230 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001231 }
1232 return Incompatible;
1233 }
1234
1235 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001236 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001237
Chris Lattner390564e2008-04-07 06:49:41 +00001238 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001239 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001240 return IntToPointer;
Chris Lattner4b009652007-07-25 00:24:17 +00001241
Chris Lattner390564e2008-04-07 06:49:41 +00001242 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001243 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001244 return Incompatible;
1245 }
1246
Chris Lattner390564e2008-04-07 06:49:41 +00001247 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001248 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Chris Lattner390564e2008-04-07 06:49:41 +00001249 if (lhsType->isIntegerType() && lhsType != Context.BoolTy)
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001250 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001251
Chris Lattner390564e2008-04-07 06:49:41 +00001252 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001253 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001254 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001255 }
1256
1257 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001258 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001259 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001260 }
1261 return Incompatible;
1262}
1263
Chris Lattner005ed752008-01-04 18:04:52 +00001264Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001265Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001266 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1267 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001268 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001269 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001270 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001271 return Compatible;
1272 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001273 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001274 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001275 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001276 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001277 //
1278 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1279 // are better understood.
1280 if (!lhsType->isReferenceType())
1281 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001282
Chris Lattner005ed752008-01-04 18:04:52 +00001283 Sema::AssignConvertType result =
1284 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001285
1286 // C99 6.5.16.1p2: The value of the right operand is converted to the
1287 // type of the assignment expression.
1288 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001289 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001290 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001291}
1292
Chris Lattner005ed752008-01-04 18:04:52 +00001293Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001294Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1295 return CheckAssignmentConstraints(lhsType, rhsType);
1296}
1297
Chris Lattner2c8bff72007-12-12 05:47:28 +00001298QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001299 Diag(loc, diag::err_typecheck_invalid_operands,
1300 lex->getType().getAsString(), rex->getType().getAsString(),
1301 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001302 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001303}
1304
1305inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1306 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001307 // For conversion purposes, we ignore any qualifiers.
1308 // For example, "const float" and "float" are equivalent.
1309 QualType lhsType = lex->getType().getCanonicalType().getUnqualifiedType();
1310 QualType rhsType = rex->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001311
1312 // make sure the vector types are identical.
Nate Begeman03105572008-04-04 01:30:25 +00001313 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001314 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001315
Nate Begemanaf6ed502008-04-18 23:10:10 +00001316 // if the lhs is an extended vector and the rhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001317 // promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001318 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001319 if (V->getElementType().getCanonicalType().getTypePtr()
1320 == rhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001321 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001322 return lhsType;
1323 }
1324 }
1325
Nate Begemanaf6ed502008-04-18 23:10:10 +00001326 // if the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001327 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001328 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001329 if (V->getElementType().getCanonicalType().getTypePtr()
1330 == lhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001331 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001332 return rhsType;
1333 }
1334 }
1335
Chris Lattner4b009652007-07-25 00:24:17 +00001336 // You cannot convert between vector values of different size.
1337 Diag(loc, diag::err_typecheck_vector_not_convertable,
1338 lex->getType().getAsString(), rex->getType().getAsString(),
1339 lex->getSourceRange(), rex->getSourceRange());
1340 return QualType();
1341}
1342
1343inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001344 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001345{
1346 QualType lhsType = lex->getType(), rhsType = rex->getType();
1347
1348 if (lhsType->isVectorType() || rhsType->isVectorType())
1349 return CheckVectorOperands(loc, lex, rex);
1350
Steve Naroff8f708362007-08-24 19:07:16 +00001351 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001352
Chris Lattner4b009652007-07-25 00:24:17 +00001353 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001354 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001355 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001356}
1357
1358inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001359 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001360{
1361 QualType lhsType = lex->getType(), rhsType = rex->getType();
1362
Steve Naroff8f708362007-08-24 19:07:16 +00001363 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001364
Chris Lattner4b009652007-07-25 00:24:17 +00001365 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001366 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001367 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001368}
1369
1370inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001371 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001372{
1373 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1374 return CheckVectorOperands(loc, lex, rex);
1375
Steve Naroff8f708362007-08-24 19:07:16 +00001376 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001377
1378 // handle the common case first (both operands are arithmetic).
1379 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001380 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001381
1382 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1383 return lex->getType();
1384 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1385 return rex->getType();
Chris Lattner2c8bff72007-12-12 05:47:28 +00001386 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001387}
1388
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001389// C99 6.5.6
1390QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1391 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001392 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1393 return CheckVectorOperands(loc, lex, rex);
1394
Steve Naroff8f708362007-08-24 19:07:16 +00001395 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001396
Chris Lattnerf6da2912007-12-09 21:53:25 +00001397 // Enforce type constraints: C99 6.5.6p3.
1398
1399 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001400 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001401 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001402
1403 // Either ptr - int or ptr - ptr.
1404 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001405 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001406
Chris Lattnerf6da2912007-12-09 21:53:25 +00001407 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001408 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001409 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001410 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001411 Diag(loc, diag::ext_gnu_void_ptr,
1412 lex->getSourceRange(), rex->getSourceRange());
1413 } else {
1414 Diag(loc, diag::err_typecheck_sub_ptr_object,
1415 lex->getType().getAsString(), lex->getSourceRange());
1416 return QualType();
1417 }
1418 }
1419
1420 // The result type of a pointer-int computation is the pointer type.
1421 if (rex->getType()->isIntegerType())
1422 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001423
Chris Lattnerf6da2912007-12-09 21:53:25 +00001424 // Handle pointer-pointer subtractions.
1425 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001426 QualType rpointee = RHSPTy->getPointeeType();
1427
Chris Lattnerf6da2912007-12-09 21:53:25 +00001428 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001429 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001430 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001431 if (rpointee->isVoidType()) {
1432 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001433 Diag(loc, diag::ext_gnu_void_ptr,
1434 lex->getSourceRange(), rex->getSourceRange());
1435 } else {
1436 Diag(loc, diag::err_typecheck_sub_ptr_object,
1437 rex->getType().getAsString(), rex->getSourceRange());
1438 return QualType();
1439 }
1440 }
1441
1442 // Pointee types must be compatible.
Steve Naroff577f9722008-01-29 18:58:14 +00001443 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1444 rpointee.getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001445 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1446 lex->getType().getAsString(), rex->getType().getAsString(),
1447 lex->getSourceRange(), rex->getSourceRange());
1448 return QualType();
1449 }
1450
1451 return Context.getPointerDiffType();
1452 }
1453 }
1454
Chris Lattner2c8bff72007-12-12 05:47:28 +00001455 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001456}
1457
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001458// C99 6.5.7
1459QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1460 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00001461 // C99 6.5.7p2: Each of the operands shall have integer type.
1462 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1463 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001464
Chris Lattner2c8bff72007-12-12 05:47:28 +00001465 // Shifts don't perform usual arithmetic conversions, they just do integer
1466 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001467 if (!isCompAssign)
1468 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001469 UsualUnaryConversions(rex);
1470
1471 // "The type of the result is that of the promoted left operand."
1472 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001473}
1474
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001475// C99 6.5.8
1476QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1477 bool isRelational) {
Chris Lattner254f3bc2007-08-26 01:18:55 +00001478 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001479 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1480 UsualArithmeticConversions(lex, rex);
1481 else {
1482 UsualUnaryConversions(lex);
1483 UsualUnaryConversions(rex);
1484 }
Chris Lattner4b009652007-07-25 00:24:17 +00001485 QualType lType = lex->getType();
1486 QualType rType = rex->getType();
1487
Ted Kremenek486509e2007-10-29 17:13:39 +00001488 // For non-floating point types, check for self-comparisons of the form
1489 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1490 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001491 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001492 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1493 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001494 if (DRL->getDecl() == DRR->getDecl())
1495 Diag(loc, diag::warn_selfcomparison);
1496 }
1497
Chris Lattner254f3bc2007-08-26 01:18:55 +00001498 if (isRelational) {
1499 if (lType->isRealType() && rType->isRealType())
1500 return Context.IntTy;
1501 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001502 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001503 if (lType->isFloatingType()) {
1504 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001505 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001506 }
1507
Chris Lattner254f3bc2007-08-26 01:18:55 +00001508 if (lType->isArithmeticType() && rType->isArithmeticType())
1509 return Context.IntTy;
1510 }
Chris Lattner4b009652007-07-25 00:24:17 +00001511
Chris Lattner22be8422007-08-26 01:10:14 +00001512 bool LHSIsNull = lex->isNullPointerConstant(Context);
1513 bool RHSIsNull = rex->isNullPointerConstant(Context);
1514
Chris Lattner254f3bc2007-08-26 01:18:55 +00001515 // All of the following pointer related warnings are GCC extensions, except
1516 // when handling null pointer constants. One day, we can consider making them
1517 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001518 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001519 QualType LCanPointeeTy =
1520 lType->getAsPointerType()->getPointeeType().getCanonicalType();
1521 QualType RCanPointeeTy =
1522 rType->getAsPointerType()->getPointeeType().getCanonicalType();
Eli Friedman50727042008-02-08 01:19:44 +00001523
Steve Naroff3b435622007-11-13 14:57:38 +00001524 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001525 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1526 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
1527 RCanPointeeTy.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001528 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1529 lType.getAsString(), rType.getAsString(),
1530 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001531 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001532 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001533 return Context.IntTy;
1534 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001535 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001536 && ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001537 ImpCastExprToType(rex, lType);
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001538 return Context.IntTy;
1539 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001540 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001541 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001542 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1543 lType.getAsString(), rType.getAsString(),
1544 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001545 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001546 return Context.IntTy;
1547 }
1548 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001549 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001550 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1551 lType.getAsString(), rType.getAsString(),
1552 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001553 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001554 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001555 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001556 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001557}
1558
Chris Lattner4b009652007-07-25 00:24:17 +00001559inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001560 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001561{
1562 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1563 return CheckVectorOperands(loc, lex, rex);
1564
Steve Naroff8f708362007-08-24 19:07:16 +00001565 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001566
1567 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001568 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001569 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001570}
1571
1572inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1573 Expr *&lex, Expr *&rex, SourceLocation loc)
1574{
1575 UsualUnaryConversions(lex);
1576 UsualUnaryConversions(rex);
1577
1578 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1579 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001580 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001581}
1582
1583inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001584 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001585{
1586 QualType lhsType = lex->getType();
1587 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner4b009652007-07-25 00:24:17 +00001588 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1589
1590 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001591 case Expr::MLV_Valid:
1592 break;
1593 case Expr::MLV_ConstQualified:
1594 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1595 return QualType();
1596 case Expr::MLV_ArrayType:
1597 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1598 lhsType.getAsString(), lex->getSourceRange());
1599 return QualType();
1600 case Expr::MLV_NotObjectType:
1601 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1602 lhsType.getAsString(), lex->getSourceRange());
1603 return QualType();
1604 case Expr::MLV_InvalidExpression:
1605 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1606 lex->getSourceRange());
1607 return QualType();
1608 case Expr::MLV_IncompleteType:
1609 case Expr::MLV_IncompleteVoidType:
1610 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1611 lhsType.getAsString(), lex->getSourceRange());
1612 return QualType();
1613 case Expr::MLV_DuplicateVectorComponents:
1614 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1615 lex->getSourceRange());
1616 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001617 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001618
Chris Lattner005ed752008-01-04 18:04:52 +00001619 AssignConvertType ConvTy;
1620 if (compoundType.isNull())
1621 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1622 else
1623 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1624
1625 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1626 rex, "assigning"))
1627 return QualType();
1628
Chris Lattner4b009652007-07-25 00:24:17 +00001629 // C99 6.5.16p3: The type of an assignment expression is the type of the
1630 // left operand unless the left operand has qualified type, in which case
1631 // it is the unqualified version of the type of the left operand.
1632 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1633 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001634 // C++ 5.17p1: the type of the assignment expression is that of its left
1635 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001636 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001637}
1638
1639inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1640 Expr *&lex, Expr *&rex, SourceLocation loc) {
1641 UsualUnaryConversions(rex);
1642 return rex->getType();
1643}
1644
1645/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1646/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1647QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1648 QualType resType = op->getType();
1649 assert(!resType.isNull() && "no type for increment/decrement expression");
1650
Steve Naroffd30e1932007-08-24 17:20:07 +00001651 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001652 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001653 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1654 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1655 resType.getAsString(), op->getSourceRange());
1656 return QualType();
1657 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001658 } else if (!resType->isRealType()) {
1659 if (resType->isComplexType())
1660 // C99 does not support ++/-- on complex types.
1661 Diag(OpLoc, diag::ext_integer_increment_complex,
1662 resType.getAsString(), op->getSourceRange());
1663 else {
1664 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1665 resType.getAsString(), op->getSourceRange());
1666 return QualType();
1667 }
Chris Lattner4b009652007-07-25 00:24:17 +00001668 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001669 // At this point, we know we have a real, complex or pointer type.
1670 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001671 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1672 if (mlval != Expr::MLV_Valid) {
1673 // FIXME: emit a more precise diagnostic...
1674 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1675 op->getSourceRange());
1676 return QualType();
1677 }
1678 return resType;
1679}
1680
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001681/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00001682/// This routine allows us to typecheck complex/recursive expressions
1683/// where the declaration is needed for type checking. Here are some
1684/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
Chris Lattner48d7f382008-04-02 04:24:33 +00001685static ValueDecl *getPrimaryDecl(Expr *E) {
1686 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001687 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001688 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001689 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001690 // Fields cannot be declared with a 'register' storage class.
1691 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00001692 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00001693 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00001694 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001695 case Stmt::ArraySubscriptExprClass: {
1696 // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer.
1697
Chris Lattner48d7f382008-04-02 04:24:33 +00001698 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00001699 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001700 return 0;
1701 else
1702 return VD;
1703 }
Chris Lattner4b009652007-07-25 00:24:17 +00001704 case Stmt::UnaryOperatorClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001705 return getPrimaryDecl(cast<UnaryOperator>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001706 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001707 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001708 case Stmt::ImplicitCastExprClass:
1709 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00001710 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001711 default:
1712 return 0;
1713 }
1714}
1715
1716/// CheckAddressOfOperand - The operand of & must be either a function
1717/// designator or an lvalue designating an object. If it is an lvalue, the
1718/// object cannot be declared with storage class register or be a bit field.
1719/// Note: The usual conversions are *not* applied to the operand of the &
1720/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1721QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001722 if (getLangOptions().C99) {
1723 // Implement C99-only parts of addressof rules.
1724 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
1725 if (uOp->getOpcode() == UnaryOperator::Deref)
1726 // Per C99 6.5.3.2, the address of a deref always returns a valid result
1727 // (assuming the deref expression is valid).
1728 return uOp->getSubExpr()->getType();
1729 }
1730 // Technically, there should be a check for array subscript
1731 // expressions here, but the result of one is always an lvalue anyway.
1732 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001733 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner4b009652007-07-25 00:24:17 +00001734 Expr::isLvalueResult lval = op->isLvalue();
1735
1736 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001737 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1738 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001739 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1740 op->getSourceRange());
1741 return QualType();
1742 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00001743 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
1744 if (MemExpr->getMemberDecl()->isBitField()) {
1745 Diag(OpLoc, diag::err_typecheck_address_of,
1746 std::string("bit-field"), op->getSourceRange());
1747 return QualType();
1748 }
1749 // Check for Apple extension for accessing vector components.
1750 } else if (isa<ArraySubscriptExpr>(op) &&
1751 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
1752 Diag(OpLoc, diag::err_typecheck_address_of,
1753 std::string("vector"), op->getSourceRange());
1754 return QualType();
1755 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00001756 // We have an lvalue with a decl. Make sure the decl is not declared
1757 // with the register storage-class specifier.
1758 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1759 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00001760 Diag(OpLoc, diag::err_typecheck_address_of,
1761 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001762 return QualType();
1763 }
1764 } else
1765 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00001766 }
1767 // If the operand has type "type", the result has type "pointer to type".
1768 return Context.getPointerType(op->getType());
1769}
1770
1771QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1772 UsualUnaryConversions(op);
1773 QualType qType = op->getType();
1774
Chris Lattner7931f4a2007-07-31 16:53:04 +00001775 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001776 // Note that per both C89 and C99, this is always legal, even
1777 // if ptype is an incomplete type or void.
1778 // It would be possible to warn about dereferencing a
1779 // void pointer, but it's completely well-defined,
1780 // and such a warning is unlikely to catch any mistakes.
1781 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001782 }
1783 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1784 qType.getAsString(), op->getSourceRange());
1785 return QualType();
1786}
1787
1788static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1789 tok::TokenKind Kind) {
1790 BinaryOperator::Opcode Opc;
1791 switch (Kind) {
1792 default: assert(0 && "Unknown binop!");
1793 case tok::star: Opc = BinaryOperator::Mul; break;
1794 case tok::slash: Opc = BinaryOperator::Div; break;
1795 case tok::percent: Opc = BinaryOperator::Rem; break;
1796 case tok::plus: Opc = BinaryOperator::Add; break;
1797 case tok::minus: Opc = BinaryOperator::Sub; break;
1798 case tok::lessless: Opc = BinaryOperator::Shl; break;
1799 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1800 case tok::lessequal: Opc = BinaryOperator::LE; break;
1801 case tok::less: Opc = BinaryOperator::LT; break;
1802 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1803 case tok::greater: Opc = BinaryOperator::GT; break;
1804 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1805 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1806 case tok::amp: Opc = BinaryOperator::And; break;
1807 case tok::caret: Opc = BinaryOperator::Xor; break;
1808 case tok::pipe: Opc = BinaryOperator::Or; break;
1809 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1810 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1811 case tok::equal: Opc = BinaryOperator::Assign; break;
1812 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1813 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1814 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1815 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1816 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1817 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1818 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1819 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1820 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1821 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1822 case tok::comma: Opc = BinaryOperator::Comma; break;
1823 }
1824 return Opc;
1825}
1826
1827static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1828 tok::TokenKind Kind) {
1829 UnaryOperator::Opcode Opc;
1830 switch (Kind) {
1831 default: assert(0 && "Unknown unary op!");
1832 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1833 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1834 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1835 case tok::star: Opc = UnaryOperator::Deref; break;
1836 case tok::plus: Opc = UnaryOperator::Plus; break;
1837 case tok::minus: Opc = UnaryOperator::Minus; break;
1838 case tok::tilde: Opc = UnaryOperator::Not; break;
1839 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1840 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1841 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1842 case tok::kw___real: Opc = UnaryOperator::Real; break;
1843 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1844 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1845 }
1846 return Opc;
1847}
1848
1849// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001850Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001851 ExprTy *LHS, ExprTy *RHS) {
1852 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1853 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1854
Steve Naroff87d58b42007-09-16 03:34:24 +00001855 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1856 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001857
1858 QualType ResultTy; // Result type of the binary operator.
1859 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1860
1861 switch (Opc) {
1862 default:
1863 assert(0 && "Unknown binary expr!");
1864 case BinaryOperator::Assign:
1865 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1866 break;
1867 case BinaryOperator::Mul:
1868 case BinaryOperator::Div:
1869 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1870 break;
1871 case BinaryOperator::Rem:
1872 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1873 break;
1874 case BinaryOperator::Add:
1875 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1876 break;
1877 case BinaryOperator::Sub:
1878 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1879 break;
1880 case BinaryOperator::Shl:
1881 case BinaryOperator::Shr:
1882 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1883 break;
1884 case BinaryOperator::LE:
1885 case BinaryOperator::LT:
1886 case BinaryOperator::GE:
1887 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001888 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001889 break;
1890 case BinaryOperator::EQ:
1891 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001892 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001893 break;
1894 case BinaryOperator::And:
1895 case BinaryOperator::Xor:
1896 case BinaryOperator::Or:
1897 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1898 break;
1899 case BinaryOperator::LAnd:
1900 case BinaryOperator::LOr:
1901 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1902 break;
1903 case BinaryOperator::MulAssign:
1904 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001905 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001906 if (!CompTy.isNull())
1907 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1908 break;
1909 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001910 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001911 if (!CompTy.isNull())
1912 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1913 break;
1914 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001915 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001916 if (!CompTy.isNull())
1917 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1918 break;
1919 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001920 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001921 if (!CompTy.isNull())
1922 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1923 break;
1924 case BinaryOperator::ShlAssign:
1925 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001926 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001927 if (!CompTy.isNull())
1928 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1929 break;
1930 case BinaryOperator::AndAssign:
1931 case BinaryOperator::XorAssign:
1932 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001933 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001934 if (!CompTy.isNull())
1935 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1936 break;
1937 case BinaryOperator::Comma:
1938 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1939 break;
1940 }
1941 if (ResultTy.isNull())
1942 return true;
1943 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001944 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001945 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001946 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001947}
1948
1949// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001950Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001951 ExprTy *input) {
1952 Expr *Input = (Expr*)input;
1953 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1954 QualType resultType;
1955 switch (Opc) {
1956 default:
1957 assert(0 && "Unimplemented unary expr!");
1958 case UnaryOperator::PreInc:
1959 case UnaryOperator::PreDec:
1960 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1961 break;
1962 case UnaryOperator::AddrOf:
1963 resultType = CheckAddressOfOperand(Input, OpLoc);
1964 break;
1965 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00001966 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00001967 resultType = CheckIndirectionOperand(Input, OpLoc);
1968 break;
1969 case UnaryOperator::Plus:
1970 case UnaryOperator::Minus:
1971 UsualUnaryConversions(Input);
1972 resultType = Input->getType();
1973 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1974 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1975 resultType.getAsString());
1976 break;
1977 case UnaryOperator::Not: // bitwise complement
1978 UsualUnaryConversions(Input);
1979 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001980 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1981 if (!resultType->isIntegerType()) {
1982 if (resultType->isComplexType())
1983 // C99 does not support '~' for complex conjugation.
1984 Diag(OpLoc, diag::ext_integer_complement_complex,
1985 resultType.getAsString());
1986 else
1987 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1988 resultType.getAsString());
1989 }
Chris Lattner4b009652007-07-25 00:24:17 +00001990 break;
1991 case UnaryOperator::LNot: // logical negation
1992 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1993 DefaultFunctionArrayConversion(Input);
1994 resultType = Input->getType();
1995 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1996 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1997 resultType.getAsString());
1998 // LNot always has type int. C99 6.5.3.3p5.
1999 resultType = Context.IntTy;
2000 break;
2001 case UnaryOperator::SizeOf:
2002 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
2003 break;
2004 case UnaryOperator::AlignOf:
2005 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
2006 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002007 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002008 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002009 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002010 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002011 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002012 resultType = Input->getType();
2013 break;
2014 }
2015 if (resultType.isNull())
2016 return true;
2017 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2018}
2019
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002020/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2021Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002022 SourceLocation LabLoc,
2023 IdentifierInfo *LabelII) {
2024 // Look up the record for this label identifier.
2025 LabelStmt *&LabelDecl = LabelMap[LabelII];
2026
2027 // If we haven't seen this label yet, create a forward reference.
2028 if (LabelDecl == 0)
2029 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2030
2031 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002032 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2033 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002034}
2035
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002036Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002037 SourceLocation RPLoc) { // "({..})"
2038 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2039 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2040 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2041
2042 // FIXME: there are a variety of strange constraints to enforce here, for
2043 // example, it is not possible to goto into a stmt expression apparently.
2044 // More semantic analysis is needed.
2045
2046 // FIXME: the last statement in the compount stmt has its value used. We
2047 // should not warn about it being unused.
2048
2049 // If there are sub stmts in the compound stmt, take the type of the last one
2050 // as the type of the stmtexpr.
2051 QualType Ty = Context.VoidTy;
2052
2053 if (!Compound->body_empty())
2054 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
2055 Ty = LastExpr->getType();
2056
2057 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2058}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002059
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002060Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002061 SourceLocation TypeLoc,
2062 TypeTy *argty,
2063 OffsetOfComponent *CompPtr,
2064 unsigned NumComponents,
2065 SourceLocation RPLoc) {
2066 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2067 assert(!ArgTy.isNull() && "Missing type argument!");
2068
2069 // We must have at least one component that refers to the type, and the first
2070 // one is known to be a field designator. Verify that the ArgTy represents
2071 // a struct/union/class.
2072 if (!ArgTy->isRecordType())
2073 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2074
2075 // Otherwise, create a compound literal expression as the base, and
2076 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002077 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002078
Chris Lattnerb37522e2007-08-31 21:49:13 +00002079 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2080 // GCC extension, diagnose them.
2081 if (NumComponents != 1)
2082 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2083 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2084
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002085 for (unsigned i = 0; i != NumComponents; ++i) {
2086 const OffsetOfComponent &OC = CompPtr[i];
2087 if (OC.isBrackets) {
2088 // Offset of an array sub-field. TODO: Should we allow vector elements?
2089 const ArrayType *AT = Res->getType()->getAsArrayType();
2090 if (!AT) {
2091 delete Res;
2092 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2093 Res->getType().getAsString());
2094 }
2095
Chris Lattner2af6a802007-08-30 17:59:59 +00002096 // FIXME: C++: Verify that operator[] isn't overloaded.
2097
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002098 // C99 6.5.2.1p1
2099 Expr *Idx = static_cast<Expr*>(OC.U.E);
2100 if (!Idx->getType()->isIntegerType())
2101 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2102 Idx->getSourceRange());
2103
2104 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2105 continue;
2106 }
2107
2108 const RecordType *RC = Res->getType()->getAsRecordType();
2109 if (!RC) {
2110 delete Res;
2111 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2112 Res->getType().getAsString());
2113 }
2114
2115 // Get the decl corresponding to this.
2116 RecordDecl *RD = RC->getDecl();
2117 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2118 if (!MemberDecl)
2119 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2120 OC.U.IdentInfo->getName(),
2121 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002122
2123 // FIXME: C++: Verify that MemberDecl isn't a static field.
2124 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002125 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2126 // matter here.
2127 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002128 }
2129
2130 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2131 BuiltinLoc);
2132}
2133
2134
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002135Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002136 TypeTy *arg1, TypeTy *arg2,
2137 SourceLocation RPLoc) {
2138 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2139 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2140
2141 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2142
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002143 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002144}
2145
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002146Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002147 ExprTy *expr1, ExprTy *expr2,
2148 SourceLocation RPLoc) {
2149 Expr *CondExpr = static_cast<Expr*>(cond);
2150 Expr *LHSExpr = static_cast<Expr*>(expr1);
2151 Expr *RHSExpr = static_cast<Expr*>(expr2);
2152
2153 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2154
2155 // The conditional expression is required to be a constant expression.
2156 llvm::APSInt condEval(32);
2157 SourceLocation ExpLoc;
2158 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2159 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2160 CondExpr->getSourceRange());
2161
2162 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2163 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2164 RHSExpr->getType();
2165 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2166}
2167
Nate Begemanbd881ef2008-01-30 20:50:20 +00002168/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002169/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002170/// The number of arguments has already been validated to match the number of
2171/// arguments in FnType.
2172static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002173 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00002174 for (unsigned i = 0; i != NumParams; ++i) {
2175 QualType ExprTy = Args[i]->getType().getCanonicalType();
2176 QualType ParmTy = FnType->getArgType(i).getCanonicalType();
2177
2178 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002179 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00002180 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002181 return true;
2182}
2183
2184Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2185 SourceLocation *CommaLocs,
2186 SourceLocation BuiltinLoc,
2187 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002188 // __builtin_overload requires at least 2 arguments
2189 if (NumArgs < 2)
2190 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2191 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002192
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002193 // The first argument is required to be a constant expression. It tells us
2194 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002195 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002196 Expr *NParamsExpr = Args[0];
2197 llvm::APSInt constEval(32);
2198 SourceLocation ExpLoc;
2199 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2200 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2201 NParamsExpr->getSourceRange());
2202
2203 // Verify that the number of parameters is > 0
2204 unsigned NumParams = constEval.getZExtValue();
2205 if (NumParams == 0)
2206 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2207 NParamsExpr->getSourceRange());
2208 // Verify that we have at least 1 + NumParams arguments to the builtin.
2209 if ((NumParams + 1) > NumArgs)
2210 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2211 SourceRange(BuiltinLoc, RParenLoc));
2212
2213 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002214 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002215 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002216 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2217 // UsualUnaryConversions will convert the function DeclRefExpr into a
2218 // pointer to function.
2219 Expr *Fn = UsualUnaryConversions(Args[i]);
2220 FunctionTypeProto *FnType = 0;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002221 if (const PointerType *PT = Fn->getType()->getAsPointerType()) {
2222 QualType PointeeType = PT->getPointeeType().getCanonicalType();
2223 FnType = dyn_cast<FunctionTypeProto>(PointeeType);
2224 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002225
2226 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2227 // parameters, and the number of parameters must match the value passed to
2228 // the builtin.
2229 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002230 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2231 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002232
2233 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002234 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002235 // If they match, return a new OverloadExpr.
Nate Begemanc6078c92008-01-31 05:38:29 +00002236 if (ExprsMatchFnType(Args+1, FnType)) {
2237 if (OE)
2238 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2239 OE->getFn()->getSourceRange());
2240 // Remember our match, and continue processing the remaining arguments
2241 // to catch any errors.
2242 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2243 BuiltinLoc, RParenLoc);
2244 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002245 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002246 // Return the newly created OverloadExpr node, if we succeded in matching
2247 // exactly one of the candidate functions.
2248 if (OE)
2249 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002250
2251 // If we didn't find a matching function Expr in the __builtin_overload list
2252 // the return an error.
2253 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002254 for (unsigned i = 0; i != NumParams; ++i) {
2255 if (i != 0) typeNames += ", ";
2256 typeNames += Args[i+1]->getType().getAsString();
2257 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002258
2259 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2260 SourceRange(BuiltinLoc, RParenLoc));
2261}
2262
Anders Carlsson36760332007-10-15 20:28:48 +00002263Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2264 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002265 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002266 Expr *E = static_cast<Expr*>(expr);
2267 QualType T = QualType::getFromOpaquePtr(type);
2268
2269 InitBuiltinVaListType();
2270
Chris Lattner005ed752008-01-04 18:04:52 +00002271 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2272 != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002273 return Diag(E->getLocStart(),
2274 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2275 E->getType().getAsString(),
2276 E->getSourceRange());
2277
2278 // FIXME: Warn if a non-POD type is passed in.
2279
2280 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2281}
2282
Chris Lattner005ed752008-01-04 18:04:52 +00002283bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2284 SourceLocation Loc,
2285 QualType DstType, QualType SrcType,
2286 Expr *SrcExpr, const char *Flavor) {
2287 // Decode the result (notice that AST's are still created for extensions).
2288 bool isInvalid = false;
2289 unsigned DiagKind;
2290 switch (ConvTy) {
2291 default: assert(0 && "Unknown conversion type");
2292 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002293 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002294 DiagKind = diag::ext_typecheck_convert_pointer_int;
2295 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002296 case IntToPointer:
2297 DiagKind = diag::ext_typecheck_convert_int_pointer;
2298 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002299 case IncompatiblePointer:
2300 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2301 break;
2302 case FunctionVoidPointer:
2303 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2304 break;
2305 case CompatiblePointerDiscardsQualifiers:
2306 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2307 break;
2308 case Incompatible:
2309 DiagKind = diag::err_typecheck_convert_incompatible;
2310 isInvalid = true;
2311 break;
2312 }
2313
2314 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2315 SrcExpr->getSourceRange());
2316 return isInvalid;
2317}
2318
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002319
2320