blob: fd02443d80f5b747a4037ca3013f1e5b5f3c2818 [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());
Chris Lattner4b009652007-07-25 00:24:17 +0000131
132 assert(0 && "Invalid decl");
133 abort();
134}
135
Steve Naroff87d58b42007-09-16 03:34:24 +0000136Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000137 tok::TokenKind Kind) {
138 PreDefinedExpr::IdentType IT;
139
140 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000141 default: assert(0 && "Unknown simple primary expr!");
142 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
143 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
144 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000145 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000146
147 // Verify that this is in a function context.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000148 if (CurFunctionDecl == 0 && CurMethodDecl == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000149 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000150
Chris Lattner7e637512008-01-12 08:14:25 +0000151 // Pre-defined identifiers are of type char[x], where x is the length of the
152 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000153 unsigned Length;
154 if (CurFunctionDecl)
155 Length = CurFunctionDecl->getIdentifier()->getLength();
156 else
Fariborz Jahaniandcecd5c2008-01-17 17:37:26 +0000157 Length = CurMethodDecl->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000158
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000159 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000160 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000161 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner7e637512008-01-12 08:14:25 +0000162 return new PreDefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000163}
164
Steve Naroff87d58b42007-09-16 03:34:24 +0000165Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000166 llvm::SmallString<16> CharBuffer;
167 CharBuffer.resize(Tok.getLength());
168 const char *ThisTokBegin = &CharBuffer[0];
169 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
170
171 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
172 Tok.getLocation(), PP);
173 if (Literal.hadError())
174 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000175
176 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
177
178 return new CharacterLiteral(Literal.getValue(), type, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000179}
180
Steve Naroff87d58b42007-09-16 03:34:24 +0000181Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000182 // fast path for a single digit (which is quite common). A single digit
183 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
184 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000185 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000186
Chris Lattner8cd0e932008-03-05 18:54:05 +0000187 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000188 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000189 Context.IntTy,
190 Tok.getLocation()));
191 }
192 llvm::SmallString<512> IntegerBuffer;
193 IntegerBuffer.resize(Tok.getLength());
194 const char *ThisTokBegin = &IntegerBuffer[0];
195
196 // Get the spelling of the token, which eliminates trigraphs, etc.
197 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
198 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
199 Tok.getLocation(), PP);
200 if (Literal.hadError)
201 return ExprResult(true);
202
Chris Lattner1de66eb2007-08-26 03:42:43 +0000203 Expr *Res;
204
205 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000206 QualType Ty;
207 const llvm::fltSemantics *Format;
Chris Lattner858eece2007-09-22 18:29:59 +0000208
209 if (Literal.isFloat) {
210 Ty = Context.FloatTy;
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000211 Format = Context.Target.getFloatFormat();
212 } else if (!Literal.isLong) {
Chris Lattner858eece2007-09-22 18:29:59 +0000213 Ty = Context.DoubleTy;
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000214 Format = Context.Target.getDoubleFormat();
215 } else {
216 Ty = Context.LongDoubleTy;
217 Format = Context.Target.getLongDoubleFormat();
Chris Lattner858eece2007-09-22 18:29:59 +0000218 }
219
Ted Kremenekddedbe22007-11-29 00:56:49 +0000220 // isExact will be set by GetFloatValue().
221 bool isExact = false;
222
223 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
224 Ty, Tok.getLocation());
225
Chris Lattner1de66eb2007-08-26 03:42:43 +0000226 } else if (!Literal.isIntegerLiteral()) {
227 return ExprResult(true);
228 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000229 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000230
Neil Booth7421e9c2007-08-29 22:00:19 +0000231 // long long is a C99 feature.
232 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000233 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000234 Diag(Tok.getLocation(), diag::ext_longlong);
235
Chris Lattner4b009652007-07-25 00:24:17 +0000236 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000237 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000238
239 if (Literal.GetIntegerValue(ResultVal)) {
240 // If this value didn't fit into uintmax_t, warn and force to ull.
241 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000242 Ty = Context.UnsignedLongLongTy;
243 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000244 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000245 } else {
246 // If this value fits into a ULL, try to figure out what else it fits into
247 // according to the rules of C99 6.4.4.1p5.
248
249 // Octal, Hexadecimal, and integers with a U suffix are allowed to
250 // be an unsigned int.
251 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
252
253 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000254 if (!Literal.isLong && !Literal.isLongLong) {
255 // Are int/unsigned possibilities?
Chris Lattner8cd0e932008-03-05 18:54:05 +0000256 unsigned IntSize =
257 static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner4b009652007-07-25 00:24:17 +0000258 // Does it fit in a unsigned int?
259 if (ResultVal.isIntN(IntSize)) {
260 // Does it fit in a signed int?
261 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000262 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000263 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000264 Ty = Context.UnsignedIntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000265 }
266
Chris Lattner48d7f382008-04-02 04:24:33 +0000267 if (!Ty.isNull())
Chris Lattner4b009652007-07-25 00:24:17 +0000268 ResultVal.trunc(IntSize);
269 }
270
271 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000272 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000273 unsigned LongSize =
274 static_cast<unsigned>(Context.getTypeSize(Context.LongTy));
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 Lattner4b009652007-07-25 00:24:17 +0000283 }
Chris Lattner48d7f382008-04-02 04:24:33 +0000284 if (!Ty.isNull())
Chris Lattner4b009652007-07-25 00:24:17 +0000285 ResultVal.trunc(LongSize);
286 }
287
288 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000289 if (Ty.isNull()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000290 unsigned LongLongSize =
291 static_cast<unsigned>(Context.getTypeSize(Context.LongLongTy));
Chris Lattner4b009652007-07-25 00:24:17 +0000292
293 // Does it fit in a unsigned long long?
294 if (ResultVal.isIntN(LongLongSize)) {
295 // Does it fit in a signed long long?
296 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000297 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000298 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000299 Ty = Context.UnsignedLongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000300 }
301 }
302
303 // If we still couldn't decide a type, we probably have something that
304 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000305 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000306 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000307 Ty = Context.UnsignedLongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000308 }
309 }
310
Chris Lattner48d7f382008-04-02 04:24:33 +0000311 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000312 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000313
314 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
315 if (Literal.isImaginary)
316 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
317
318 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000319}
320
Steve Naroff87d58b42007-09-16 03:34:24 +0000321Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000322 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000323 Expr *E = (Expr *)Val;
324 assert((E != 0) && "ActOnParenExpr() missing expr");
325 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000326}
327
328/// The UsualUnaryConversions() function is *not* called by this routine.
329/// See C99 6.3.2.1p[2-4] for more details.
330QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
331 SourceLocation OpLoc, bool isSizeof) {
332 // C99 6.5.3.4p1:
333 if (isa<FunctionType>(exprType) && isSizeof)
334 // alignof(function) is allowed.
335 Diag(OpLoc, diag::ext_sizeof_function_type);
336 else if (exprType->isVoidType())
337 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
338 else if (exprType->isIncompleteType()) {
339 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
340 diag::err_alignof_incomplete_type,
341 exprType.getAsString());
342 return QualType(); // error
343 }
344 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
345 return Context.getSizeType();
346}
347
348Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000349ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000350 SourceLocation LPLoc, TypeTy *Ty,
351 SourceLocation RPLoc) {
352 // If error parsing type, ignore.
353 if (Ty == 0) return true;
354
355 // Verify that this is a valid expression.
356 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
357
358 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
359
360 if (resultType.isNull())
361 return true;
362 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
363}
364
Chris Lattner5110ad52007-08-24 21:41:10 +0000365QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000366 DefaultFunctionArrayConversion(V);
367
Chris Lattnera16e42d2007-08-26 05:39:26 +0000368 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000369 if (const ComplexType *CT = V->getType()->getAsComplexType())
370 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000371
372 // Otherwise they pass through real integer and floating point types here.
373 if (V->getType()->isArithmeticType())
374 return V->getType();
375
376 // Reject anything else.
377 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
378 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000379}
380
381
Chris Lattner4b009652007-07-25 00:24:17 +0000382
Steve Naroff87d58b42007-09-16 03:34:24 +0000383Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000384 tok::TokenKind Kind,
385 ExprTy *Input) {
386 UnaryOperator::Opcode Opc;
387 switch (Kind) {
388 default: assert(0 && "Unknown unary op!");
389 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
390 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
391 }
392 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
393 if (result.isNull())
394 return true;
395 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
396}
397
398Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000399ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000400 ExprTy *Idx, SourceLocation RLoc) {
401 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
402
403 // Perform default conversions.
404 DefaultFunctionArrayConversion(LHSExp);
405 DefaultFunctionArrayConversion(RHSExp);
406
407 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
408
409 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000410 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000411 // in the subscript position. As a result, we need to derive the array base
412 // and index from the expression types.
413 Expr *BaseExpr, *IndexExpr;
414 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000415 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000416 BaseExpr = LHSExp;
417 IndexExpr = RHSExp;
418 // FIXME: need to deal with const...
419 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000420 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000421 // Handle the uncommon case of "123[Ptr]".
422 BaseExpr = RHSExp;
423 IndexExpr = LHSExp;
424 // FIXME: need to deal with const...
425 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000426 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
427 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000428 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000429
430 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman506806b2008-02-19 01:11:03 +0000431 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000432 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000433 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000434 // FIXME: need to deal with const...
435 ResultType = VTy->getElementType();
436 } else {
437 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
438 RHSExp->getSourceRange());
439 }
440 // C99 6.5.2.1p1
441 if (!IndexExpr->getType()->isIntegerType())
442 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
443 IndexExpr->getSourceRange());
444
445 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
446 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000447 // void (*)(int)) and pointers to incomplete types. Functions are not
448 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000449 if (!ResultType->isObjectType())
450 return Diag(BaseExpr->getLocStart(),
451 diag::err_typecheck_subscript_not_object,
452 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
453
454 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
455}
456
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000457QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000458CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000459 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000460 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000461
462 // The vector accessor can't exceed the number of elements.
463 const char *compStr = CompName.getName();
464 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000465 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000466 baseType.getAsString(), SourceRange(CompLoc));
467 return QualType();
468 }
469 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000470 if (vecType->getPointAccessorIdx(*compStr) != -1) {
471 do
472 compStr++;
473 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
474 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
475 do
476 compStr++;
477 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
478 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
479 do
480 compStr++;
481 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
482 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000483
484 if (*compStr) {
485 // We didn't get to the end of the string. This means the component names
486 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000487 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000488 std::string(compStr,compStr+1), SourceRange(CompLoc));
489 return QualType();
490 }
491 // Each component accessor can't exceed the vector type.
492 compStr = CompName.getName();
493 while (*compStr) {
494 if (vecType->isAccessorWithinNumElements(*compStr))
495 compStr++;
496 else
497 break;
498 }
499 if (*compStr) {
500 // We didn't get to the end of the string. This means a component accessor
501 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000502 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000503 baseType.getAsString(), SourceRange(CompLoc));
504 return QualType();
505 }
506 // The component accessor looks fine - now we need to compute the actual type.
507 // The vector type is implied by the component accessor. For example,
508 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
509 unsigned CompSize = strlen(CompName.getName());
510 if (CompSize == 1)
511 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000512
Nate Begemanaf6ed502008-04-18 23:10:10 +0000513 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000514 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000515 // diagostics look bad. We want extended vector types to appear built-in.
516 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
517 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
518 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000519 }
520 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000521}
522
Chris Lattner4b009652007-07-25 00:24:17 +0000523Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000524ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000525 tok::TokenKind OpKind, SourceLocation MemberLoc,
526 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000527 Expr *BaseExpr = static_cast<Expr *>(Base);
528 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000529
530 // Perform default conversions.
531 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000532
Steve Naroff2cb66382007-07-26 03:11:44 +0000533 QualType BaseType = BaseExpr->getType();
534 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000535
Chris Lattner4b009652007-07-25 00:24:17 +0000536 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000537 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000538 BaseType = PT->getPointeeType();
539 else
540 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
541 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000542 }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000543 // The base type is either a record or an ExtVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000544 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000545 RecordDecl *RDecl = RTy->getDecl();
546 if (RTy->isIncompleteType())
547 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
548 BaseExpr->getSourceRange());
549 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000550 FieldDecl *MemberDecl = RDecl->getMember(&Member);
551 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000552 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
553 SourceRange(MemberLoc));
Eli Friedman76b49832008-02-06 22:48:16 +0000554
555 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000556 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000557 QualType MemberType = MemberDecl->getType();
558 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000559 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000560 MemberType = MemberType.getQualifiedType(combinedQualifiers);
561
562 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl,
563 MemberLoc, MemberType);
Nate Begemanaf6ed502008-04-18 23:10:10 +0000564 } else if (BaseType->isExtVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000565 // Component access limited to variables (reject vec4.rg.g).
Nate Begeman78a2a312008-03-17 17:22:18 +0000566 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000567 return Diag(OpLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000568 SourceRange(MemberLoc));
Nate Begemanaf6ed502008-04-18 23:10:10 +0000569 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000570 if (ret.isNull())
571 return true;
Nate Begemanaf6ed502008-04-18 23:10:10 +0000572 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Ted Kremenek42730c52008-01-07 19:49:32 +0000573 } else if (BaseType->isObjCInterfaceType()) {
574 ObjCInterfaceDecl *IFace;
575 if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
576 IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000577 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000578 IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
579 ObjCInterfaceDecl *clsDeclared;
580 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000581 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
582 OpKind==tok::arrow);
583 }
584 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
585 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000586}
587
Steve Naroff87d58b42007-09-16 03:34:24 +0000588/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000589/// This provides the location of the left/right parens and a list of comma
590/// locations.
591Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000592ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000593 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +0000594 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
595 Expr *Fn = static_cast<Expr *>(fn);
596 Expr **Args = reinterpret_cast<Expr**>(args);
597 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +0000598 FunctionDecl *FDecl = NULL;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000599
600 // Promote the function operand.
601 UsualUnaryConversions(Fn);
602
603 // If we're directly calling a function, get the declaration for
604 // that function.
605 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
606 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
607 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
608
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000609 // Make the call expr early, before semantic checks. This guarantees cleanup
610 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +0000611 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000612 Context.BoolTy, RParenLoc));
613
Chris Lattner4b009652007-07-25 00:24:17 +0000614 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
615 // type pointer to function".
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000616 const PointerType *PT = Fn->getType()->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000617 if (PT == 0)
618 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
619 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000620 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
621 if (FuncT == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000622 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
623 SourceRange(Fn->getLocStart(), RParenLoc));
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000624
625 // We know the result type of the call, set it.
626 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +0000627
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000628 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000629 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
630 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000631 unsigned NumArgsInProto = Proto->getNumArgs();
632 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +0000633
Chris Lattner3e254fb2008-04-08 04:40:51 +0000634 // If too few arguments are available (and we don't have default
635 // arguments for the remaining parameters), don't make the call.
636 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +0000637 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000638 // Use default arguments for missing arguments
639 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +0000640 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000641 } else
642 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
643 Fn->getSourceRange());
644 }
645
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000646 // If too many are passed and not variadic, error on the extras and drop
647 // them.
648 if (NumArgs > NumArgsInProto) {
649 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000650 Diag(Args[NumArgsInProto]->getLocStart(),
651 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
652 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000653 Args[NumArgs-1]->getLocEnd()));
654 // This deletes the extra arguments.
655 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +0000656 }
657 NumArgsToCheck = NumArgsInProto;
658 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000659
Chris Lattner4b009652007-07-25 00:24:17 +0000660 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000661 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +0000662 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000663
664 Expr *Arg;
665 if (i < NumArgs)
666 Arg = Args[i];
667 else
668 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +0000669 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000670
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000671 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner005ed752008-01-04 18:04:52 +0000672 AssignConvertType ConvTy =
673 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000674 TheCall->setArg(i, Arg);
675
Chris Lattner005ed752008-01-04 18:04:52 +0000676 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
677 ArgType, Arg, "passing"))
678 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000679 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000680
681 // If this is a variadic call, handle args passed through "...".
682 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +0000683 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000684 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
685 Expr *Arg = Args[i];
686 DefaultArgumentPromotion(Arg);
687 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000688 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000689 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000690 } else {
691 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
692
Steve Naroffdb65e052007-08-28 23:30:39 +0000693 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000694 for (unsigned i = 0; i != NumArgs; i++) {
695 Expr *Arg = Args[i];
696 DefaultArgumentPromotion(Arg);
697 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +0000698 }
Chris Lattner4b009652007-07-25 00:24:17 +0000699 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000700
Chris Lattner2e64c072007-08-10 20:18:51 +0000701 // Do special checking on direct calls to functions.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000702 if (FDecl && CheckFunctionCall(FDecl, TheCall.get()))
703 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000704
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000705 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000706}
707
708Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000709ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000710 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000711 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000712 QualType literalType = QualType::getFromOpaquePtr(Ty);
713 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000714 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000715 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000716
Steve Naroffcb69fb72007-12-10 22:44:33 +0000717 // FIXME: add more semantic analysis (C99 6.5.2.5).
Steve Narofff0b23542008-01-10 22:15:12 +0000718 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +0000719 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +0000720
721 bool isFileScope = !CurFunctionDecl && !CurMethodDecl;
722 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +0000723 if (CheckForConstantInitializer(literalExpr, literalType))
724 return true;
725 }
Steve Naroffbe37fc02008-01-14 18:19:28 +0000726 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000727}
728
729Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000730ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000731 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000732 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000733
Steve Naroff0acc9c92007-09-15 18:49:24 +0000734 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000735 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000736
Chris Lattner48d7f382008-04-02 04:24:33 +0000737 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
738 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
739 return E;
Chris Lattner4b009652007-07-25 00:24:17 +0000740}
741
Chris Lattnerd1f26b32007-12-20 00:44:32 +0000742bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000743 assert(VectorTy->isVectorType() && "Not a vector type!");
744
745 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000746 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000747 return Diag(R.getBegin(),
748 Ty->isVectorType() ?
749 diag::err_invalid_conversion_between_vectors :
750 diag::err_invalid_conversion_between_vector_and_integer,
751 VectorTy.getAsString().c_str(),
752 Ty.getAsString().c_str(), R);
753 } else
754 return Diag(R.getBegin(),
755 diag::err_invalid_conversion_between_vector_and_scalar,
756 VectorTy.getAsString().c_str(),
757 Ty.getAsString().c_str(), R);
758
759 return false;
760}
761
Chris Lattner4b009652007-07-25 00:24:17 +0000762Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000763ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000764 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000765 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000766
767 Expr *castExpr = static_cast<Expr*>(Op);
768 QualType castType = QualType::getFromOpaquePtr(Ty);
769
Steve Naroff68adb482007-08-31 00:32:44 +0000770 UsualUnaryConversions(castExpr);
771
Chris Lattner4b009652007-07-25 00:24:17 +0000772 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
773 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000774 if (!castType->isVoidType()) { // Cast to void allows any expr type.
Steve Narofff459ee52008-01-24 22:55:05 +0000775 if (!castType->isScalarType() && !castType->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000776 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
777 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Steve Narofff459ee52008-01-24 22:55:05 +0000778 if (!castExpr->getType()->isScalarType() &&
779 !castExpr->getType()->isVectorType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000780 return Diag(castExpr->getLocStart(),
781 diag::err_typecheck_expect_scalar_operand,
782 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000783
784 if (castExpr->getType()->isVectorType()) {
785 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
786 castExpr->getType(), castType))
787 return true;
788 } else if (castType->isVectorType()) {
789 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
790 castType, castExpr->getType()))
791 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000792 }
Chris Lattner4b009652007-07-25 00:24:17 +0000793 }
794 return new CastExpr(castType, castExpr, LParenLoc);
795}
796
Chris Lattner98a425c2007-11-26 01:40:58 +0000797/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
798/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000799inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
800 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
801 UsualUnaryConversions(cond);
802 UsualUnaryConversions(lex);
803 UsualUnaryConversions(rex);
804 QualType condT = cond->getType();
805 QualType lexT = lex->getType();
806 QualType rexT = rex->getType();
807
808 // first, check the condition.
809 if (!condT->isScalarType()) { // C99 6.5.15p2
810 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
811 condT.getAsString());
812 return QualType();
813 }
Chris Lattner992ae932008-01-06 22:42:25 +0000814
815 // Now check the two expressions.
816
817 // If both operands have arithmetic type, do the usual arithmetic conversions
818 // to find a common type: C99 6.5.15p3,5.
819 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000820 UsualArithmeticConversions(lex, rex);
821 return lex->getType();
822 }
Chris Lattner992ae932008-01-06 22:42:25 +0000823
824 // If both operands are the same structure or union type, the result is that
825 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000826 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +0000827 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +0000828 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +0000829 // "If both the operands have structure or union type, the result has
830 // that type." This implies that CV qualifiers are dropped.
831 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000832 }
Chris Lattner992ae932008-01-06 22:42:25 +0000833
834 // C99 6.5.15p5: "If both operands have void type, the result has void type."
835 if (lexT->isVoidType() && rexT->isVoidType())
836 return lexT.getUnqualifiedType();
Steve Naroff12ebf272008-01-08 01:11:38 +0000837
838 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
839 // the type of the other operand."
840 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000841 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000842 return lexT;
843 }
844 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +0000845 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +0000846 return rexT;
847 }
Chris Lattner0ac51632008-01-06 22:50:31 +0000848 // Handle the case where both operands are pointers before we handle null
849 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +0000850 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
851 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
852 // get the "pointed to" types
853 QualType lhptee = LHSPT->getPointeeType();
854 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000855
Chris Lattner71225142007-07-31 21:27:01 +0000856 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
857 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +0000858 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +0000859 // Figure out necessary qualifiers (C99 6.5.15p6)
860 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000861 QualType destType = Context.getPointerType(destPointee);
862 ImpCastExprToType(lex, destType); // add qualifiers if necessary
863 ImpCastExprToType(rex, destType); // promote to void*
864 return destType;
865 }
Chris Lattner9db553e2008-04-02 06:59:01 +0000866 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +0000867 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +0000868 QualType destType = Context.getPointerType(destPointee);
869 ImpCastExprToType(lex, destType); // add qualifiers if necessary
870 ImpCastExprToType(rex, destType); // promote to void*
871 return destType;
872 }
Chris Lattner4b009652007-07-25 00:24:17 +0000873
Steve Naroff85f0dc52007-10-15 20:41:53 +0000874 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
875 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +0000876 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +0000877 lexT.getAsString(), rexT.getAsString(),
878 lex->getSourceRange(), rex->getSourceRange());
Eli Friedman33284862008-01-30 17:02:03 +0000879 // In this situation, we assume void* type. No especially good
880 // reason, but this is what gcc does, and we do have to pick
881 // to get a consistent AST.
882 QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
883 ImpCastExprToType(lex, voidPtrTy);
884 ImpCastExprToType(rex, voidPtrTy);
885 return voidPtrTy;
Chris Lattner71225142007-07-31 21:27:01 +0000886 }
887 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000888 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
889 // differently qualified versions of compatible types, the result type is
890 // a pointer to an appropriately qualified version of the *composite*
891 // type.
Chris Lattner0ac51632008-01-06 22:50:31 +0000892 // FIXME: Need to return the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +0000893 // FIXME: Need to add qualifiers
Chris Lattner0ac51632008-01-06 22:50:31 +0000894 return lexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000895 }
Chris Lattner4b009652007-07-25 00:24:17 +0000896 }
Chris Lattner71225142007-07-31 21:27:01 +0000897
Chris Lattner992ae932008-01-06 22:42:25 +0000898 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +0000899 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
900 lexT.getAsString(), rexT.getAsString(),
901 lex->getSourceRange(), rex->getSourceRange());
902 return QualType();
903}
904
Steve Naroff87d58b42007-09-16 03:34:24 +0000905/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000906/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000907Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000908 SourceLocation ColonLoc,
909 ExprTy *Cond, ExprTy *LHS,
910 ExprTy *RHS) {
911 Expr *CondExpr = (Expr *) Cond;
912 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000913
914 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
915 // was the condition.
916 bool isLHSNull = LHSExpr == 0;
917 if (isLHSNull)
918 LHSExpr = CondExpr;
919
Chris Lattner4b009652007-07-25 00:24:17 +0000920 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
921 RHSExpr, QuestionLoc);
922 if (result.isNull())
923 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000924 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
925 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000926}
927
Steve Naroffdb65e052007-08-28 23:30:39 +0000928/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Steve Naroffbbaed752008-01-29 02:42:22 +0000929/// do not have a prototype. Arguments that have type float are promoted to
930/// double. All other argument types are converted by UsualUnaryConversions().
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000931void Sema::DefaultArgumentPromotion(Expr *&Expr) {
932 QualType Ty = Expr->getType();
933 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Steve Naroffdb65e052007-08-28 23:30:39 +0000934
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000935 if (Ty == Context.FloatTy)
Chris Lattnere992d6c2008-01-16 19:17:22 +0000936 ImpCastExprToType(Expr, Context.DoubleTy);
Steve Naroffbbaed752008-01-29 02:42:22 +0000937 else
938 UsualUnaryConversions(Expr);
Steve Naroffdb65e052007-08-28 23:30:39 +0000939}
940
Chris Lattner4b009652007-07-25 00:24:17 +0000941/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Chris Lattner48d7f382008-04-02 04:24:33 +0000942void Sema::DefaultFunctionArrayConversion(Expr *&E) {
943 QualType Ty = E->getType();
944 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000945
Chris Lattner48d7f382008-04-02 04:24:33 +0000946 if (const ReferenceType *ref = Ty->getAsReferenceType()) {
Chris Lattnera05f7d22008-04-02 17:45:06 +0000947 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
Chris Lattner48d7f382008-04-02 04:24:33 +0000948 Ty = E->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000949 }
Chris Lattner48d7f382008-04-02 04:24:33 +0000950 if (Ty->isFunctionType())
951 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner19eb97e2008-04-02 05:18:44 +0000952 else if (Ty->isArrayType())
953 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
Chris Lattner4b009652007-07-25 00:24:17 +0000954}
955
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000956/// UsualUnaryConversions - Performs various conversions that are common to most
Chris Lattner4b009652007-07-25 00:24:17 +0000957/// operators (C99 6.3). The conversions of array and function types are
958/// sometimes surpressed. For example, the array->pointer conversion doesn't
959/// apply if the array is an argument to the sizeof or address (&) operators.
960/// In these instances, this routine should *not* be called.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000961Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
962 QualType Ty = Expr->getType();
963 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000964
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000965 if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
Chris Lattnera05f7d22008-04-02 17:45:06 +0000966 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000967 Ty = Expr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000968 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000969 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
Chris Lattnere992d6c2008-01-16 19:17:22 +0000970 ImpCastExprToType(Expr, Context.IntTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000971 else
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000972 DefaultFunctionArrayConversion(Expr);
973
974 return Expr;
Chris Lattner4b009652007-07-25 00:24:17 +0000975}
976
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000977/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000978/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
979/// routine returns the first non-arithmetic type found. The client is
980/// responsible for emitting appropriate error diagnostics.
Chris Lattner48d7f382008-04-02 04:24:33 +0000981/// FIXME: verify the conversion rules for "complex int" are consistent with
982/// GCC.
Steve Naroff8f708362007-08-24 19:07:16 +0000983QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
984 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000985 if (!isCompAssign) {
986 UsualUnaryConversions(lhsExpr);
987 UsualUnaryConversions(rhsExpr);
988 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000989 // For conversion purposes, we ignore any qualifiers.
990 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000991 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
992 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000993
994 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000995 if (lhs == rhs)
996 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000997
998 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
999 // The caller can deal with this (e.g. pointer + int).
1000 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001001 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001002
1003 // At this point, we have two different arithmetic types.
1004
1005 // Handle complex types first (C99 6.3.1.8p1).
1006 if (lhs->isComplexType() || rhs->isComplexType()) {
Steve Naroff43001212008-01-15 19:36:10 +00001007 // if we have an integer operand, the result is the complex type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001008 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001009 // convert the rhs to the lhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001010 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001011 return lhs;
Steve Naroff43001212008-01-15 19:36:10 +00001012 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001013 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001014 // convert the lhs to the rhs complex type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001015 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001016 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001017 }
Steve Naroff3cf497f2007-08-27 01:27:54 +00001018 // This handles complex/complex, complex/float, or float/complex.
1019 // When both operands are complex, the shorter operand is converted to the
1020 // type of the longer, and that is the type of the result. This corresponds
1021 // to what is done when combining two real floating-point operands.
1022 // The fun begins when size promotion occur across type domains.
1023 // From H&S 6.3.4: When one operand is complex and the other is a real
1024 // floating-point type, the less precise type is converted, within it's
1025 // real or complex domain, to the precision of the other type. For example,
1026 // when combining a "long double" with a "double _Complex", the
1027 // "double _Complex" is promoted to "long double _Complex".
Chris Lattnerd7135b42008-04-06 23:38:49 +00001028 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Naroff45fc9822007-08-27 15:30:22 +00001029
1030 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +00001031 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
1032 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001033 ImpCastExprToType(rhsExpr, rhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001034 } else if (result < 0) { // The right side is bigger, convert lhs.
1035 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
1036 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001037 ImpCastExprToType(lhsExpr, lhs);
Steve Naroff3b565d62007-08-27 21:32:55 +00001038 }
1039 // At this point, lhs and rhs have the same rank/size. Now, make sure the
1040 // domains match. This is a requirement for our implementation, C99
1041 // does not require this promotion.
1042 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1043 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001044 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001045 ImpCastExprToType(lhsExpr, rhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001046 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001047 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001048 if (!isCompAssign)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001049 ImpCastExprToType(rhsExpr, lhs);
Steve Naroff3b6157f2007-08-27 21:43:43 +00001050 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001051 }
Chris Lattner4b009652007-07-25 00:24:17 +00001052 }
Steve Naroff3b6157f2007-08-27 21:43:43 +00001053 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +00001054 }
1055 // Now handle "real" floating types (i.e. float, double, long double).
1056 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1057 // if we have an integer operand, the result is the real floating type.
Steve Naroffe8419ca2008-01-15 22:21:49 +00001058 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001059 // convert rhs to the lhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001060 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001061 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001062 }
Steve Naroffe8419ca2008-01-15 22:21:49 +00001063 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001064 // convert lhs to the rhs floating point type.
Chris Lattnere992d6c2008-01-16 19:17:22 +00001065 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001066 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001067 }
1068 // We have two real floating types, float/complex combos were handled above.
1069 // Convert the smaller operand to the bigger result.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001070 int result = Context.getFloatingTypeOrder(lhs, rhs);
Steve Naroff45fc9822007-08-27 15:30:22 +00001071
1072 if (result > 0) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001073 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001074 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001075 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001076 if (result < 0) { // convert the lhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001077 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff45fc9822007-08-27 15:30:22 +00001078 return rhs;
1079 }
1080 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001081 }
Steve Naroff43001212008-01-15 19:36:10 +00001082 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
1083 // Handle GCC complex int extension.
Steve Naroff43001212008-01-15 19:36:10 +00001084 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
Eli Friedman50727042008-02-08 01:19:44 +00001085 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
Steve Naroff43001212008-01-15 19:36:10 +00001086
Eli Friedman50727042008-02-08 01:19:44 +00001087 if (lhsComplexInt && rhsComplexInt) {
Chris Lattner51285d82008-04-06 23:55:33 +00001088 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
1089 rhsComplexInt->getElementType()) >= 0) {
Eli Friedman94075c02008-02-08 01:24:30 +00001090 // convert the rhs
1091 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1092 return lhs;
Eli Friedman50727042008-02-08 01:19:44 +00001093 }
1094 if (!isCompAssign)
Eli Friedman94075c02008-02-08 01:24:30 +00001095 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Eli Friedman50727042008-02-08 01:19:44 +00001096 return rhs;
1097 } else if (lhsComplexInt && rhs->isIntegerType()) {
1098 // convert the rhs to the lhs complex type.
1099 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1100 return lhs;
1101 } else if (rhsComplexInt && lhs->isIntegerType()) {
1102 // convert the lhs to the rhs complex type.
1103 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1104 return rhs;
1105 }
Steve Naroff43001212008-01-15 19:36:10 +00001106 }
Chris Lattner4b009652007-07-25 00:24:17 +00001107 // Finally, we have two differing integer types.
Chris Lattner51285d82008-04-06 23:55:33 +00001108 if (Context.getIntegerTypeOrder(lhs, rhs) >= 0) { // convert the rhs
Chris Lattnere992d6c2008-01-16 19:17:22 +00001109 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
Steve Naroff8f708362007-08-24 19:07:16 +00001110 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001111 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001112 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
Steve Naroff8f708362007-08-24 19:07:16 +00001113 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001114}
1115
1116// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1117// being closely modeled after the C99 spec:-). The odd characteristic of this
1118// routine is it effectively iqnores the qualifiers on the top level pointee.
1119// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1120// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001121Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001122Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1123 QualType lhptee, rhptee;
1124
1125 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001126 lhptee = lhsType->getAsPointerType()->getPointeeType();
1127 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001128
1129 // make sure we operate on the canonical type
1130 lhptee = lhptee.getCanonicalType();
1131 rhptee = rhptee.getCanonicalType();
1132
Chris Lattner005ed752008-01-04 18:04:52 +00001133 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001134
1135 // C99 6.5.16.1p1: This following citation is common to constraints
1136 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1137 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001138 // FIXME: Handle ASQualType
1139 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1140 rhptee.getCVRQualifiers())
Chris Lattner005ed752008-01-04 18:04:52 +00001141 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001142
1143 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1144 // incomplete type and the other is a pointer to a qualified or unqualified
1145 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001146 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001147 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001148 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001149
1150 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001151 assert(rhptee->isFunctionType());
1152 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001153 }
1154
1155 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001156 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001157 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001158
1159 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001160 assert(lhptee->isFunctionType());
1161 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001162 }
1163
Chris Lattner4b009652007-07-25 00:24:17 +00001164 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1165 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001166 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1167 rhptee.getUnqualifiedType()))
1168 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001169 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001170}
1171
1172/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1173/// has code to accommodate several GCC extensions when type checking
1174/// pointers. Here are some objectionable examples that GCC considers warnings:
1175///
1176/// int a, *pint;
1177/// short *pshort;
1178/// struct foo *pfoo;
1179///
1180/// pint = pshort; // warning: assignment from incompatible pointer type
1181/// a = pint; // warning: assignment makes integer from pointer without a cast
1182/// pint = a; // warning: assignment makes pointer from integer without a cast
1183/// pint = pfoo; // warning: assignment from incompatible pointer type
1184///
1185/// As a result, the code for dealing with pointers is more complex than the
1186/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001187///
Chris Lattner005ed752008-01-04 18:04:52 +00001188Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001189Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001190 // Get canonical types. We're not formatting these types, just comparing
1191 // them.
1192 lhsType = lhsType.getCanonicalType();
1193 rhsType = rhsType.getCanonicalType();
1194
1195 if (lhsType.getUnqualifiedType() == rhsType.getUnqualifiedType())
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001196 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001197
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001198 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Chris Lattnere1577e22008-04-07 06:52:53 +00001199 if (Context.typesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001200 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001201 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001202 }
Chris Lattner1853da22008-01-04 23:18:45 +00001203
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001204 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1205 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001206 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001207 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001208 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001209
Chris Lattner390564e2008-04-07 06:49:41 +00001210 if (isa<VectorType>(lhsType) || isa<VectorType>(rhsType)) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001211 // For ExtVector, allow vector splats; float -> <n x float>
1212 if (const ExtVectorType *LV = dyn_cast<ExtVectorType>(lhsType)) {
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001213 if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1214 return Compatible;
1215 }
1216
1217 // If LHS and RHS are both vectors of integer or both vectors of floating
1218 // point types, and the total vector length is the same, allow the
1219 // conversion. This is a bitcast; no bits are changed but the result type
1220 // is different.
1221 if (getLangOptions().LaxVectorConversions &&
1222 lhsType->isVectorType() && rhsType->isVectorType()) {
1223 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1224 (lhsType->isRealFloatingType() && rhsType->isRealFloatingType())) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001225 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Nate Begemanec2d1062007-12-30 02:59:45 +00001226 return Compatible;
1227 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001228 }
1229 return Incompatible;
1230 }
1231
1232 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001233 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001234
Chris Lattner390564e2008-04-07 06:49:41 +00001235 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001236 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001237 return IntToPointer;
Chris Lattner4b009652007-07-25 00:24:17 +00001238
Chris Lattner390564e2008-04-07 06:49:41 +00001239 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001240 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001241 return Incompatible;
1242 }
1243
Chris Lattner390564e2008-04-07 06:49:41 +00001244 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001245 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Chris Lattner390564e2008-04-07 06:49:41 +00001246 if (lhsType->isIntegerType() && lhsType != Context.BoolTy)
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001247 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001248
Chris Lattner390564e2008-04-07 06:49:41 +00001249 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001250 return CheckPointerTypesForAssignment(lhsType, rhsType);
Chris Lattner1853da22008-01-04 23:18:45 +00001251 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001252 }
1253
1254 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001255 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001256 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001257 }
1258 return Incompatible;
1259}
1260
Chris Lattner005ed752008-01-04 18:04:52 +00001261Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001262Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001263 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1264 // a null pointer constant.
Ted Kremenek42730c52008-01-07 19:49:32 +00001265 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001266 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001267 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001268 return Compatible;
1269 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001270 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001271 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001272 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001273 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001274 //
1275 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1276 // are better understood.
1277 if (!lhsType->isReferenceType())
1278 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001279
Chris Lattner005ed752008-01-04 18:04:52 +00001280 Sema::AssignConvertType result =
1281 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001282
1283 // C99 6.5.16.1p2: The value of the right operand is converted to the
1284 // type of the assignment expression.
1285 if (rExpr->getType() != lhsType)
Chris Lattnere992d6c2008-01-16 19:17:22 +00001286 ImpCastExprToType(rExpr, lhsType);
Steve Naroff0f32f432007-08-24 22:33:52 +00001287 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001288}
1289
Chris Lattner005ed752008-01-04 18:04:52 +00001290Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001291Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1292 return CheckAssignmentConstraints(lhsType, rhsType);
1293}
1294
Chris Lattner2c8bff72007-12-12 05:47:28 +00001295QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001296 Diag(loc, diag::err_typecheck_invalid_operands,
1297 lex->getType().getAsString(), rex->getType().getAsString(),
1298 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001299 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001300}
1301
1302inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1303 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001304 // For conversion purposes, we ignore any qualifiers.
1305 // For example, "const float" and "float" are equivalent.
1306 QualType lhsType = lex->getType().getCanonicalType().getUnqualifiedType();
1307 QualType rhsType = rex->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001308
1309 // make sure the vector types are identical.
Nate Begeman03105572008-04-04 01:30:25 +00001310 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001311 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001312
Nate Begemanaf6ed502008-04-18 23:10:10 +00001313 // if the lhs is an extended vector and the rhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001314 // promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001315 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001316 if (V->getElementType().getCanonicalType().getTypePtr()
1317 == rhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001318 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001319 return lhsType;
1320 }
1321 }
1322
Nate Begemanaf6ed502008-04-18 23:10:10 +00001323 // if the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001324 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001325 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001326 if (V->getElementType().getCanonicalType().getTypePtr()
1327 == lhsType.getCanonicalType().getTypePtr()) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001328 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001329 return rhsType;
1330 }
1331 }
1332
Chris Lattner4b009652007-07-25 00:24:17 +00001333 // You cannot convert between vector values of different size.
1334 Diag(loc, diag::err_typecheck_vector_not_convertable,
1335 lex->getType().getAsString(), rex->getType().getAsString(),
1336 lex->getSourceRange(), rex->getSourceRange());
1337 return QualType();
1338}
1339
1340inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001341 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001342{
1343 QualType lhsType = lex->getType(), rhsType = rex->getType();
1344
1345 if (lhsType->isVectorType() || rhsType->isVectorType())
1346 return CheckVectorOperands(loc, lex, rex);
1347
Steve Naroff8f708362007-08-24 19:07:16 +00001348 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001349
Chris Lattner4b009652007-07-25 00:24:17 +00001350 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001351 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001352 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001353}
1354
1355inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001356 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001357{
1358 QualType lhsType = lex->getType(), rhsType = rex->getType();
1359
Steve Naroff8f708362007-08-24 19:07:16 +00001360 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001361
Chris Lattner4b009652007-07-25 00:24:17 +00001362 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001363 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001364 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001365}
1366
1367inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001368 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001369{
1370 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1371 return CheckVectorOperands(loc, lex, rex);
1372
Steve Naroff8f708362007-08-24 19:07:16 +00001373 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001374
1375 // handle the common case first (both operands are arithmetic).
1376 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001377 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001378
1379 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1380 return lex->getType();
1381 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1382 return rex->getType();
Chris Lattner2c8bff72007-12-12 05:47:28 +00001383 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001384}
1385
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001386// C99 6.5.6
1387QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1388 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001389 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1390 return CheckVectorOperands(loc, lex, rex);
1391
Steve Naroff8f708362007-08-24 19:07:16 +00001392 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001393
Chris Lattnerf6da2912007-12-09 21:53:25 +00001394 // Enforce type constraints: C99 6.5.6p3.
1395
1396 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001397 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001398 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001399
1400 // Either ptr - int or ptr - ptr.
1401 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001402 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001403
Chris Lattnerf6da2912007-12-09 21:53:25 +00001404 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001405 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001406 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001407 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001408 Diag(loc, diag::ext_gnu_void_ptr,
1409 lex->getSourceRange(), rex->getSourceRange());
1410 } else {
1411 Diag(loc, diag::err_typecheck_sub_ptr_object,
1412 lex->getType().getAsString(), lex->getSourceRange());
1413 return QualType();
1414 }
1415 }
1416
1417 // The result type of a pointer-int computation is the pointer type.
1418 if (rex->getType()->isIntegerType())
1419 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001420
Chris Lattnerf6da2912007-12-09 21:53:25 +00001421 // Handle pointer-pointer subtractions.
1422 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001423 QualType rpointee = RHSPTy->getPointeeType();
1424
Chris Lattnerf6da2912007-12-09 21:53:25 +00001425 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001426 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001427 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001428 if (rpointee->isVoidType()) {
1429 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00001430 Diag(loc, diag::ext_gnu_void_ptr,
1431 lex->getSourceRange(), rex->getSourceRange());
1432 } else {
1433 Diag(loc, diag::err_typecheck_sub_ptr_object,
1434 rex->getType().getAsString(), rex->getSourceRange());
1435 return QualType();
1436 }
1437 }
1438
1439 // Pointee types must be compatible.
Steve Naroff577f9722008-01-29 18:58:14 +00001440 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1441 rpointee.getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001442 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1443 lex->getType().getAsString(), rex->getType().getAsString(),
1444 lex->getSourceRange(), rex->getSourceRange());
1445 return QualType();
1446 }
1447
1448 return Context.getPointerDiffType();
1449 }
1450 }
1451
Chris Lattner2c8bff72007-12-12 05:47:28 +00001452 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001453}
1454
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001455// C99 6.5.7
1456QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1457 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00001458 // C99 6.5.7p2: Each of the operands shall have integer type.
1459 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1460 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001461
Chris Lattner2c8bff72007-12-12 05:47:28 +00001462 // Shifts don't perform usual arithmetic conversions, they just do integer
1463 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001464 if (!isCompAssign)
1465 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001466 UsualUnaryConversions(rex);
1467
1468 // "The type of the result is that of the promoted left operand."
1469 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001470}
1471
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001472// C99 6.5.8
1473QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1474 bool isRelational) {
Chris Lattner254f3bc2007-08-26 01:18:55 +00001475 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001476 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1477 UsualArithmeticConversions(lex, rex);
1478 else {
1479 UsualUnaryConversions(lex);
1480 UsualUnaryConversions(rex);
1481 }
Chris Lattner4b009652007-07-25 00:24:17 +00001482 QualType lType = lex->getType();
1483 QualType rType = rex->getType();
1484
Ted Kremenek486509e2007-10-29 17:13:39 +00001485 // For non-floating point types, check for self-comparisons of the form
1486 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1487 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001488 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00001489 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1490 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001491 if (DRL->getDecl() == DRR->getDecl())
1492 Diag(loc, diag::warn_selfcomparison);
1493 }
1494
Chris Lattner254f3bc2007-08-26 01:18:55 +00001495 if (isRelational) {
1496 if (lType->isRealType() && rType->isRealType())
1497 return Context.IntTy;
1498 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001499 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001500 if (lType->isFloatingType()) {
1501 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001502 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001503 }
1504
Chris Lattner254f3bc2007-08-26 01:18:55 +00001505 if (lType->isArithmeticType() && rType->isArithmeticType())
1506 return Context.IntTy;
1507 }
Chris Lattner4b009652007-07-25 00:24:17 +00001508
Chris Lattner22be8422007-08-26 01:10:14 +00001509 bool LHSIsNull = lex->isNullPointerConstant(Context);
1510 bool RHSIsNull = rex->isNullPointerConstant(Context);
1511
Chris Lattner254f3bc2007-08-26 01:18:55 +00001512 // All of the following pointer related warnings are GCC extensions, except
1513 // when handling null pointer constants. One day, we can consider making them
1514 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001515 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001516 QualType LCanPointeeTy =
1517 lType->getAsPointerType()->getPointeeType().getCanonicalType();
1518 QualType RCanPointeeTy =
1519 rType->getAsPointerType()->getPointeeType().getCanonicalType();
Eli Friedman50727042008-02-08 01:19:44 +00001520
Steve Naroff3b435622007-11-13 14:57:38 +00001521 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00001522 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1523 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
1524 RCanPointeeTy.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001525 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1526 lType.getAsString(), rType.getAsString(),
1527 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001528 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00001529 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001530 return Context.IntTy;
1531 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001532 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001533 && ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001534 ImpCastExprToType(rex, lType);
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00001535 return Context.IntTy;
1536 }
Steve Naroff4462cb02007-08-16 21:48:38 +00001537 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001538 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001539 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1540 lType.getAsString(), rType.getAsString(),
1541 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001542 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001543 return Context.IntTy;
1544 }
1545 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001546 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001547 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1548 lType.getAsString(), rType.getAsString(),
1549 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00001550 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001551 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001552 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001553 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001554}
1555
Chris Lattner4b009652007-07-25 00:24:17 +00001556inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001557 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001558{
1559 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1560 return CheckVectorOperands(loc, lex, rex);
1561
Steve Naroff8f708362007-08-24 19:07:16 +00001562 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001563
1564 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001565 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001566 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001567}
1568
1569inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1570 Expr *&lex, Expr *&rex, SourceLocation loc)
1571{
1572 UsualUnaryConversions(lex);
1573 UsualUnaryConversions(rex);
1574
1575 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1576 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001577 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001578}
1579
1580inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001581 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001582{
1583 QualType lhsType = lex->getType();
1584 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner4b009652007-07-25 00:24:17 +00001585 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1586
1587 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00001588 case Expr::MLV_Valid:
1589 break;
1590 case Expr::MLV_ConstQualified:
1591 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1592 return QualType();
1593 case Expr::MLV_ArrayType:
1594 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1595 lhsType.getAsString(), lex->getSourceRange());
1596 return QualType();
1597 case Expr::MLV_NotObjectType:
1598 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1599 lhsType.getAsString(), lex->getSourceRange());
1600 return QualType();
1601 case Expr::MLV_InvalidExpression:
1602 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1603 lex->getSourceRange());
1604 return QualType();
1605 case Expr::MLV_IncompleteType:
1606 case Expr::MLV_IncompleteVoidType:
1607 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1608 lhsType.getAsString(), lex->getSourceRange());
1609 return QualType();
1610 case Expr::MLV_DuplicateVectorComponents:
1611 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1612 lex->getSourceRange());
1613 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001614 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00001615
Chris Lattner005ed752008-01-04 18:04:52 +00001616 AssignConvertType ConvTy;
1617 if (compoundType.isNull())
1618 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1619 else
1620 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1621
1622 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1623 rex, "assigning"))
1624 return QualType();
1625
Chris Lattner4b009652007-07-25 00:24:17 +00001626 // C99 6.5.16p3: The type of an assignment expression is the type of the
1627 // left operand unless the left operand has qualified type, in which case
1628 // it is the unqualified version of the type of the left operand.
1629 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1630 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001631 // C++ 5.17p1: the type of the assignment expression is that of its left
1632 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00001633 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001634}
1635
1636inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1637 Expr *&lex, Expr *&rex, SourceLocation loc) {
1638 UsualUnaryConversions(rex);
1639 return rex->getType();
1640}
1641
1642/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1643/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1644QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1645 QualType resType = op->getType();
1646 assert(!resType.isNull() && "no type for increment/decrement expression");
1647
Steve Naroffd30e1932007-08-24 17:20:07 +00001648 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001649 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001650 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1651 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1652 resType.getAsString(), op->getSourceRange());
1653 return QualType();
1654 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001655 } else if (!resType->isRealType()) {
1656 if (resType->isComplexType())
1657 // C99 does not support ++/-- on complex types.
1658 Diag(OpLoc, diag::ext_integer_increment_complex,
1659 resType.getAsString(), op->getSourceRange());
1660 else {
1661 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1662 resType.getAsString(), op->getSourceRange());
1663 return QualType();
1664 }
Chris Lattner4b009652007-07-25 00:24:17 +00001665 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001666 // At this point, we know we have a real, complex or pointer type.
1667 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001668 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1669 if (mlval != Expr::MLV_Valid) {
1670 // FIXME: emit a more precise diagnostic...
1671 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1672 op->getSourceRange());
1673 return QualType();
1674 }
1675 return resType;
1676}
1677
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001678/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00001679/// This routine allows us to typecheck complex/recursive expressions
1680/// where the declaration is needed for type checking. Here are some
1681/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
Chris Lattner48d7f382008-04-02 04:24:33 +00001682static ValueDecl *getPrimaryDecl(Expr *E) {
1683 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001684 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001685 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001686 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001687 // Fields cannot be declared with a 'register' storage class.
1688 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00001689 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00001690 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00001691 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001692 case Stmt::ArraySubscriptExprClass: {
1693 // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer.
1694
Chris Lattner48d7f382008-04-02 04:24:33 +00001695 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Anders Carlsson655694e2008-02-01 16:01:31 +00001696 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001697 return 0;
1698 else
1699 return VD;
1700 }
Chris Lattner4b009652007-07-25 00:24:17 +00001701 case Stmt::UnaryOperatorClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001702 return getPrimaryDecl(cast<UnaryOperator>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001703 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00001704 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001705 case Stmt::ImplicitCastExprClass:
1706 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00001707 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001708 default:
1709 return 0;
1710 }
1711}
1712
1713/// CheckAddressOfOperand - The operand of & must be either a function
1714/// designator or an lvalue designating an object. If it is an lvalue, the
1715/// object cannot be declared with storage class register or be a bit field.
1716/// Note: The usual conversions are *not* applied to the operand of the &
1717/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1718QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001719 if (getLangOptions().C99) {
1720 // Implement C99-only parts of addressof rules.
1721 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
1722 if (uOp->getOpcode() == UnaryOperator::Deref)
1723 // Per C99 6.5.3.2, the address of a deref always returns a valid result
1724 // (assuming the deref expression is valid).
1725 return uOp->getSubExpr()->getType();
1726 }
1727 // Technically, there should be a check for array subscript
1728 // expressions here, but the result of one is always an lvalue anyway.
1729 }
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00001730 ValueDecl *dcl = getPrimaryDecl(op);
Chris Lattner4b009652007-07-25 00:24:17 +00001731 Expr::isLvalueResult lval = op->isLvalue();
1732
1733 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001734 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1735 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001736 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1737 op->getSourceRange());
1738 return QualType();
1739 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00001740 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
1741 if (MemExpr->getMemberDecl()->isBitField()) {
1742 Diag(OpLoc, diag::err_typecheck_address_of,
1743 std::string("bit-field"), op->getSourceRange());
1744 return QualType();
1745 }
1746 // Check for Apple extension for accessing vector components.
1747 } else if (isa<ArraySubscriptExpr>(op) &&
1748 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
1749 Diag(OpLoc, diag::err_typecheck_address_of,
1750 std::string("vector"), op->getSourceRange());
1751 return QualType();
1752 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00001753 // We have an lvalue with a decl. Make sure the decl is not declared
1754 // with the register storage-class specifier.
1755 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1756 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00001757 Diag(OpLoc, diag::err_typecheck_address_of,
1758 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001759 return QualType();
1760 }
1761 } else
1762 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00001763 }
1764 // If the operand has type "type", the result has type "pointer to type".
1765 return Context.getPointerType(op->getType());
1766}
1767
1768QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1769 UsualUnaryConversions(op);
1770 QualType qType = op->getType();
1771
Chris Lattner7931f4a2007-07-31 16:53:04 +00001772 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00001773 // Note that per both C89 and C99, this is always legal, even
1774 // if ptype is an incomplete type or void.
1775 // It would be possible to warn about dereferencing a
1776 // void pointer, but it's completely well-defined,
1777 // and such a warning is unlikely to catch any mistakes.
1778 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001779 }
1780 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1781 qType.getAsString(), op->getSourceRange());
1782 return QualType();
1783}
1784
1785static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1786 tok::TokenKind Kind) {
1787 BinaryOperator::Opcode Opc;
1788 switch (Kind) {
1789 default: assert(0 && "Unknown binop!");
1790 case tok::star: Opc = BinaryOperator::Mul; break;
1791 case tok::slash: Opc = BinaryOperator::Div; break;
1792 case tok::percent: Opc = BinaryOperator::Rem; break;
1793 case tok::plus: Opc = BinaryOperator::Add; break;
1794 case tok::minus: Opc = BinaryOperator::Sub; break;
1795 case tok::lessless: Opc = BinaryOperator::Shl; break;
1796 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1797 case tok::lessequal: Opc = BinaryOperator::LE; break;
1798 case tok::less: Opc = BinaryOperator::LT; break;
1799 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1800 case tok::greater: Opc = BinaryOperator::GT; break;
1801 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1802 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1803 case tok::amp: Opc = BinaryOperator::And; break;
1804 case tok::caret: Opc = BinaryOperator::Xor; break;
1805 case tok::pipe: Opc = BinaryOperator::Or; break;
1806 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1807 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1808 case tok::equal: Opc = BinaryOperator::Assign; break;
1809 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1810 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1811 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1812 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1813 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1814 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1815 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1816 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1817 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1818 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1819 case tok::comma: Opc = BinaryOperator::Comma; break;
1820 }
1821 return Opc;
1822}
1823
1824static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1825 tok::TokenKind Kind) {
1826 UnaryOperator::Opcode Opc;
1827 switch (Kind) {
1828 default: assert(0 && "Unknown unary op!");
1829 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1830 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1831 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1832 case tok::star: Opc = UnaryOperator::Deref; break;
1833 case tok::plus: Opc = UnaryOperator::Plus; break;
1834 case tok::minus: Opc = UnaryOperator::Minus; break;
1835 case tok::tilde: Opc = UnaryOperator::Not; break;
1836 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1837 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1838 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1839 case tok::kw___real: Opc = UnaryOperator::Real; break;
1840 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1841 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1842 }
1843 return Opc;
1844}
1845
1846// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001847Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001848 ExprTy *LHS, ExprTy *RHS) {
1849 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1850 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1851
Steve Naroff87d58b42007-09-16 03:34:24 +00001852 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1853 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001854
1855 QualType ResultTy; // Result type of the binary operator.
1856 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1857
1858 switch (Opc) {
1859 default:
1860 assert(0 && "Unknown binary expr!");
1861 case BinaryOperator::Assign:
1862 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1863 break;
1864 case BinaryOperator::Mul:
1865 case BinaryOperator::Div:
1866 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1867 break;
1868 case BinaryOperator::Rem:
1869 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1870 break;
1871 case BinaryOperator::Add:
1872 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1873 break;
1874 case BinaryOperator::Sub:
1875 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1876 break;
1877 case BinaryOperator::Shl:
1878 case BinaryOperator::Shr:
1879 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1880 break;
1881 case BinaryOperator::LE:
1882 case BinaryOperator::LT:
1883 case BinaryOperator::GE:
1884 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001885 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001886 break;
1887 case BinaryOperator::EQ:
1888 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001889 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001890 break;
1891 case BinaryOperator::And:
1892 case BinaryOperator::Xor:
1893 case BinaryOperator::Or:
1894 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1895 break;
1896 case BinaryOperator::LAnd:
1897 case BinaryOperator::LOr:
1898 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1899 break;
1900 case BinaryOperator::MulAssign:
1901 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001902 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001903 if (!CompTy.isNull())
1904 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1905 break;
1906 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001907 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001908 if (!CompTy.isNull())
1909 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1910 break;
1911 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001912 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001913 if (!CompTy.isNull())
1914 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1915 break;
1916 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001917 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001918 if (!CompTy.isNull())
1919 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1920 break;
1921 case BinaryOperator::ShlAssign:
1922 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001923 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001924 if (!CompTy.isNull())
1925 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1926 break;
1927 case BinaryOperator::AndAssign:
1928 case BinaryOperator::XorAssign:
1929 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001930 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001931 if (!CompTy.isNull())
1932 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1933 break;
1934 case BinaryOperator::Comma:
1935 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1936 break;
1937 }
1938 if (ResultTy.isNull())
1939 return true;
1940 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001941 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001942 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001943 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001944}
1945
1946// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001947Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001948 ExprTy *input) {
1949 Expr *Input = (Expr*)input;
1950 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1951 QualType resultType;
1952 switch (Opc) {
1953 default:
1954 assert(0 && "Unimplemented unary expr!");
1955 case UnaryOperator::PreInc:
1956 case UnaryOperator::PreDec:
1957 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1958 break;
1959 case UnaryOperator::AddrOf:
1960 resultType = CheckAddressOfOperand(Input, OpLoc);
1961 break;
1962 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00001963 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00001964 resultType = CheckIndirectionOperand(Input, OpLoc);
1965 break;
1966 case UnaryOperator::Plus:
1967 case UnaryOperator::Minus:
1968 UsualUnaryConversions(Input);
1969 resultType = Input->getType();
1970 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1971 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1972 resultType.getAsString());
1973 break;
1974 case UnaryOperator::Not: // bitwise complement
1975 UsualUnaryConversions(Input);
1976 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001977 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1978 if (!resultType->isIntegerType()) {
1979 if (resultType->isComplexType())
1980 // C99 does not support '~' for complex conjugation.
1981 Diag(OpLoc, diag::ext_integer_complement_complex,
1982 resultType.getAsString());
1983 else
1984 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1985 resultType.getAsString());
1986 }
Chris Lattner4b009652007-07-25 00:24:17 +00001987 break;
1988 case UnaryOperator::LNot: // logical negation
1989 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1990 DefaultFunctionArrayConversion(Input);
1991 resultType = Input->getType();
1992 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1993 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1994 resultType.getAsString());
1995 // LNot always has type int. C99 6.5.3.3p5.
1996 resultType = Context.IntTy;
1997 break;
1998 case UnaryOperator::SizeOf:
1999 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
2000 break;
2001 case UnaryOperator::AlignOf:
2002 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
2003 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002004 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002005 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002006 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002007 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002008 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002009 resultType = Input->getType();
2010 break;
2011 }
2012 if (resultType.isNull())
2013 return true;
2014 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2015}
2016
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002017/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2018Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002019 SourceLocation LabLoc,
2020 IdentifierInfo *LabelII) {
2021 // Look up the record for this label identifier.
2022 LabelStmt *&LabelDecl = LabelMap[LabelII];
2023
2024 // If we haven't seen this label yet, create a forward reference.
2025 if (LabelDecl == 0)
2026 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2027
2028 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002029 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2030 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002031}
2032
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002033Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002034 SourceLocation RPLoc) { // "({..})"
2035 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2036 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2037 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2038
2039 // FIXME: there are a variety of strange constraints to enforce here, for
2040 // example, it is not possible to goto into a stmt expression apparently.
2041 // More semantic analysis is needed.
2042
2043 // FIXME: the last statement in the compount stmt has its value used. We
2044 // should not warn about it being unused.
2045
2046 // If there are sub stmts in the compound stmt, take the type of the last one
2047 // as the type of the stmtexpr.
2048 QualType Ty = Context.VoidTy;
2049
2050 if (!Compound->body_empty())
2051 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
2052 Ty = LastExpr->getType();
2053
2054 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2055}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002056
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002057Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002058 SourceLocation TypeLoc,
2059 TypeTy *argty,
2060 OffsetOfComponent *CompPtr,
2061 unsigned NumComponents,
2062 SourceLocation RPLoc) {
2063 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2064 assert(!ArgTy.isNull() && "Missing type argument!");
2065
2066 // We must have at least one component that refers to the type, and the first
2067 // one is known to be a field designator. Verify that the ArgTy represents
2068 // a struct/union/class.
2069 if (!ArgTy->isRecordType())
2070 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2071
2072 // Otherwise, create a compound literal expression as the base, and
2073 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002074 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002075
Chris Lattnerb37522e2007-08-31 21:49:13 +00002076 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2077 // GCC extension, diagnose them.
2078 if (NumComponents != 1)
2079 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2080 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2081
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002082 for (unsigned i = 0; i != NumComponents; ++i) {
2083 const OffsetOfComponent &OC = CompPtr[i];
2084 if (OC.isBrackets) {
2085 // Offset of an array sub-field. TODO: Should we allow vector elements?
2086 const ArrayType *AT = Res->getType()->getAsArrayType();
2087 if (!AT) {
2088 delete Res;
2089 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2090 Res->getType().getAsString());
2091 }
2092
Chris Lattner2af6a802007-08-30 17:59:59 +00002093 // FIXME: C++: Verify that operator[] isn't overloaded.
2094
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002095 // C99 6.5.2.1p1
2096 Expr *Idx = static_cast<Expr*>(OC.U.E);
2097 if (!Idx->getType()->isIntegerType())
2098 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2099 Idx->getSourceRange());
2100
2101 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2102 continue;
2103 }
2104
2105 const RecordType *RC = Res->getType()->getAsRecordType();
2106 if (!RC) {
2107 delete Res;
2108 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2109 Res->getType().getAsString());
2110 }
2111
2112 // Get the decl corresponding to this.
2113 RecordDecl *RD = RC->getDecl();
2114 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2115 if (!MemberDecl)
2116 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2117 OC.U.IdentInfo->getName(),
2118 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002119
2120 // FIXME: C++: Verify that MemberDecl isn't a static field.
2121 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002122 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2123 // matter here.
2124 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002125 }
2126
2127 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2128 BuiltinLoc);
2129}
2130
2131
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002132Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002133 TypeTy *arg1, TypeTy *arg2,
2134 SourceLocation RPLoc) {
2135 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2136 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2137
2138 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2139
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002140 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002141}
2142
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002143Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002144 ExprTy *expr1, ExprTy *expr2,
2145 SourceLocation RPLoc) {
2146 Expr *CondExpr = static_cast<Expr*>(cond);
2147 Expr *LHSExpr = static_cast<Expr*>(expr1);
2148 Expr *RHSExpr = static_cast<Expr*>(expr2);
2149
2150 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2151
2152 // The conditional expression is required to be a constant expression.
2153 llvm::APSInt condEval(32);
2154 SourceLocation ExpLoc;
2155 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2156 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2157 CondExpr->getSourceRange());
2158
2159 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2160 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2161 RHSExpr->getType();
2162 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2163}
2164
Nate Begemanbd881ef2008-01-30 20:50:20 +00002165/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002166/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00002167/// The number of arguments has already been validated to match the number of
2168/// arguments in FnType.
2169static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002170 unsigned NumParams = FnType->getNumArgs();
2171 for (unsigned i = 0; i != NumParams; ++i)
Nate Begemanbd881ef2008-01-30 20:50:20 +00002172 if (Args[i]->getType().getCanonicalType() !=
2173 FnType->getArgType(i).getCanonicalType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002174 return false;
2175 return true;
2176}
2177
2178Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2179 SourceLocation *CommaLocs,
2180 SourceLocation BuiltinLoc,
2181 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00002182 // __builtin_overload requires at least 2 arguments
2183 if (NumArgs < 2)
2184 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2185 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002186
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002187 // The first argument is required to be a constant expression. It tells us
2188 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00002189 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002190 Expr *NParamsExpr = Args[0];
2191 llvm::APSInt constEval(32);
2192 SourceLocation ExpLoc;
2193 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2194 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2195 NParamsExpr->getSourceRange());
2196
2197 // Verify that the number of parameters is > 0
2198 unsigned NumParams = constEval.getZExtValue();
2199 if (NumParams == 0)
2200 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2201 NParamsExpr->getSourceRange());
2202 // Verify that we have at least 1 + NumParams arguments to the builtin.
2203 if ((NumParams + 1) > NumArgs)
2204 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2205 SourceRange(BuiltinLoc, RParenLoc));
2206
2207 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00002208 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00002209 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002210 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2211 // UsualUnaryConversions will convert the function DeclRefExpr into a
2212 // pointer to function.
2213 Expr *Fn = UsualUnaryConversions(Args[i]);
2214 FunctionTypeProto *FnType = 0;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002215 if (const PointerType *PT = Fn->getType()->getAsPointerType()) {
2216 QualType PointeeType = PT->getPointeeType().getCanonicalType();
2217 FnType = dyn_cast<FunctionTypeProto>(PointeeType);
2218 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002219
2220 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2221 // parameters, and the number of parameters must match the value passed to
2222 // the builtin.
2223 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00002224 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2225 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002226
2227 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00002228 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002229 // If they match, return a new OverloadExpr.
Nate Begemanc6078c92008-01-31 05:38:29 +00002230 if (ExprsMatchFnType(Args+1, FnType)) {
2231 if (OE)
2232 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2233 OE->getFn()->getSourceRange());
2234 // Remember our match, and continue processing the remaining arguments
2235 // to catch any errors.
2236 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2237 BuiltinLoc, RParenLoc);
2238 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002239 }
Nate Begemanc6078c92008-01-31 05:38:29 +00002240 // Return the newly created OverloadExpr node, if we succeded in matching
2241 // exactly one of the candidate functions.
2242 if (OE)
2243 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002244
2245 // If we didn't find a matching function Expr in the __builtin_overload list
2246 // the return an error.
2247 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00002248 for (unsigned i = 0; i != NumParams; ++i) {
2249 if (i != 0) typeNames += ", ";
2250 typeNames += Args[i+1]->getType().getAsString();
2251 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00002252
2253 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2254 SourceRange(BuiltinLoc, RParenLoc));
2255}
2256
Anders Carlsson36760332007-10-15 20:28:48 +00002257Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2258 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00002259 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00002260 Expr *E = static_cast<Expr*>(expr);
2261 QualType T = QualType::getFromOpaquePtr(type);
2262
2263 InitBuiltinVaListType();
2264
Chris Lattner005ed752008-01-04 18:04:52 +00002265 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2266 != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00002267 return Diag(E->getLocStart(),
2268 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2269 E->getType().getAsString(),
2270 E->getSourceRange());
2271
2272 // FIXME: Warn if a non-POD type is passed in.
2273
2274 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2275}
2276
Chris Lattner005ed752008-01-04 18:04:52 +00002277bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2278 SourceLocation Loc,
2279 QualType DstType, QualType SrcType,
2280 Expr *SrcExpr, const char *Flavor) {
2281 // Decode the result (notice that AST's are still created for extensions).
2282 bool isInvalid = false;
2283 unsigned DiagKind;
2284 switch (ConvTy) {
2285 default: assert(0 && "Unknown conversion type");
2286 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002287 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00002288 DiagKind = diag::ext_typecheck_convert_pointer_int;
2289 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002290 case IntToPointer:
2291 DiagKind = diag::ext_typecheck_convert_int_pointer;
2292 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002293 case IncompatiblePointer:
2294 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2295 break;
2296 case FunctionVoidPointer:
2297 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2298 break;
2299 case CompatiblePointerDiscardsQualifiers:
2300 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2301 break;
2302 case Incompatible:
2303 DiagKind = diag::err_typecheck_convert_incompatible;
2304 isInvalid = true;
2305 break;
2306 }
2307
2308 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2309 SrcExpr->getSourceRange());
2310 return isInvalid;
2311}
2312