blob: bf5d71fd080314ca40d6a7ad8e61698e1c46bcbf [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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"
17#include "clang/AST/Decl.h"
Steve Narofffa465d12007-10-02 20:01:56 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/AST/Expr.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000020#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Lex/Preprocessor.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Basic/SourceManager.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/TargetInfo.h"
27#include "llvm/ADT/SmallString.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000028#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029using namespace clang;
30
Steve Naroff87d58b42007-09-16 03:34:24 +000031/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +000032/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
33/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
34/// multiple tokens. However, the common case is that StringToks points to one
35/// string.
36///
37Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +000038Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +000039 assert(NumStringToks && "Must have at least one string!");
40
41 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
42 if (Literal.hadError)
43 return ExprResult(true);
44
45 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
46 for (unsigned i = 0; i != NumStringToks; ++i)
47 StringTokLocs.push_back(StringToks[i].getLocation());
48
49 // FIXME: handle wchar_t
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000050 QualType t;
51
52 if (Literal.Pascal)
53 t = Context.getPointerType(Context.UnsignedCharTy);
54 else
55 t = Context.getPointerType(Context.CharTy);
56
57 if (Literal.Pascal && Literal.GetStringLength() > 256)
58 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
59 SourceRange(StringToks[0].getLocation(),
60 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +000061
62 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
63 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Anders Carlsson55bfe0d2007-10-15 02:50:23 +000064 Literal.AnyWide, t,
65 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +000066 StringToks[NumStringToks-1].getLocation());
67}
68
69
Steve Naroff0acc9c92007-09-15 18:49:24 +000070/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +000071/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
72/// identifier is used in an function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +000073Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +000074 IdentifierInfo &II,
75 bool HasTrailingLParen) {
76 // Could be enum-constant or decl.
Steve Narofff0c31dd2007-09-16 16:16:00 +000077 ScopedDecl *D = LookupScopedDecl(&II, Decl::IDNS_Ordinary, Loc, S);
Chris Lattner4b009652007-07-25 00:24:17 +000078 if (D == 0) {
79 // Otherwise, this could be an implicitly declared function reference (legal
80 // in C90, extension in C99).
81 if (HasTrailingLParen &&
82 // Not in C++.
83 !getLangOptions().CPlusPlus)
84 D = ImplicitlyDefineFunction(Loc, II, S);
85 else {
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000086 if (CurMethodDecl) {
87 ObjcInterfaceDecl *IFace = CurMethodDecl->getClassInterface();
88 ObjcInterfaceDecl *clsDeclared;
Steve Naroff6b759ce2007-11-15 02:58:25 +000089 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&II, clsDeclared)) {
90 IdentifierInfo &II = Context.Idents.get("self");
91 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
92 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
93 static_cast<Expr*>(SelfExpr.Val), true, true);
94 }
Steve Naroff5eb2a4a2007-11-12 14:29:37 +000095 }
Chris Lattner4b009652007-07-25 00:24:17 +000096 // If this name wasn't predeclared and if this is not a function call,
97 // diagnose the problem.
98 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
99 }
100 }
Steve Naroff91b03f72007-08-28 03:03:08 +0000101 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Steve Naroffcae537d2007-08-28 18:45:29 +0000102 // Only create DeclRefExpr's for valid Decl's.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000103 if (VD->isInvalidDecl())
Steve Naroff91b03f72007-08-28 03:03:08 +0000104 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000105 return new DeclRefExpr(VD, VD->getType(), Loc);
Steve Naroff91b03f72007-08-28 03:03:08 +0000106 }
Chris Lattner4b009652007-07-25 00:24:17 +0000107 if (isa<TypedefDecl>(D))
108 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000109 if (isa<ObjcInterfaceDecl>(D))
110 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000111
112 assert(0 && "Invalid decl");
113 abort();
114}
115
Steve Naroff87d58b42007-09-16 03:34:24 +0000116Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000117 tok::TokenKind Kind) {
118 PreDefinedExpr::IdentType IT;
119
120 switch (Kind) {
121 default:
122 assert(0 && "Unknown simple primary expr!");
123 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
124 IT = PreDefinedExpr::Func;
125 break;
126 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
127 IT = PreDefinedExpr::Function;
128 break;
129 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
130 IT = PreDefinedExpr::PrettyFunction;
131 break;
132 }
133
134 // Pre-defined identifiers are always of type char *.
135 return new PreDefinedExpr(Loc, Context.getPointerType(Context.CharTy), IT);
136}
137
Steve Naroff87d58b42007-09-16 03:34:24 +0000138Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000139 llvm::SmallString<16> CharBuffer;
140 CharBuffer.resize(Tok.getLength());
141 const char *ThisTokBegin = &CharBuffer[0];
142 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
143
144 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
145 Tok.getLocation(), PP);
146 if (Literal.hadError())
147 return ExprResult(true);
148 return new CharacterLiteral(Literal.getValue(), Context.IntTy,
149 Tok.getLocation());
150}
151
Steve Naroff87d58b42007-09-16 03:34:24 +0000152Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000153 // fast path for a single digit (which is quite common). A single digit
154 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
155 if (Tok.getLength() == 1) {
156 const char *t = PP.getSourceManager().getCharacterData(Tok.getLocation());
157
Chris Lattner3496d522007-09-04 02:45:27 +0000158 unsigned IntSize = static_cast<unsigned>(
159 Context.getTypeSize(Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000160 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *t-'0'),
161 Context.IntTy,
162 Tok.getLocation()));
163 }
164 llvm::SmallString<512> IntegerBuffer;
165 IntegerBuffer.resize(Tok.getLength());
166 const char *ThisTokBegin = &IntegerBuffer[0];
167
168 // Get the spelling of the token, which eliminates trigraphs, etc.
169 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
170 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
171 Tok.getLocation(), PP);
172 if (Literal.hadError)
173 return ExprResult(true);
174
Chris Lattner1de66eb2007-08-26 03:42:43 +0000175 Expr *Res;
176
177 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000178 QualType Ty;
179 const llvm::fltSemantics *Format;
180 uint64_t Size; unsigned Align;
181
182 if (Literal.isFloat) {
183 Ty = Context.FloatTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000184 Context.Target.getFloatInfo(Size, Align, Format,
185 Context.getFullLoc(Tok.getLocation()));
186
Chris Lattner858eece2007-09-22 18:29:59 +0000187 } else if (Literal.isLong) {
188 Ty = Context.LongDoubleTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000189 Context.Target.getLongDoubleInfo(Size, Align, Format,
190 Context.getFullLoc(Tok.getLocation()));
Chris Lattner858eece2007-09-22 18:29:59 +0000191 } else {
192 Ty = Context.DoubleTy;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000193 Context.Target.getDoubleInfo(Size, Align, Format,
194 Context.getFullLoc(Tok.getLocation()));
Chris Lattner858eece2007-09-22 18:29:59 +0000195 }
196
Ted Kremenekddedbe22007-11-29 00:56:49 +0000197 // isExact will be set by GetFloatValue().
198 bool isExact = false;
199
200 Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
201 Ty, Tok.getLocation());
202
Chris Lattner1de66eb2007-08-26 03:42:43 +0000203 } else if (!Literal.isIntegerLiteral()) {
204 return ExprResult(true);
205 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000206 QualType t;
207
Neil Booth7421e9c2007-08-29 22:00:19 +0000208 // long long is a C99 feature.
209 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000210 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000211 Diag(Tok.getLocation(), diag::ext_longlong);
212
Chris Lattner4b009652007-07-25 00:24:17 +0000213 // Get the value in the widest-possible width.
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000214 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(
215 Context.getFullLoc(Tok.getLocation())), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000216
217 if (Literal.GetIntegerValue(ResultVal)) {
218 // If this value didn't fit into uintmax_t, warn and force to ull.
219 Diag(Tok.getLocation(), diag::warn_integer_too_large);
220 t = Context.UnsignedLongLongTy;
221 assert(Context.getTypeSize(t, Tok.getLocation()) ==
222 ResultVal.getBitWidth() && "long long is not intmax_t?");
223 } else {
224 // If this value fits into a ULL, try to figure out what else it fits into
225 // according to the rules of C99 6.4.4.1p5.
226
227 // Octal, Hexadecimal, and integers with a U suffix are allowed to
228 // be an unsigned int.
229 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
230
231 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner98540b62007-08-23 21:58:08 +0000232 if (!Literal.isLong && !Literal.isLongLong) {
233 // Are int/unsigned possibilities?
Chris Lattner3496d522007-09-04 02:45:27 +0000234 unsigned IntSize = static_cast<unsigned>(
235 Context.getTypeSize(Context.IntTy,Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000236 // Does it fit in a unsigned int?
237 if (ResultVal.isIntN(IntSize)) {
238 // Does it fit in a signed int?
239 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
240 t = Context.IntTy;
241 else if (AllowUnsigned)
242 t = Context.UnsignedIntTy;
243 }
244
245 if (!t.isNull())
246 ResultVal.trunc(IntSize);
247 }
248
249 // Are long/unsigned long possibilities?
250 if (t.isNull() && !Literal.isLongLong) {
Chris Lattner3496d522007-09-04 02:45:27 +0000251 unsigned LongSize = static_cast<unsigned>(
252 Context.getTypeSize(Context.LongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000253
254 // Does it fit in a unsigned long?
255 if (ResultVal.isIntN(LongSize)) {
256 // Does it fit in a signed long?
257 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
258 t = Context.LongTy;
259 else if (AllowUnsigned)
260 t = Context.UnsignedLongTy;
261 }
262 if (!t.isNull())
263 ResultVal.trunc(LongSize);
264 }
265
266 // Finally, check long long if needed.
267 if (t.isNull()) {
Chris Lattner3496d522007-09-04 02:45:27 +0000268 unsigned LongLongSize = static_cast<unsigned>(
269 Context.getTypeSize(Context.LongLongTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000270
271 // Does it fit in a unsigned long long?
272 if (ResultVal.isIntN(LongLongSize)) {
273 // Does it fit in a signed long long?
274 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
275 t = Context.LongLongTy;
276 else if (AllowUnsigned)
277 t = Context.UnsignedLongLongTy;
278 }
279 }
280
281 // If we still couldn't decide a type, we probably have something that
282 // does not fit in a signed long long, but has no U suffix.
283 if (t.isNull()) {
284 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
285 t = Context.UnsignedLongLongTy;
286 }
287 }
288
Chris Lattner1de66eb2007-08-26 03:42:43 +0000289 Res = new IntegerLiteral(ResultVal, t, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000290 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000291
292 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
293 if (Literal.isImaginary)
294 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
295
296 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000297}
298
Steve Naroff87d58b42007-09-16 03:34:24 +0000299Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000300 ExprTy *Val) {
301 Expr *e = (Expr *)Val;
Steve Naroff87d58b42007-09-16 03:34:24 +0000302 assert((e != 0) && "ActOnParenExpr() missing expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000303 return new ParenExpr(L, R, e);
304}
305
306/// The UsualUnaryConversions() function is *not* called by this routine.
307/// See C99 6.3.2.1p[2-4] for more details.
308QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
309 SourceLocation OpLoc, bool isSizeof) {
310 // C99 6.5.3.4p1:
311 if (isa<FunctionType>(exprType) && isSizeof)
312 // alignof(function) is allowed.
313 Diag(OpLoc, diag::ext_sizeof_function_type);
314 else if (exprType->isVoidType())
315 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
316 else if (exprType->isIncompleteType()) {
317 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
318 diag::err_alignof_incomplete_type,
319 exprType.getAsString());
320 return QualType(); // error
321 }
322 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
323 return Context.getSizeType();
324}
325
326Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000327ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000328 SourceLocation LPLoc, TypeTy *Ty,
329 SourceLocation RPLoc) {
330 // If error parsing type, ignore.
331 if (Ty == 0) return true;
332
333 // Verify that this is a valid expression.
334 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
335
336 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
337
338 if (resultType.isNull())
339 return true;
340 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
341}
342
Chris Lattner5110ad52007-08-24 21:41:10 +0000343QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000344 DefaultFunctionArrayConversion(V);
345
Chris Lattnera16e42d2007-08-26 05:39:26 +0000346 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000347 if (const ComplexType *CT = V->getType()->getAsComplexType())
348 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000349
350 // Otherwise they pass through real integer and floating point types here.
351 if (V->getType()->isArithmeticType())
352 return V->getType();
353
354 // Reject anything else.
355 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
356 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000357}
358
359
Chris Lattner4b009652007-07-25 00:24:17 +0000360
Steve Naroff87d58b42007-09-16 03:34:24 +0000361Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000362 tok::TokenKind Kind,
363 ExprTy *Input) {
364 UnaryOperator::Opcode Opc;
365 switch (Kind) {
366 default: assert(0 && "Unknown unary op!");
367 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
368 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
369 }
370 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
371 if (result.isNull())
372 return true;
373 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
374}
375
376Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000377ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000378 ExprTy *Idx, SourceLocation RLoc) {
379 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
380
381 // Perform default conversions.
382 DefaultFunctionArrayConversion(LHSExp);
383 DefaultFunctionArrayConversion(RHSExp);
384
385 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
386
387 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000388 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000389 // in the subscript position. As a result, we need to derive the array base
390 // and index from the expression types.
391 Expr *BaseExpr, *IndexExpr;
392 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000393 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000394 BaseExpr = LHSExp;
395 IndexExpr = RHSExp;
396 // FIXME: need to deal with const...
397 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000398 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000399 // Handle the uncommon case of "123[Ptr]".
400 BaseExpr = RHSExp;
401 IndexExpr = LHSExp;
402 // FIXME: need to deal with const...
403 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000404 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
405 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000406 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000407
408 // Component access limited to variables (reject vec4.rg[1]).
409 if (!isa<DeclRefExpr>(BaseExpr))
410 return Diag(LLoc, diag::err_ocuvector_component_access,
411 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000412 // FIXME: need to deal with const...
413 ResultType = VTy->getElementType();
414 } else {
415 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
416 RHSExp->getSourceRange());
417 }
418 // C99 6.5.2.1p1
419 if (!IndexExpr->getType()->isIntegerType())
420 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
421 IndexExpr->getSourceRange());
422
423 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
424 // the following check catches trying to index a pointer to a function (e.g.
425 // void (*)(int)). Functions are not objects in C99.
426 if (!ResultType->isObjectType())
427 return Diag(BaseExpr->getLocStart(),
428 diag::err_typecheck_subscript_not_object,
429 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
430
431 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
432}
433
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000434QualType Sema::
435CheckOCUVectorComponent(QualType baseType, SourceLocation OpLoc,
436 IdentifierInfo &CompName, SourceLocation CompLoc) {
Chris Lattnere35a1042007-07-31 19:29:30 +0000437 const OCUVectorType *vecType = baseType->getAsOCUVectorType();
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000438
439 // The vector accessor can't exceed the number of elements.
440 const char *compStr = CompName.getName();
441 if (strlen(compStr) > vecType->getNumElements()) {
442 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
443 baseType.getAsString(), SourceRange(CompLoc));
444 return QualType();
445 }
446 // The component names must come from the same set.
Chris Lattner9096b792007-08-02 22:33:49 +0000447 if (vecType->getPointAccessorIdx(*compStr) != -1) {
448 do
449 compStr++;
450 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
451 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
452 do
453 compStr++;
454 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
455 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
456 do
457 compStr++;
458 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
459 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000460
461 if (*compStr) {
462 // We didn't get to the end of the string. This means the component names
463 // didn't come from the same set *or* we encountered an illegal name.
464 Diag(OpLoc, diag::err_ocuvector_component_name_illegal,
465 std::string(compStr,compStr+1), SourceRange(CompLoc));
466 return QualType();
467 }
468 // Each component accessor can't exceed the vector type.
469 compStr = CompName.getName();
470 while (*compStr) {
471 if (vecType->isAccessorWithinNumElements(*compStr))
472 compStr++;
473 else
474 break;
475 }
476 if (*compStr) {
477 // We didn't get to the end of the string. This means a component accessor
478 // exceeds the number of elements in the vector.
479 Diag(OpLoc, diag::err_ocuvector_component_exceeds_length,
480 baseType.getAsString(), SourceRange(CompLoc));
481 return QualType();
482 }
483 // The component accessor looks fine - now we need to compute the actual type.
484 // The vector type is implied by the component accessor. For example,
485 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
486 unsigned CompSize = strlen(CompName.getName());
487 if (CompSize == 1)
488 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000489
490 QualType VT = Context.getOCUVectorType(vecType->getElementType(), CompSize);
491 // Now look up the TypeDefDecl from the vector type. Without this,
492 // diagostics look bad. We want OCU vector types to appear built-in.
493 for (unsigned i = 0, e = OCUVectorDecls.size(); i != e; ++i) {
494 if (OCUVectorDecls[i]->getUnderlyingType() == VT)
495 return Context.getTypedefType(OCUVectorDecls[i]);
496 }
497 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000498}
499
Chris Lattner4b009652007-07-25 00:24:17 +0000500Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000501ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000502 tok::TokenKind OpKind, SourceLocation MemberLoc,
503 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000504 Expr *BaseExpr = static_cast<Expr *>(Base);
505 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000506
507 // Perform default conversions.
508 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000509
Steve Naroff2cb66382007-07-26 03:11:44 +0000510 QualType BaseType = BaseExpr->getType();
511 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000512
Chris Lattner4b009652007-07-25 00:24:17 +0000513 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000514 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000515 BaseType = PT->getPointeeType();
516 else
517 return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
518 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000519 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000520 // The base type is either a record or an OCUVectorType.
Chris Lattnere35a1042007-07-31 19:29:30 +0000521 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000522 RecordDecl *RDecl = RTy->getDecl();
523 if (RTy->isIncompleteType())
524 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
525 BaseExpr->getSourceRange());
526 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000527 FieldDecl *MemberDecl = RDecl->getMember(&Member);
528 if (!MemberDecl)
Steve Naroff2cb66382007-07-26 03:11:44 +0000529 return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
530 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000531 return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl, MemberLoc);
532 } else if (BaseType->isOCUVectorType() && OpKind == tok::period) {
Steve Naroff89345522007-08-03 22:40:33 +0000533 // Component access limited to variables (reject vec4.rg.g).
534 if (!isa<DeclRefExpr>(BaseExpr))
535 return Diag(OpLoc, diag::err_ocuvector_component_access,
536 SourceRange(MemberLoc));
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000537 QualType ret = CheckOCUVectorComponent(BaseType, OpLoc, Member, MemberLoc);
538 if (ret.isNull())
539 return true;
Chris Lattnera0d03a72007-08-03 17:31:20 +0000540 return new OCUVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000541 } else if (BaseType->isObjcInterfaceType()) {
542 ObjcInterfaceDecl *IFace;
543 if (isa<ObjcInterfaceType>(BaseType.getCanonicalType()))
544 IFace = dyn_cast<ObjcInterfaceType>(BaseType)->getDecl();
545 else
Fariborz Jahanian0c2f2142007-12-13 20:47:42 +0000546 IFace = dyn_cast<ObjcQualifiedInterfaceType>(BaseType)->getDecl();
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000547 ObjcInterfaceDecl *clsDeclared;
548 if (ObjcIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
549 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
550 OpKind==tok::arrow);
551 }
552 return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
553 SourceRange(MemberLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000554}
555
Steve Naroff87d58b42007-09-16 03:34:24 +0000556/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +0000557/// This provides the location of the left/right parens and a list of comma
558/// locations.
559Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000560ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000561 ExprTy **args, unsigned NumArgsInCall,
562 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
563 Expr *Fn = static_cast<Expr *>(fn);
564 Expr **Args = reinterpret_cast<Expr**>(args);
565 assert(Fn && "no function call expression");
566
567 UsualUnaryConversions(Fn);
568 QualType funcType = Fn->getType();
569
570 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
571 // type pointer to function".
Chris Lattner71225142007-07-31 21:27:01 +0000572 const PointerType *PT = funcType->getAsPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +0000573 if (PT == 0)
574 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
575 SourceRange(Fn->getLocStart(), RParenLoc));
576
Chris Lattner71225142007-07-31 21:27:01 +0000577 const FunctionType *funcT = PT->getPointeeType()->getAsFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +0000578 if (funcT == 0)
579 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
580 SourceRange(Fn->getLocStart(), RParenLoc));
581
582 // If a prototype isn't declared, the parser implicitly defines a func decl
583 QualType resultType = funcT->getResultType();
584
585 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcT)) {
586 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
587 // assignment, to the types of the corresponding parameter, ...
588
589 unsigned NumArgsInProto = proto->getNumArgs();
590 unsigned NumArgsToCheck = NumArgsInCall;
591
592 if (NumArgsInCall < NumArgsInProto)
593 Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
594 Fn->getSourceRange());
595 else if (NumArgsInCall > NumArgsInProto) {
596 if (!proto->isVariadic()) {
597 Diag(Args[NumArgsInProto]->getLocStart(),
598 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
599 SourceRange(Args[NumArgsInProto]->getLocStart(),
600 Args[NumArgsInCall-1]->getLocEnd()));
601 }
602 NumArgsToCheck = NumArgsInProto;
603 }
604 // Continue to check argument types (even if we have too few/many args).
605 for (unsigned i = 0; i < NumArgsToCheck; i++) {
606 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000607 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000608
609 QualType lhsType = proto->getArgType(i);
610 QualType rhsType = argExpr->getType();
611
Steve Naroff75644062007-07-25 20:45:33 +0000612 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattnere35a1042007-07-31 19:29:30 +0000613 if (const ArrayType *ary = lhsType->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000614 lhsType = Context.getPointerType(ary->getElementType());
Steve Naroff75644062007-07-25 20:45:33 +0000615 else if (lhsType->isFunctionType())
Chris Lattner4b009652007-07-25 00:24:17 +0000616 lhsType = Context.getPointerType(lhsType);
617
618 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
619 argExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +0000620 if (Args[i] != argExpr) // The expression was converted.
621 Args[i] = argExpr; // Make sure we store the converted expression.
Chris Lattner4b009652007-07-25 00:24:17 +0000622 SourceLocation l = argExpr->getLocStart();
623
624 // decode the result (notice that AST's are still created for extensions).
625 switch (result) {
626 case Compatible:
627 break;
628 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +0000629 Diag(l, diag::ext_typecheck_passing_pointer_int,
630 lhsType.getAsString(), rhsType.getAsString(),
631 Fn->getSourceRange(), argExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000632 break;
633 case IntFromPointer:
634 Diag(l, diag::ext_typecheck_passing_pointer_int,
635 lhsType.getAsString(), rhsType.getAsString(),
636 Fn->getSourceRange(), argExpr->getSourceRange());
637 break;
638 case IncompatiblePointer:
639 Diag(l, diag::ext_typecheck_passing_incompatible_pointer,
640 rhsType.getAsString(), lhsType.getAsString(),
641 Fn->getSourceRange(), argExpr->getSourceRange());
642 break;
643 case CompatiblePointerDiscardsQualifiers:
644 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
645 rhsType.getAsString(), lhsType.getAsString(),
646 Fn->getSourceRange(), argExpr->getSourceRange());
647 break;
648 case Incompatible:
649 return Diag(l, diag::err_typecheck_passing_incompatible,
650 rhsType.getAsString(), lhsType.getAsString(),
651 Fn->getSourceRange(), argExpr->getSourceRange());
652 }
653 }
Steve Naroffdb65e052007-08-28 23:30:39 +0000654 if (NumArgsInCall > NumArgsInProto && proto->isVariadic()) {
655 // Promote the arguments (C99 6.5.2.2p7).
656 for (unsigned i = NumArgsInProto; i < NumArgsInCall; i++) {
657 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000658 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000659
660 DefaultArgumentPromotion(argExpr);
661 if (Args[i] != argExpr) // The expression was converted.
662 Args[i] = argExpr; // Make sure we store the converted expression.
663 }
664 } else if (NumArgsInCall != NumArgsInProto && !proto->isVariadic()) {
665 // Even if the types checked, bail if the number of arguments don't match.
Chris Lattner4b009652007-07-25 00:24:17 +0000666 return true;
Steve Naroffdb65e052007-08-28 23:30:39 +0000667 }
668 } else if (isa<FunctionTypeNoProto>(funcT)) {
669 // Promote the arguments (C99 6.5.2.2p6).
670 for (unsigned i = 0; i < NumArgsInCall; i++) {
671 Expr *argExpr = Args[i];
Steve Naroff87d58b42007-09-16 03:34:24 +0000672 assert(argExpr && "ActOnCallExpr(): missing argument expression");
Steve Naroffdb65e052007-08-28 23:30:39 +0000673
674 DefaultArgumentPromotion(argExpr);
675 if (Args[i] != argExpr) // The expression was converted.
676 Args[i] = argExpr; // Make sure we store the converted expression.
677 }
Chris Lattner4b009652007-07-25 00:24:17 +0000678 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000679 // Do special checking on direct calls to functions.
680 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
681 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
682 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()))
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000683 if (CheckFunctionCall(Fn, LParenLoc, RParenLoc, FDecl, Args,
684 NumArgsInCall))
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000685 return true;
Chris Lattner2e64c072007-08-10 20:18:51 +0000686
Chris Lattner4b009652007-07-25 00:24:17 +0000687 return new CallExpr(Fn, Args, NumArgsInCall, resultType, RParenLoc);
688}
689
690Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000691ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000692 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000693 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +0000694 QualType literalType = QualType::getFromOpaquePtr(Ty);
695 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +0000696 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000697 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +0000698
Steve Naroffcb69fb72007-12-10 22:44:33 +0000699 // FIXME: add more semantic analysis (C99 6.5.2.5).
700 if (CheckInitializer(literalExpr, literalType, false))
701 return 0;
Anders Carlsson9374b852007-12-05 07:24:19 +0000702
Chris Lattner4b009652007-07-25 00:24:17 +0000703 return new CompoundLiteralExpr(literalType, literalExpr);
704}
705
706Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000707ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Anders Carlsson762b7c72007-08-31 04:56:16 +0000708 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000709 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +0000710
Steve Naroff0acc9c92007-09-15 18:49:24 +0000711 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +0000712 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +0000713
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000714 InitListExpr *e = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
715 e->setType(Context.VoidTy); // FIXME: just a place holder for now.
716 return e;
Chris Lattner4b009652007-07-25 00:24:17 +0000717}
718
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000719bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty)
720{
721 assert(VectorTy->isVectorType() && "Not a vector type!");
722
723 if (Ty->isVectorType() || Ty->isIntegerType()) {
724 if (Context.getTypeSize(VectorTy, SourceLocation()) !=
725 Context.getTypeSize(Ty, SourceLocation()))
726 return Diag(R.getBegin(),
727 Ty->isVectorType() ?
728 diag::err_invalid_conversion_between_vectors :
729 diag::err_invalid_conversion_between_vector_and_integer,
730 VectorTy.getAsString().c_str(),
731 Ty.getAsString().c_str(), R);
732 } else
733 return Diag(R.getBegin(),
734 diag::err_invalid_conversion_between_vector_and_scalar,
735 VectorTy.getAsString().c_str(),
736 Ty.getAsString().c_str(), R);
737
738 return false;
739}
740
Chris Lattner4b009652007-07-25 00:24:17 +0000741Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000742ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +0000743 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +0000744 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +0000745
746 Expr *castExpr = static_cast<Expr*>(Op);
747 QualType castType = QualType::getFromOpaquePtr(Ty);
748
Steve Naroff68adb482007-08-31 00:32:44 +0000749 UsualUnaryConversions(castExpr);
750
Chris Lattner4b009652007-07-25 00:24:17 +0000751 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
752 // type needs to be scalar.
Chris Lattnerdb526732007-10-29 04:26:44 +0000753 if (!castType->isVoidType()) { // Cast to void allows any expr type.
754 if (!castType->isScalarType())
755 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
756 castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000757 if (!castExpr->getType()->isScalarType())
Chris Lattnerdb526732007-10-29 04:26:44 +0000758 return Diag(castExpr->getLocStart(),
759 diag::err_typecheck_expect_scalar_operand,
760 castExpr->getType().getAsString(),castExpr->getSourceRange());
Anders Carlssonf257b4c2007-11-27 05:51:55 +0000761
762 if (castExpr->getType()->isVectorType()) {
763 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
764 castExpr->getType(), castType))
765 return true;
766 } else if (castType->isVectorType()) {
767 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
768 castType, castExpr->getType()))
769 return true;
Chris Lattnerdb526732007-10-29 04:26:44 +0000770 }
Chris Lattner4b009652007-07-25 00:24:17 +0000771 }
772 return new CastExpr(castType, castExpr, LParenLoc);
773}
774
Steve Naroff144667e2007-10-18 05:13:08 +0000775// promoteExprToType - a helper function to ensure we create exactly one
776// ImplicitCastExpr.
777static void promoteExprToType(Expr *&expr, QualType type) {
778 if (ImplicitCastExpr *impCast = dyn_cast<ImplicitCastExpr>(expr))
779 impCast->setType(type);
780 else
781 expr = new ImplicitCastExpr(type, expr);
782 return;
783}
784
Chris Lattner98a425c2007-11-26 01:40:58 +0000785/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
786/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +0000787inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
788 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
789 UsualUnaryConversions(cond);
790 UsualUnaryConversions(lex);
791 UsualUnaryConversions(rex);
792 QualType condT = cond->getType();
793 QualType lexT = lex->getType();
794 QualType rexT = rex->getType();
795
796 // first, check the condition.
797 if (!condT->isScalarType()) { // C99 6.5.15p2
798 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
799 condT.getAsString());
800 return QualType();
801 }
802 // now check the two expressions.
803 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { // C99 6.5.15p3,5
804 UsualArithmeticConversions(lex, rex);
805 return lex->getType();
806 }
Chris Lattner71225142007-07-31 21:27:01 +0000807 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
808 if (const RecordType *RHSRT = rexT->getAsRecordType()) {
Chris Lattner98a425c2007-11-26 01:40:58 +0000809 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner71225142007-07-31 21:27:01 +0000810 return lexT;
811
Chris Lattner4b009652007-07-25 00:24:17 +0000812 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
813 lexT.getAsString(), rexT.getAsString(),
814 lex->getSourceRange(), rex->getSourceRange());
815 return QualType();
816 }
817 }
818 // C99 6.5.15p3
Steve Naroff144667e2007-10-18 05:13:08 +0000819 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
820 promoteExprToType(rex, lexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000821 return lexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000822 }
823 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
824 promoteExprToType(lex, rexT); // promote the null to a pointer.
Chris Lattner4b009652007-07-25 00:24:17 +0000825 return rexT;
Steve Naroff144667e2007-10-18 05:13:08 +0000826 }
Chris Lattner71225142007-07-31 21:27:01 +0000827 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
828 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
829 // get the "pointed to" types
830 QualType lhptee = LHSPT->getPointeeType();
831 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +0000832
Chris Lattner71225142007-07-31 21:27:01 +0000833 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
834 if (lhptee->isVoidType() &&
835 (rhptee->isObjectType() || rhptee->isIncompleteType()))
836 return lexT;
837 if (rhptee->isVoidType() &&
838 (lhptee->isObjectType() || lhptee->isIncompleteType()))
839 return rexT;
Chris Lattner4b009652007-07-25 00:24:17 +0000840
Steve Naroff85f0dc52007-10-15 20:41:53 +0000841 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
842 rhptee.getUnqualifiedType())) {
Chris Lattner71225142007-07-31 21:27:01 +0000843 Diag(questionLoc, diag::ext_typecheck_cond_incompatible_pointers,
844 lexT.getAsString(), rexT.getAsString(),
845 lex->getSourceRange(), rex->getSourceRange());
846 return lexT; // FIXME: this is an _ext - is this return o.k?
847 }
848 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000849 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
850 // differently qualified versions of compatible types, the result type is
851 // a pointer to an appropriately qualified version of the *composite*
852 // type.
Chris Lattner71225142007-07-31 21:27:01 +0000853 return lexT; // FIXME: Need to return the composite type.
Chris Lattner4b009652007-07-25 00:24:17 +0000854 }
Chris Lattner4b009652007-07-25 00:24:17 +0000855 }
Chris Lattner71225142007-07-31 21:27:01 +0000856
Chris Lattner4b009652007-07-25 00:24:17 +0000857 if (lexT->isVoidType() && rexT->isVoidType()) // C99 6.5.15p3
858 return lexT;
859
860 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
861 lexT.getAsString(), rexT.getAsString(),
862 lex->getSourceRange(), rex->getSourceRange());
863 return QualType();
864}
865
Steve Naroff87d58b42007-09-16 03:34:24 +0000866/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +0000867/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +0000868Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000869 SourceLocation ColonLoc,
870 ExprTy *Cond, ExprTy *LHS,
871 ExprTy *RHS) {
872 Expr *CondExpr = (Expr *) Cond;
873 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +0000874
875 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
876 // was the condition.
877 bool isLHSNull = LHSExpr == 0;
878 if (isLHSNull)
879 LHSExpr = CondExpr;
880
Chris Lattner4b009652007-07-25 00:24:17 +0000881 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
882 RHSExpr, QuestionLoc);
883 if (result.isNull())
884 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +0000885 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
886 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +0000887}
888
Steve Naroffdb65e052007-08-28 23:30:39 +0000889/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
890/// do not have a prototype. Integer promotions are performed on each
891/// argument, and arguments that have type float are promoted to double.
892void Sema::DefaultArgumentPromotion(Expr *&expr) {
893 QualType t = expr->getType();
894 assert(!t.isNull() && "DefaultArgumentPromotion - missing type");
895
896 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
897 promoteExprToType(expr, Context.IntTy);
898 if (t == Context.FloatTy)
899 promoteExprToType(expr, Context.DoubleTy);
900}
901
Chris Lattner4b009652007-07-25 00:24:17 +0000902/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
903void Sema::DefaultFunctionArrayConversion(Expr *&e) {
904 QualType t = e->getType();
905 assert(!t.isNull() && "DefaultFunctionArrayConversion - missing type");
906
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000907 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000908 promoteExprToType(e, ref->getReferenceeType()); // C++ [expr]
909 t = e->getType();
910 }
911 if (t->isFunctionType())
912 promoteExprToType(e, Context.getPointerType(t));
Chris Lattnere35a1042007-07-31 19:29:30 +0000913 else if (const ArrayType *ary = t->getAsArrayType())
Chris Lattner4b009652007-07-25 00:24:17 +0000914 promoteExprToType(e, Context.getPointerType(ary->getElementType()));
915}
916
917/// UsualUnaryConversion - Performs various conversions that are common to most
918/// operators (C99 6.3). The conversions of array and function types are
919/// sometimes surpressed. For example, the array->pointer conversion doesn't
920/// apply if the array is an argument to the sizeof or address (&) operators.
921/// In these instances, this routine should *not* be called.
922void Sema::UsualUnaryConversions(Expr *&expr) {
923 QualType t = expr->getType();
924 assert(!t.isNull() && "UsualUnaryConversions - missing type");
925
Chris Lattnerf0c4a0a2007-07-31 16:56:34 +0000926 if (const ReferenceType *ref = t->getAsReferenceType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000927 promoteExprToType(expr, ref->getReferenceeType()); // C++ [expr]
928 t = expr->getType();
929 }
930 if (t->isPromotableIntegerType()) // C99 6.3.1.1p2
931 promoteExprToType(expr, Context.IntTy);
932 else
933 DefaultFunctionArrayConversion(expr);
934}
935
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000936/// UsualArithmeticConversions - Performs various conversions that are common to
Chris Lattner4b009652007-07-25 00:24:17 +0000937/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
938/// routine returns the first non-arithmetic type found. The client is
939/// responsible for emitting appropriate error diagnostics.
Steve Naroff8f708362007-08-24 19:07:16 +0000940QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
941 bool isCompAssign) {
Steve Naroffb2f9f552007-08-25 19:54:59 +0000942 if (!isCompAssign) {
943 UsualUnaryConversions(lhsExpr);
944 UsualUnaryConversions(rhsExpr);
945 }
Steve Naroff7438fdf2007-10-18 18:55:53 +0000946 // For conversion purposes, we ignore any qualifiers.
947 // For example, "const float" and "float" are equivalent.
Steve Naroff1ddb6f52007-11-10 19:45:54 +0000948 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
949 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +0000950
951 // If both types are identical, no conversion is needed.
Steve Naroff7438fdf2007-10-18 18:55:53 +0000952 if (lhs == rhs)
953 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000954
955 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
956 // The caller can deal with this (e.g. pointer + int).
957 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +0000958 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000959
960 // At this point, we have two different arithmetic types.
961
962 // Handle complex types first (C99 6.3.1.8p1).
963 if (lhs->isComplexType() || rhs->isComplexType()) {
964 // if we have an integer operand, the result is the complex type.
965 if (rhs->isIntegerType()) { // convert the rhs to the lhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000966 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
967 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000968 }
969 if (lhs->isIntegerType()) { // convert the lhs to the rhs complex type.
Steve Naroff8f708362007-08-24 19:07:16 +0000970 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
971 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +0000972 }
Steve Naroff3cf497f2007-08-27 01:27:54 +0000973 // This handles complex/complex, complex/float, or float/complex.
974 // When both operands are complex, the shorter operand is converted to the
975 // type of the longer, and that is the type of the result. This corresponds
976 // to what is done when combining two real floating-point operands.
977 // The fun begins when size promotion occur across type domains.
978 // From H&S 6.3.4: When one operand is complex and the other is a real
979 // floating-point type, the less precise type is converted, within it's
980 // real or complex domain, to the precision of the other type. For example,
981 // when combining a "long double" with a "double _Complex", the
982 // "double _Complex" is promoted to "long double _Complex".
Steve Naroff45fc9822007-08-27 15:30:22 +0000983 int result = Context.compareFloatingType(lhs, rhs);
984
985 if (result > 0) { // The left side is bigger, convert rhs.
Steve Naroff3b565d62007-08-27 21:32:55 +0000986 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
987 if (!isCompAssign)
988 promoteExprToType(rhsExpr, rhs);
989 } else if (result < 0) { // The right side is bigger, convert lhs.
990 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
991 if (!isCompAssign)
992 promoteExprToType(lhsExpr, lhs);
993 }
994 // At this point, lhs and rhs have the same rank/size. Now, make sure the
995 // domains match. This is a requirement for our implementation, C99
996 // does not require this promotion.
997 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
998 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Steve Naroff3b6157f2007-08-27 21:43:43 +0000999 if (!isCompAssign)
1000 promoteExprToType(lhsExpr, rhs);
1001 return rhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001002 } else { // handle "_Complex double, double".
Steve Naroff3b6157f2007-08-27 21:43:43 +00001003 if (!isCompAssign)
1004 promoteExprToType(rhsExpr, lhs);
1005 return lhs;
Steve Naroff3b565d62007-08-27 21:32:55 +00001006 }
Chris Lattner4b009652007-07-25 00:24:17 +00001007 }
Steve Naroff3b6157f2007-08-27 21:43:43 +00001008 return lhs; // The domain/size match exactly.
Chris Lattner4b009652007-07-25 00:24:17 +00001009 }
1010 // Now handle "real" floating types (i.e. float, double, long double).
1011 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1012 // if we have an integer operand, the result is the real floating type.
1013 if (rhs->isIntegerType()) { // convert rhs to the lhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001014 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1015 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001016 }
1017 if (lhs->isIntegerType()) { // convert lhs to the rhs floating point type.
Steve Naroff8f708362007-08-24 19:07:16 +00001018 if (!isCompAssign) promoteExprToType(lhsExpr, rhs);
1019 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001020 }
1021 // We have two real floating types, float/complex combos were handled above.
1022 // Convert the smaller operand to the bigger result.
Steve Naroff45fc9822007-08-27 15:30:22 +00001023 int result = Context.compareFloatingType(lhs, rhs);
1024
1025 if (result > 0) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001026 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1027 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001028 }
Steve Naroff45fc9822007-08-27 15:30:22 +00001029 if (result < 0) { // convert the lhs
1030 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1031 return rhs;
1032 }
1033 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
Chris Lattner4b009652007-07-25 00:24:17 +00001034 }
1035 // Finally, we have two differing integer types.
1036 if (Context.maxIntegerType(lhs, rhs) == lhs) { // convert the rhs
Steve Naroff8f708362007-08-24 19:07:16 +00001037 if (!isCompAssign) promoteExprToType(rhsExpr, lhs);
1038 return lhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001039 }
Steve Naroff8f708362007-08-24 19:07:16 +00001040 if (!isCompAssign) promoteExprToType(lhsExpr, rhs); // convert the lhs
1041 return rhs;
Chris Lattner4b009652007-07-25 00:24:17 +00001042}
1043
1044// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1045// being closely modeled after the C99 spec:-). The odd characteristic of this
1046// routine is it effectively iqnores the qualifiers on the top level pointee.
1047// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1048// FIXME: add a couple examples in this comment.
1049Sema::AssignmentCheckResult
1050Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1051 QualType lhptee, rhptee;
1052
1053 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001054 lhptee = lhsType->getAsPointerType()->getPointeeType();
1055 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001056
1057 // make sure we operate on the canonical type
1058 lhptee = lhptee.getCanonicalType();
1059 rhptee = rhptee.getCanonicalType();
1060
1061 AssignmentCheckResult r = Compatible;
1062
1063 // C99 6.5.16.1p1: This following citation is common to constraints
1064 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1065 // qualifiers of the type *pointed to* by the right;
1066 if ((lhptee.getQualifiers() & rhptee.getQualifiers()) !=
1067 rhptee.getQualifiers())
1068 r = CompatiblePointerDiscardsQualifiers;
1069
1070 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1071 // incomplete type and the other is a pointer to a qualified or unqualified
1072 // version of void...
1073 if (lhptee.getUnqualifiedType()->isVoidType() &&
1074 (rhptee->isObjectType() || rhptee->isIncompleteType()))
1075 ;
1076 else if (rhptee.getUnqualifiedType()->isVoidType() &&
1077 (lhptee->isObjectType() || lhptee->isIncompleteType()))
1078 ;
1079 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1080 // unqualified versions of compatible types, ...
Steve Naroff85f0dc52007-10-15 20:41:53 +00001081 else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1082 rhptee.getUnqualifiedType()))
Chris Lattner4b009652007-07-25 00:24:17 +00001083 r = IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1084 return r;
1085}
1086
1087/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1088/// has code to accommodate several GCC extensions when type checking
1089/// pointers. Here are some objectionable examples that GCC considers warnings:
1090///
1091/// int a, *pint;
1092/// short *pshort;
1093/// struct foo *pfoo;
1094///
1095/// pint = pshort; // warning: assignment from incompatible pointer type
1096/// a = pint; // warning: assignment makes integer from pointer without a cast
1097/// pint = a; // warning: assignment makes pointer from integer without a cast
1098/// pint = pfoo; // warning: assignment from incompatible pointer type
1099///
1100/// As a result, the code for dealing with pointers is more complex than the
1101/// C99 spec dictates.
1102/// Note: the warning above turn into errors when -pedantic-errors is enabled.
1103///
1104Sema::AssignmentCheckResult
1105Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001106
1107
Steve Naroffeed76842007-11-13 00:31:42 +00001108 if (lhsType.getCanonicalType().getUnqualifiedType() ==
1109 rhsType.getCanonicalType().getUnqualifiedType())
Chris Lattnera703c2e2007-10-29 05:15:40 +00001110 return Compatible; // common case, fast path...
Chris Lattner4b009652007-07-25 00:24:17 +00001111
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001112 if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001113 if (Context.referenceTypesAreCompatible(lhsType, rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001114 return Compatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001115 }
1116 else if (lhsType->isObjcQualifiedIdType()
1117 || rhsType->isObjcQualifiedIdType()) {
1118 if (Context.ObjcQualifiedIdTypesAreCompatible(lhsType, rhsType))
1119 return Compatible;
1120 }
1121 else if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001122 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Anders Carlssone87cd982007-11-30 04:21:22 +00001123 if (!getLangOptions().LaxVectorConversions) {
1124 if (lhsType.getCanonicalType() != rhsType.getCanonicalType())
1125 return Incompatible;
1126 } else {
1127 if (lhsType->isVectorType() && rhsType->isVectorType()) {
1128 if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1129 (lhsType->isRealFloatingType() &&
1130 rhsType->isRealFloatingType())) {
1131 if (Context.getTypeSize(lhsType, SourceLocation()) ==
1132 Context.getTypeSize(rhsType, SourceLocation()))
1133 return Compatible;
1134 }
1135 }
Chris Lattner4b009652007-07-25 00:24:17 +00001136 return Incompatible;
Anders Carlssone87cd982007-11-30 04:21:22 +00001137 }
1138 }
Chris Lattner4b009652007-07-25 00:24:17 +00001139 return Compatible;
1140 } else if (lhsType->isPointerType()) {
1141 if (rhsType->isIntegerType())
1142 return PointerFromInt;
1143
1144 if (rhsType->isPointerType())
1145 return CheckPointerTypesForAssignment(lhsType, rhsType);
1146 } else if (rhsType->isPointerType()) {
1147 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1148 if ((lhsType->isIntegerType()) && (lhsType != Context.BoolTy))
1149 return IntFromPointer;
1150
1151 if (lhsType->isPointerType())
1152 return CheckPointerTypesForAssignment(lhsType, rhsType);
1153 } else if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Steve Naroff85f0dc52007-10-15 20:41:53 +00001154 if (Context.tagTypesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001155 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001156 }
1157 return Incompatible;
1158}
1159
1160Sema::AssignmentCheckResult
1161Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Steve Naroffcdee22d2007-11-27 17:58:44 +00001162 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1163 // a null pointer constant.
1164 if (lhsType->isPointerType() && rExpr->isNullPointerConstant(Context)) {
1165 promoteExprToType(rExpr, lhsType);
1166 return Compatible;
1167 }
Chris Lattner5f505bf2007-10-16 02:55:40 +00001168 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001169 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001170 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001171 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001172 //
1173 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references
1174 // are better understood.
1175 if (!lhsType->isReferenceType())
1176 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001177
1178 Sema::AssignmentCheckResult result;
Chris Lattner4b009652007-07-25 00:24:17 +00001179
Steve Naroff0f32f432007-08-24 22:33:52 +00001180 result = CheckAssignmentConstraints(lhsType, rExpr->getType());
1181
1182 // C99 6.5.16.1p2: The value of the right operand is converted to the
1183 // type of the assignment expression.
1184 if (rExpr->getType() != lhsType)
1185 promoteExprToType(rExpr, lhsType);
1186 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001187}
1188
1189Sema::AssignmentCheckResult
1190Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1191 return CheckAssignmentConstraints(lhsType, rhsType);
1192}
1193
Chris Lattner2c8bff72007-12-12 05:47:28 +00001194QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001195 Diag(loc, diag::err_typecheck_invalid_operands,
1196 lex->getType().getAsString(), rex->getType().getAsString(),
1197 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001198 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001199}
1200
1201inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1202 Expr *&rex) {
1203 QualType lhsType = lex->getType(), rhsType = rex->getType();
1204
1205 // make sure the vector types are identical.
1206 if (lhsType == rhsType)
1207 return lhsType;
1208 // You cannot convert between vector values of different size.
1209 Diag(loc, diag::err_typecheck_vector_not_convertable,
1210 lex->getType().getAsString(), rex->getType().getAsString(),
1211 lex->getSourceRange(), rex->getSourceRange());
1212 return QualType();
1213}
1214
1215inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001216 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001217{
1218 QualType lhsType = lex->getType(), rhsType = rex->getType();
1219
1220 if (lhsType->isVectorType() || rhsType->isVectorType())
1221 return CheckVectorOperands(loc, lex, rex);
1222
Steve Naroff8f708362007-08-24 19:07:16 +00001223 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001224
Chris Lattner4b009652007-07-25 00:24:17 +00001225 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001226 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001227 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001228}
1229
1230inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001231 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001232{
1233 QualType lhsType = lex->getType(), rhsType = rex->getType();
1234
Steve Naroff8f708362007-08-24 19:07:16 +00001235 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001236
Chris Lattner4b009652007-07-25 00:24:17 +00001237 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001238 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001239 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001240}
1241
1242inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001243 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001244{
1245 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1246 return CheckVectorOperands(loc, lex, rex);
1247
Steve Naroff8f708362007-08-24 19:07:16 +00001248 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001249
1250 // handle the common case first (both operands are arithmetic).
1251 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001252 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001253
1254 if (lex->getType()->isPointerType() && rex->getType()->isIntegerType())
1255 return lex->getType();
1256 if (lex->getType()->isIntegerType() && rex->getType()->isPointerType())
1257 return rex->getType();
Chris Lattner2c8bff72007-12-12 05:47:28 +00001258 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001259}
1260
1261inline QualType Sema::CheckSubtractionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001262 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001263{
1264 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1265 return CheckVectorOperands(loc, lex, rex);
1266
Steve Naroff8f708362007-08-24 19:07:16 +00001267 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001268
Chris Lattnerf6da2912007-12-09 21:53:25 +00001269 // Enforce type constraints: C99 6.5.6p3.
1270
1271 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001272 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001273 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001274
1275 // Either ptr - int or ptr - ptr.
1276 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1277 // The LHS must be an object type, not incomplete, function, etc.
1278 if (!LHSPTy->getPointeeType()->isObjectType()) {
1279 // Handle the GNU void* extension.
1280 if (LHSPTy->getPointeeType()->isVoidType()) {
1281 Diag(loc, diag::ext_gnu_void_ptr,
1282 lex->getSourceRange(), rex->getSourceRange());
1283 } else {
1284 Diag(loc, diag::err_typecheck_sub_ptr_object,
1285 lex->getType().getAsString(), lex->getSourceRange());
1286 return QualType();
1287 }
1288 }
1289
1290 // The result type of a pointer-int computation is the pointer type.
1291 if (rex->getType()->isIntegerType())
1292 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001293
Chris Lattnerf6da2912007-12-09 21:53:25 +00001294 // Handle pointer-pointer subtractions.
1295 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1296 // RHS must be an object type, unless void (GNU).
1297 if (!RHSPTy->getPointeeType()->isObjectType()) {
1298 // Handle the GNU void* extension.
1299 if (RHSPTy->getPointeeType()->isVoidType()) {
1300 if (!LHSPTy->getPointeeType()->isVoidType())
1301 Diag(loc, diag::ext_gnu_void_ptr,
1302 lex->getSourceRange(), rex->getSourceRange());
1303 } else {
1304 Diag(loc, diag::err_typecheck_sub_ptr_object,
1305 rex->getType().getAsString(), rex->getSourceRange());
1306 return QualType();
1307 }
1308 }
1309
1310 // Pointee types must be compatible.
1311 if (!Context.typesAreCompatible(LHSPTy->getPointeeType(),
1312 RHSPTy->getPointeeType())) {
1313 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1314 lex->getType().getAsString(), rex->getType().getAsString(),
1315 lex->getSourceRange(), rex->getSourceRange());
1316 return QualType();
1317 }
1318
1319 return Context.getPointerDiffType();
1320 }
1321 }
1322
Chris Lattner2c8bff72007-12-12 05:47:28 +00001323 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001324}
1325
1326inline QualType Sema::CheckShiftOperands( // C99 6.5.7
Chris Lattner2c8bff72007-12-12 05:47:28 +00001327 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) {
1328 // C99 6.5.7p2: Each of the operands shall have integer type.
1329 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1330 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001331
Chris Lattner2c8bff72007-12-12 05:47:28 +00001332 // Shifts don't perform usual arithmetic conversions, they just do integer
1333 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00001334 if (!isCompAssign)
1335 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00001336 UsualUnaryConversions(rex);
1337
1338 // "The type of the result is that of the promoted left operand."
1339 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001340}
1341
Chris Lattner254f3bc2007-08-26 01:18:55 +00001342inline QualType Sema::CheckCompareOperands( // C99 6.5.8
1343 Expr *&lex, Expr *&rex, SourceLocation loc, bool isRelational)
Chris Lattner4b009652007-07-25 00:24:17 +00001344{
Chris Lattner254f3bc2007-08-26 01:18:55 +00001345 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00001346 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1347 UsualArithmeticConversions(lex, rex);
1348 else {
1349 UsualUnaryConversions(lex);
1350 UsualUnaryConversions(rex);
1351 }
Chris Lattner4b009652007-07-25 00:24:17 +00001352 QualType lType = lex->getType();
1353 QualType rType = rex->getType();
1354
Ted Kremenek486509e2007-10-29 17:13:39 +00001355 // For non-floating point types, check for self-comparisons of the form
1356 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
1357 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00001358 if (!lType->isFloatingType()) {
1359 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(IgnoreParen(lex)))
1360 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(IgnoreParen(rex)))
1361 if (DRL->getDecl() == DRR->getDecl())
1362 Diag(loc, diag::warn_selfcomparison);
1363 }
1364
Chris Lattner254f3bc2007-08-26 01:18:55 +00001365 if (isRelational) {
1366 if (lType->isRealType() && rType->isRealType())
1367 return Context.IntTy;
1368 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00001369 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00001370 if (lType->isFloatingType()) {
1371 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00001372 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00001373 }
1374
Chris Lattner254f3bc2007-08-26 01:18:55 +00001375 if (lType->isArithmeticType() && rType->isArithmeticType())
1376 return Context.IntTy;
1377 }
Chris Lattner4b009652007-07-25 00:24:17 +00001378
Chris Lattner22be8422007-08-26 01:10:14 +00001379 bool LHSIsNull = lex->isNullPointerConstant(Context);
1380 bool RHSIsNull = rex->isNullPointerConstant(Context);
1381
Chris Lattner254f3bc2007-08-26 01:18:55 +00001382 // All of the following pointer related warnings are GCC extensions, except
1383 // when handling null pointer constants. One day, we can consider making them
1384 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00001385 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Steve Naroff3b435622007-11-13 14:57:38 +00001386
1387 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
1388 !lType->getAsPointerType()->getPointeeType()->isVoidType() &&
1389 !rType->getAsPointerType()->getPointeeType()->isVoidType() &&
Steve Naroff85f0dc52007-10-15 20:41:53 +00001390 !Context.pointerTypesAreCompatible(lType.getUnqualifiedType(),
1391 rType.getUnqualifiedType())) {
Steve Naroff4462cb02007-08-16 21:48:38 +00001392 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1393 lType.getAsString(), rType.getAsString(),
1394 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001395 }
Chris Lattner22be8422007-08-26 01:10:14 +00001396 promoteExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001397 return Context.IntTy;
1398 }
1399 if (lType->isPointerType() && rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001400 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001401 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1402 lType.getAsString(), rType.getAsString(),
1403 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001404 promoteExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001405 return Context.IntTy;
1406 }
1407 if (lType->isIntegerType() && rType->isPointerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00001408 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00001409 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1410 lType.getAsString(), rType.getAsString(),
1411 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner22be8422007-08-26 01:10:14 +00001412 promoteExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00001413 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001414 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00001415 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001416}
1417
Chris Lattner4b009652007-07-25 00:24:17 +00001418inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001419 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001420{
1421 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1422 return CheckVectorOperands(loc, lex, rex);
1423
Steve Naroff8f708362007-08-24 19:07:16 +00001424 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001425
1426 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001427 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001428 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001429}
1430
1431inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1432 Expr *&lex, Expr *&rex, SourceLocation loc)
1433{
1434 UsualUnaryConversions(lex);
1435 UsualUnaryConversions(rex);
1436
1437 if (lex->getType()->isScalarType() || rex->getType()->isScalarType())
1438 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001439 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001440}
1441
1442inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00001443 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00001444{
1445 QualType lhsType = lex->getType();
1446 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1447 bool hadError = false;
1448 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1449
1450 switch (mlval) { // C99 6.5.16p2
1451 case Expr::MLV_Valid:
1452 break;
1453 case Expr::MLV_ConstQualified:
1454 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1455 hadError = true;
1456 break;
1457 case Expr::MLV_ArrayType:
1458 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1459 lhsType.getAsString(), lex->getSourceRange());
1460 return QualType();
1461 case Expr::MLV_NotObjectType:
1462 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1463 lhsType.getAsString(), lex->getSourceRange());
1464 return QualType();
1465 case Expr::MLV_InvalidExpression:
1466 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1467 lex->getSourceRange());
1468 return QualType();
1469 case Expr::MLV_IncompleteType:
1470 case Expr::MLV_IncompleteVoidType:
1471 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1472 lhsType.getAsString(), lex->getSourceRange());
1473 return QualType();
Steve Naroffba67f692007-07-30 03:29:09 +00001474 case Expr::MLV_DuplicateVectorComponents:
1475 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1476 lex->getSourceRange());
1477 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001478 }
1479 AssignmentCheckResult result;
1480
1481 if (compoundType.isNull())
1482 result = CheckSingleAssignmentConstraints(lhsType, rex);
1483 else
1484 result = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001485
Chris Lattner4b009652007-07-25 00:24:17 +00001486 // decode the result (notice that extensions still return a type).
1487 switch (result) {
1488 case Compatible:
1489 break;
1490 case Incompatible:
1491 Diag(loc, diag::err_typecheck_assign_incompatible,
1492 lhsType.getAsString(), rhsType.getAsString(),
1493 lex->getSourceRange(), rex->getSourceRange());
1494 hadError = true;
1495 break;
1496 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +00001497 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1498 lhsType.getAsString(), rhsType.getAsString(),
1499 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001500 break;
1501 case IntFromPointer:
1502 Diag(loc, diag::ext_typecheck_assign_pointer_int,
1503 lhsType.getAsString(), rhsType.getAsString(),
1504 lex->getSourceRange(), rex->getSourceRange());
1505 break;
1506 case IncompatiblePointer:
1507 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
1508 lhsType.getAsString(), rhsType.getAsString(),
1509 lex->getSourceRange(), rex->getSourceRange());
1510 break;
1511 case CompatiblePointerDiscardsQualifiers:
1512 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
1513 lhsType.getAsString(), rhsType.getAsString(),
1514 lex->getSourceRange(), rex->getSourceRange());
1515 break;
1516 }
1517 // C99 6.5.16p3: The type of an assignment expression is the type of the
1518 // left operand unless the left operand has qualified type, in which case
1519 // it is the unqualified version of the type of the left operand.
1520 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1521 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001522 // C++ 5.17p1: the type of the assignment expression is that of its left
1523 // oprdu.
Chris Lattner4b009652007-07-25 00:24:17 +00001524 return hadError ? QualType() : lhsType.getUnqualifiedType();
1525}
1526
1527inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1528 Expr *&lex, Expr *&rex, SourceLocation loc) {
1529 UsualUnaryConversions(rex);
1530 return rex->getType();
1531}
1532
1533/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1534/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1535QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1536 QualType resType = op->getType();
1537 assert(!resType.isNull() && "no type for increment/decrement expression");
1538
Steve Naroffd30e1932007-08-24 17:20:07 +00001539 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00001540 if (const PointerType *pt = resType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001541 if (!pt->getPointeeType()->isObjectType()) { // C99 6.5.2.4p2, 6.5.6p2
1542 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1543 resType.getAsString(), op->getSourceRange());
1544 return QualType();
1545 }
Steve Naroffd30e1932007-08-24 17:20:07 +00001546 } else if (!resType->isRealType()) {
1547 if (resType->isComplexType())
1548 // C99 does not support ++/-- on complex types.
1549 Diag(OpLoc, diag::ext_integer_increment_complex,
1550 resType.getAsString(), op->getSourceRange());
1551 else {
1552 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1553 resType.getAsString(), op->getSourceRange());
1554 return QualType();
1555 }
Chris Lattner4b009652007-07-25 00:24:17 +00001556 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00001557 // At this point, we know we have a real, complex or pointer type.
1558 // Now make sure the operand is a modifiable lvalue.
Chris Lattner4b009652007-07-25 00:24:17 +00001559 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1560 if (mlval != Expr::MLV_Valid) {
1561 // FIXME: emit a more precise diagnostic...
1562 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1563 op->getSourceRange());
1564 return QualType();
1565 }
1566 return resType;
1567}
1568
1569/// getPrimaryDeclaration - Helper function for CheckAddressOfOperand().
1570/// This routine allows us to typecheck complex/recursive expressions
1571/// where the declaration is needed for type checking. Here are some
1572/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1573static Decl *getPrimaryDeclaration(Expr *e) {
1574 switch (e->getStmtClass()) {
1575 case Stmt::DeclRefExprClass:
1576 return cast<DeclRefExpr>(e)->getDecl();
1577 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001578 // Fields cannot be declared with a 'register' storage class.
1579 // &X->f is always ok, even if X is declared register.
1580 if (cast<MemberExpr>(e)->isArrow())
1581 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001582 return getPrimaryDeclaration(cast<MemberExpr>(e)->getBase());
1583 case Stmt::ArraySubscriptExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00001584 // &X[4] and &4[X] is invalid if X is invalid.
Chris Lattner4b009652007-07-25 00:24:17 +00001585 return getPrimaryDeclaration(cast<ArraySubscriptExpr>(e)->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +00001586 case Stmt::UnaryOperatorClass:
1587 return getPrimaryDeclaration(cast<UnaryOperator>(e)->getSubExpr());
1588 case Stmt::ParenExprClass:
1589 return getPrimaryDeclaration(cast<ParenExpr>(e)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00001590 case Stmt::ImplicitCastExprClass:
1591 // &X[4] when X is an array, has an implicit cast from array to pointer.
1592 return getPrimaryDeclaration(cast<ImplicitCastExpr>(e)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00001593 default:
1594 return 0;
1595 }
1596}
1597
1598/// CheckAddressOfOperand - The operand of & must be either a function
1599/// designator or an lvalue designating an object. If it is an lvalue, the
1600/// object cannot be declared with storage class register or be a bit field.
1601/// Note: The usual conversions are *not* applied to the operand of the &
1602/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1603QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1604 Decl *dcl = getPrimaryDeclaration(op);
1605 Expr::isLvalueResult lval = op->isLvalue();
1606
1607 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00001608 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1609 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00001610 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1611 op->getSourceRange());
1612 return QualType();
1613 }
1614 } else if (dcl) {
1615 // We have an lvalue with a decl. Make sure the decl is not declared
1616 // with the register storage-class specifier.
1617 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1618 if (vd->getStorageClass() == VarDecl::Register) {
1619 Diag(OpLoc, diag::err_typecheck_address_of_register,
1620 op->getSourceRange());
1621 return QualType();
1622 }
1623 } else
1624 assert(0 && "Unknown/unexpected decl type");
1625
1626 // FIXME: add check for bitfields!
1627 }
1628 // If the operand has type "type", the result has type "pointer to type".
1629 return Context.getPointerType(op->getType());
1630}
1631
1632QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1633 UsualUnaryConversions(op);
1634 QualType qType = op->getType();
1635
Chris Lattner7931f4a2007-07-31 16:53:04 +00001636 if (const PointerType *PT = qType->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001637 QualType ptype = PT->getPointeeType();
1638 // C99 6.5.3.2p4. "if it points to an object,...".
1639 if (ptype->isIncompleteType()) { // An incomplete type is not an object
1640 // GCC compat: special case 'void *' (treat as warning).
1641 if (ptype->isVoidType()) {
1642 Diag(OpLoc, diag::ext_typecheck_deref_ptr_to_void,
1643 qType.getAsString(), op->getSourceRange());
1644 } else {
1645 Diag(OpLoc, diag::err_typecheck_deref_incomplete_type,
1646 ptype.getAsString(), op->getSourceRange());
1647 return QualType();
1648 }
1649 }
1650 return ptype;
1651 }
1652 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1653 qType.getAsString(), op->getSourceRange());
1654 return QualType();
1655}
1656
1657static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1658 tok::TokenKind Kind) {
1659 BinaryOperator::Opcode Opc;
1660 switch (Kind) {
1661 default: assert(0 && "Unknown binop!");
1662 case tok::star: Opc = BinaryOperator::Mul; break;
1663 case tok::slash: Opc = BinaryOperator::Div; break;
1664 case tok::percent: Opc = BinaryOperator::Rem; break;
1665 case tok::plus: Opc = BinaryOperator::Add; break;
1666 case tok::minus: Opc = BinaryOperator::Sub; break;
1667 case tok::lessless: Opc = BinaryOperator::Shl; break;
1668 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
1669 case tok::lessequal: Opc = BinaryOperator::LE; break;
1670 case tok::less: Opc = BinaryOperator::LT; break;
1671 case tok::greaterequal: Opc = BinaryOperator::GE; break;
1672 case tok::greater: Opc = BinaryOperator::GT; break;
1673 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
1674 case tok::equalequal: Opc = BinaryOperator::EQ; break;
1675 case tok::amp: Opc = BinaryOperator::And; break;
1676 case tok::caret: Opc = BinaryOperator::Xor; break;
1677 case tok::pipe: Opc = BinaryOperator::Or; break;
1678 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
1679 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
1680 case tok::equal: Opc = BinaryOperator::Assign; break;
1681 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
1682 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
1683 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
1684 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
1685 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
1686 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
1687 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
1688 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
1689 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
1690 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
1691 case tok::comma: Opc = BinaryOperator::Comma; break;
1692 }
1693 return Opc;
1694}
1695
1696static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1697 tok::TokenKind Kind) {
1698 UnaryOperator::Opcode Opc;
1699 switch (Kind) {
1700 default: assert(0 && "Unknown unary op!");
1701 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
1702 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
1703 case tok::amp: Opc = UnaryOperator::AddrOf; break;
1704 case tok::star: Opc = UnaryOperator::Deref; break;
1705 case tok::plus: Opc = UnaryOperator::Plus; break;
1706 case tok::minus: Opc = UnaryOperator::Minus; break;
1707 case tok::tilde: Opc = UnaryOperator::Not; break;
1708 case tok::exclaim: Opc = UnaryOperator::LNot; break;
1709 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
1710 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1711 case tok::kw___real: Opc = UnaryOperator::Real; break;
1712 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
1713 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1714 }
1715 return Opc;
1716}
1717
1718// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001719Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00001720 ExprTy *LHS, ExprTy *RHS) {
1721 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1722 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1723
Steve Naroff87d58b42007-09-16 03:34:24 +00001724 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1725 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001726
1727 QualType ResultTy; // Result type of the binary operator.
1728 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
1729
1730 switch (Opc) {
1731 default:
1732 assert(0 && "Unknown binary expr!");
1733 case BinaryOperator::Assign:
1734 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1735 break;
1736 case BinaryOperator::Mul:
1737 case BinaryOperator::Div:
1738 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
1739 break;
1740 case BinaryOperator::Rem:
1741 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
1742 break;
1743 case BinaryOperator::Add:
1744 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
1745 break;
1746 case BinaryOperator::Sub:
1747 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
1748 break;
1749 case BinaryOperator::Shl:
1750 case BinaryOperator::Shr:
1751 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
1752 break;
1753 case BinaryOperator::LE:
1754 case BinaryOperator::LT:
1755 case BinaryOperator::GE:
1756 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001757 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001758 break;
1759 case BinaryOperator::EQ:
1760 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00001761 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001762 break;
1763 case BinaryOperator::And:
1764 case BinaryOperator::Xor:
1765 case BinaryOperator::Or:
1766 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
1767 break;
1768 case BinaryOperator::LAnd:
1769 case BinaryOperator::LOr:
1770 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
1771 break;
1772 case BinaryOperator::MulAssign:
1773 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001774 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001775 if (!CompTy.isNull())
1776 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1777 break;
1778 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001779 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001780 if (!CompTy.isNull())
1781 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1782 break;
1783 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001784 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001785 if (!CompTy.isNull())
1786 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1787 break;
1788 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001789 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001790 if (!CompTy.isNull())
1791 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1792 break;
1793 case BinaryOperator::ShlAssign:
1794 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001795 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001796 if (!CompTy.isNull())
1797 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1798 break;
1799 case BinaryOperator::AndAssign:
1800 case BinaryOperator::XorAssign:
1801 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00001802 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001803 if (!CompTy.isNull())
1804 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
1805 break;
1806 case BinaryOperator::Comma:
1807 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
1808 break;
1809 }
1810 if (ResultTy.isNull())
1811 return true;
1812 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00001813 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001814 else
Chris Lattnerf420df12007-08-28 18:36:55 +00001815 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001816}
1817
1818// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00001819Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00001820 ExprTy *input) {
1821 Expr *Input = (Expr*)input;
1822 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
1823 QualType resultType;
1824 switch (Opc) {
1825 default:
1826 assert(0 && "Unimplemented unary expr!");
1827 case UnaryOperator::PreInc:
1828 case UnaryOperator::PreDec:
1829 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
1830 break;
1831 case UnaryOperator::AddrOf:
1832 resultType = CheckAddressOfOperand(Input, OpLoc);
1833 break;
1834 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00001835 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00001836 resultType = CheckIndirectionOperand(Input, OpLoc);
1837 break;
1838 case UnaryOperator::Plus:
1839 case UnaryOperator::Minus:
1840 UsualUnaryConversions(Input);
1841 resultType = Input->getType();
1842 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
1843 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1844 resultType.getAsString());
1845 break;
1846 case UnaryOperator::Not: // bitwise complement
1847 UsualUnaryConversions(Input);
1848 resultType = Input->getType();
Steve Naroffd30e1932007-08-24 17:20:07 +00001849 // C99 6.5.3.3p1. We allow complex as a GCC extension.
1850 if (!resultType->isIntegerType()) {
1851 if (resultType->isComplexType())
1852 // C99 does not support '~' for complex conjugation.
1853 Diag(OpLoc, diag::ext_integer_complement_complex,
1854 resultType.getAsString());
1855 else
1856 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1857 resultType.getAsString());
1858 }
Chris Lattner4b009652007-07-25 00:24:17 +00001859 break;
1860 case UnaryOperator::LNot: // logical negation
1861 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
1862 DefaultFunctionArrayConversion(Input);
1863 resultType = Input->getType();
1864 if (!resultType->isScalarType()) // C99 6.5.3.3p1
1865 return Diag(OpLoc, diag::err_typecheck_unary_expr,
1866 resultType.getAsString());
1867 // LNot always has type int. C99 6.5.3.3p5.
1868 resultType = Context.IntTy;
1869 break;
1870 case UnaryOperator::SizeOf:
1871 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
1872 break;
1873 case UnaryOperator::AlignOf:
1874 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
1875 break;
Chris Lattner03931a72007-08-24 21:16:53 +00001876 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00001877 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00001878 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00001879 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001880 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00001881 resultType = Input->getType();
1882 break;
1883 }
1884 if (resultType.isNull())
1885 return true;
1886 return new UnaryOperator(Input, Opc, resultType, OpLoc);
1887}
1888
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001889/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
1890Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001891 SourceLocation LabLoc,
1892 IdentifierInfo *LabelII) {
1893 // Look up the record for this label identifier.
1894 LabelStmt *&LabelDecl = LabelMap[LabelII];
1895
1896 // If we haven't seen this label yet, create a forward reference.
1897 if (LabelDecl == 0)
1898 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
1899
1900 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00001901 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
1902 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001903}
1904
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001905Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00001906 SourceLocation RPLoc) { // "({..})"
1907 Stmt *SubStmt = static_cast<Stmt*>(substmt);
1908 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
1909 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
1910
1911 // FIXME: there are a variety of strange constraints to enforce here, for
1912 // example, it is not possible to goto into a stmt expression apparently.
1913 // More semantic analysis is needed.
1914
1915 // FIXME: the last statement in the compount stmt has its value used. We
1916 // should not warn about it being unused.
1917
1918 // If there are sub stmts in the compound stmt, take the type of the last one
1919 // as the type of the stmtexpr.
1920 QualType Ty = Context.VoidTy;
1921
1922 if (!Compound->body_empty())
1923 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
1924 Ty = LastExpr->getType();
1925
1926 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
1927}
Steve Naroff63bad2d2007-08-01 22:05:33 +00001928
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001929Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001930 SourceLocation TypeLoc,
1931 TypeTy *argty,
1932 OffsetOfComponent *CompPtr,
1933 unsigned NumComponents,
1934 SourceLocation RPLoc) {
1935 QualType ArgTy = QualType::getFromOpaquePtr(argty);
1936 assert(!ArgTy.isNull() && "Missing type argument!");
1937
1938 // We must have at least one component that refers to the type, and the first
1939 // one is known to be a field designator. Verify that the ArgTy represents
1940 // a struct/union/class.
1941 if (!ArgTy->isRecordType())
1942 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
1943
1944 // Otherwise, create a compound literal expression as the base, and
1945 // iteratively process the offsetof designators.
1946 Expr *Res = new CompoundLiteralExpr(ArgTy, 0);
1947
Chris Lattnerb37522e2007-08-31 21:49:13 +00001948 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
1949 // GCC extension, diagnose them.
1950 if (NumComponents != 1)
1951 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
1952 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
1953
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001954 for (unsigned i = 0; i != NumComponents; ++i) {
1955 const OffsetOfComponent &OC = CompPtr[i];
1956 if (OC.isBrackets) {
1957 // Offset of an array sub-field. TODO: Should we allow vector elements?
1958 const ArrayType *AT = Res->getType()->getAsArrayType();
1959 if (!AT) {
1960 delete Res;
1961 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
1962 Res->getType().getAsString());
1963 }
1964
Chris Lattner2af6a802007-08-30 17:59:59 +00001965 // FIXME: C++: Verify that operator[] isn't overloaded.
1966
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001967 // C99 6.5.2.1p1
1968 Expr *Idx = static_cast<Expr*>(OC.U.E);
1969 if (!Idx->getType()->isIntegerType())
1970 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
1971 Idx->getSourceRange());
1972
1973 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
1974 continue;
1975 }
1976
1977 const RecordType *RC = Res->getType()->getAsRecordType();
1978 if (!RC) {
1979 delete Res;
1980 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
1981 Res->getType().getAsString());
1982 }
1983
1984 // Get the decl corresponding to this.
1985 RecordDecl *RD = RC->getDecl();
1986 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
1987 if (!MemberDecl)
1988 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
1989 OC.U.IdentInfo->getName(),
1990 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00001991
1992 // FIXME: C++: Verify that MemberDecl isn't a static field.
1993 // FIXME: Verify that MemberDecl isn't a bitfield.
1994
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001995 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd);
1996 }
1997
1998 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
1999 BuiltinLoc);
2000}
2001
2002
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002003Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002004 TypeTy *arg1, TypeTy *arg2,
2005 SourceLocation RPLoc) {
2006 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2007 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2008
2009 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2010
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002011 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002012}
2013
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002014Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002015 ExprTy *expr1, ExprTy *expr2,
2016 SourceLocation RPLoc) {
2017 Expr *CondExpr = static_cast<Expr*>(cond);
2018 Expr *LHSExpr = static_cast<Expr*>(expr1);
2019 Expr *RHSExpr = static_cast<Expr*>(expr2);
2020
2021 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2022
2023 // The conditional expression is required to be a constant expression.
2024 llvm::APSInt condEval(32);
2025 SourceLocation ExpLoc;
2026 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2027 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2028 CondExpr->getSourceRange());
2029
2030 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2031 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2032 RHSExpr->getType();
2033 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2034}
2035
Anders Carlsson36760332007-10-15 20:28:48 +00002036Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2037 ExprTy *expr, TypeTy *type,
2038 SourceLocation RPLoc)
2039{
2040 Expr *E = static_cast<Expr*>(expr);
2041 QualType T = QualType::getFromOpaquePtr(type);
2042
2043 InitBuiltinVaListType();
2044
2045 Sema::AssignmentCheckResult result;
2046
2047 result = CheckAssignmentConstraints(Context.getBuiltinVaListType(),
2048 E->getType());
2049 if (result != Compatible)
2050 return Diag(E->getLocStart(),
2051 diag::err_first_argument_to_va_arg_not_of_type_va_list,
2052 E->getType().getAsString(),
2053 E->getSourceRange());
2054
2055 // FIXME: Warn if a non-POD type is passed in.
2056
2057 return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2058}
2059
Anders Carlssona66cad42007-08-21 17:43:55 +00002060// TODO: Move this to SemaObjC.cpp
Chris Lattnerddd3e632007-12-12 01:04:12 +00002061Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
2062 ExprTy **Strings,
2063 unsigned NumStrings) {
Chris Lattnerddd3e632007-12-12 01:04:12 +00002064 SourceLocation AtLoc = AtLocs[0];
2065 StringLiteral* S = static_cast<StringLiteral *>(Strings[0]);
Fariborz Jahanian1a442d32007-12-12 23:55:49 +00002066 if (NumStrings > 1) {
2067 // Concatenate objc strings.
2068 StringLiteral* ES = static_cast<StringLiteral *>(Strings[NumStrings-1]);
2069 SourceLocation EndLoc = ES->getSourceRange().getEnd();
2070 unsigned Length = 0;
2071 for (unsigned i = 0; i < NumStrings; i++)
2072 Length += static_cast<StringLiteral *>(Strings[i])->getByteLength();
2073 char *strBuf = new char [Length];
2074 char *p = strBuf;
2075 bool isWide = false;
2076 for (unsigned i = 0; i < NumStrings; i++) {
2077 S = static_cast<StringLiteral *>(Strings[i]);
2078 if (S->isWide())
2079 isWide = true;
2080 memcpy(p, S->getStrData(), S->getByteLength());
2081 p += S->getByteLength();
2082 delete S;
2083 }
2084 S = new StringLiteral(strBuf, Length,
2085 isWide, Context.getPointerType(Context.CharTy),
2086 AtLoc, EndLoc);
2087 }
Anders Carlssona66cad42007-08-21 17:43:55 +00002088
2089 if (CheckBuiltinCFStringArgument(S))
2090 return true;
2091
Steve Narofff2e30312007-10-15 23:35:17 +00002092 if (Context.getObjcConstantStringInterface().isNull()) {
2093 // Initialize the constant string interface lazily. This assumes
2094 // the NSConstantString interface is seen in this translation unit.
2095 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
2096 ScopedDecl *IFace = LookupScopedDecl(NSIdent, Decl::IDNS_Ordinary,
2097 SourceLocation(), TUScope);
Steve Naroff134c3502007-10-16 00:00:18 +00002098 ObjcInterfaceDecl *strIFace = dyn_cast_or_null<ObjcInterfaceDecl>(IFace);
Steve Naroff96f136d2007-10-18 23:53:51 +00002099 if (!strIFace)
2100 return Diag(S->getLocStart(), diag::err_undef_interface,
2101 NSIdent->getName());
Steve Naroff134c3502007-10-16 00:00:18 +00002102 Context.setObjcConstantStringInterface(strIFace);
Steve Narofff2e30312007-10-15 23:35:17 +00002103 }
2104 QualType t = Context.getObjcConstantStringInterface();
Anders Carlssona66cad42007-08-21 17:43:55 +00002105 t = Context.getPointerType(t);
Steve Naroff0add5d22007-11-03 11:27:19 +00002106 return new ObjCStringLiteral(S, t, AtLoc);
Anders Carlssona66cad42007-08-21 17:43:55 +00002107}
Anders Carlsson8be1d402007-08-22 15:14:15 +00002108
2109Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
Chris Lattnercfd61c82007-10-16 22:51:17 +00002110 SourceLocation EncodeLoc,
Anders Carlsson8be1d402007-08-22 15:14:15 +00002111 SourceLocation LParenLoc,
2112 TypeTy *Ty,
2113 SourceLocation RParenLoc) {
2114 QualType EncodedType = QualType::getFromOpaquePtr(Ty);
2115
2116 QualType t = Context.getPointerType(Context.CharTy);
2117 return new ObjCEncodeExpr(t, EncodedType, AtLoc, RParenLoc);
2118}
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002119
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002120Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
2121 SourceLocation AtLoc,
Fariborz Jahanian957448a2007-10-16 23:21:02 +00002122 SourceLocation SelLoc,
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002123 SourceLocation LParenLoc,
2124 SourceLocation RParenLoc) {
Steve Naroffae84af82007-10-31 18:42:27 +00002125 QualType t = Context.getObjcSelType();
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002126 return new ObjCSelectorExpr(t, Sel, AtLoc, RParenLoc);
2127}
2128
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002129Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
2130 SourceLocation AtLoc,
2131 SourceLocation ProtoLoc,
2132 SourceLocation LParenLoc,
2133 SourceLocation RParenLoc) {
2134 ObjcProtocolDecl* PDecl = ObjcProtocols[ProtocolId];
2135 if (!PDecl) {
2136 Diag(ProtoLoc, diag::err_undeclared_protocol, ProtocolId->getName());
2137 return true;
2138 }
2139
Fariborz Jahanianb4452ed2007-12-07 00:18:54 +00002140 QualType t = Context.getObjcProtoType();
Fariborz Jahanian20b40e42007-10-18 22:59:23 +00002141 if (t.isNull())
2142 return true;
Fariborz Jahanianb4452ed2007-12-07 00:18:54 +00002143 t = Context.getPointerType(t);
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002144 return new ObjCProtocolExpr(t, PDecl, AtLoc, RParenLoc);
2145}
Steve Naroff52664182007-10-16 23:12:48 +00002146
2147bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
2148 ObjcMethodDecl *Method) {
2149 bool anyIncompatibleArgs = false;
2150
2151 for (unsigned i = 0; i < NumArgs; i++) {
2152 Expr *argExpr = Args[i];
2153 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
2154
2155 QualType lhsType = Method->getParamDecl(i)->getType();
2156 QualType rhsType = argExpr->getType();
2157
2158 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
2159 if (const ArrayType *ary = lhsType->getAsArrayType())
2160 lhsType = Context.getPointerType(ary->getElementType());
2161 else if (lhsType->isFunctionType())
2162 lhsType = Context.getPointerType(lhsType);
2163
2164 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
2165 argExpr);
2166 if (Args[i] != argExpr) // The expression was converted.
2167 Args[i] = argExpr; // Make sure we store the converted expression.
2168 SourceLocation l = argExpr->getLocStart();
2169
2170 // decode the result (notice that AST's are still created for extensions).
2171 switch (result) {
2172 case Compatible:
2173 break;
2174 case PointerFromInt:
Steve Naroffcdee22d2007-11-27 17:58:44 +00002175 Diag(l, diag::ext_typecheck_sending_pointer_int,
2176 lhsType.getAsString(), rhsType.getAsString(),
2177 argExpr->getSourceRange());
Steve Naroff52664182007-10-16 23:12:48 +00002178 break;
2179 case IntFromPointer:
2180 Diag(l, diag::ext_typecheck_sending_pointer_int,
2181 lhsType.getAsString(), rhsType.getAsString(),
2182 argExpr->getSourceRange());
2183 break;
2184 case IncompatiblePointer:
2185 Diag(l, diag::ext_typecheck_sending_incompatible_pointer,
2186 rhsType.getAsString(), lhsType.getAsString(),
2187 argExpr->getSourceRange());
2188 break;
2189 case CompatiblePointerDiscardsQualifiers:
2190 Diag(l, diag::ext_typecheck_passing_discards_qualifiers,
2191 rhsType.getAsString(), lhsType.getAsString(),
2192 argExpr->getSourceRange());
2193 break;
2194 case Incompatible:
2195 Diag(l, diag::err_typecheck_sending_incompatible,
2196 rhsType.getAsString(), lhsType.getAsString(),
2197 argExpr->getSourceRange());
2198 anyIncompatibleArgs = true;
2199 }
2200 }
2201 return anyIncompatibleArgs;
2202}
2203
Steve Naroff4ed9d662007-09-27 14:38:14 +00002204// ActOnClassMessage - used for both unary and keyword messages.
2205// ArgExprs is optional - if it is present, the number of expressions
2206// is obtained from Sel.getNumArgs().
2207Sema::ExprResult Sema::ActOnClassMessage(
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002208 Scope *S,
Steve Narofffa465d12007-10-02 20:01:56 +00002209 IdentifierInfo *receiverName, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002210 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002211{
Steve Narofffa465d12007-10-02 20:01:56 +00002212 assert(receiverName && "missing receiver class name");
Steve Naroffc39ca262007-09-18 23:55:05 +00002213
Steve Naroff52664182007-10-16 23:12:48 +00002214 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002215 ObjcInterfaceDecl* ClassDecl = 0;
2216 if (!strcmp(receiverName->getName(), "super") && CurMethodDecl) {
2217 ClassDecl = CurMethodDecl->getClassInterface()->getSuperClass();
Fariborz Jahanian342f3602007-11-12 20:20:37 +00002218 if (ClassDecl && CurMethodDecl->isInstance()) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002219 // Synthesize a cast to the super class. This hack allows us to loosely
2220 // represent super without creating a special expression node.
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002221 IdentifierInfo &II = Context.Idents.get("self");
Steve Naroff3b1caac2007-12-07 03:50:46 +00002222 ExprResult ReceiverExpr = ActOnIdentifierExpr(S, lbrac, II, false);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002223 QualType superTy = Context.getObjcInterfaceType(ClassDecl);
2224 superTy = Context.getPointerType(superTy);
2225 ReceiverExpr = ActOnCastExpr(SourceLocation(), superTy.getAsOpaquePtr(),
2226 SourceLocation(), ReceiverExpr.Val);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002227 // We are really in an instance method, redirect.
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002228 return ActOnInstanceMessage(ReceiverExpr.Val, Sel, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002229 Args, NumArgs);
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002230 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00002231 // We are sending a message to 'super' within a class method. Do nothing,
2232 // the receiver will pass through as 'super' (how convenient:-).
2233 } else
Fariborz Jahanian2ce5dc52007-11-12 20:13:27 +00002234 ClassDecl = getObjCInterfaceDecl(receiverName);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002235
2236 // FIXME: can ClassDecl ever be null?
Steve Narofffa465d12007-10-02 20:01:56 +00002237 ObjcMethodDecl *Method = ClassDecl->lookupClassMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002238 QualType returnType;
Steve Naroff75c4baf2007-11-05 15:27:52 +00002239
2240 // Before we give up, check if the selector is an instance method.
2241 if (!Method)
2242 Method = ClassDecl->lookupInstanceMethod(Sel);
Steve Naroff7e461452007-10-16 20:39:36 +00002243 if (!Method) {
2244 Diag(lbrac, diag::warn_method_not_found, std::string("+"), Sel.getName(),
2245 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002246 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002247 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002248 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002249 if (Sel.getNumArgs()) {
2250 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2251 return true;
2252 }
Steve Naroff7e461452007-10-16 20:39:36 +00002253 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002254 return new ObjCMessageExpr(receiverName, Sel, returnType, Method,
Steve Naroff9f176d12007-11-15 13:05:42 +00002255 lbrac, rbrac, ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002256}
2257
Steve Naroff4ed9d662007-09-27 14:38:14 +00002258// ActOnInstanceMessage - used for both unary and keyword messages.
2259// ArgExprs is optional - if it is present, the number of expressions
2260// is obtained from Sel.getNumArgs().
2261Sema::ExprResult Sema::ActOnInstanceMessage(
Steve Naroff6cb1d362007-09-28 22:22:11 +00002262 ExprTy *receiver, Selector Sel,
Steve Naroff9f176d12007-11-15 13:05:42 +00002263 SourceLocation lbrac, SourceLocation rbrac, ExprTy **Args, unsigned NumArgs)
Steve Naroff4ed9d662007-09-27 14:38:14 +00002264{
Steve Naroffc39ca262007-09-18 23:55:05 +00002265 assert(receiver && "missing receiver expression");
2266
Steve Naroff52664182007-10-16 23:12:48 +00002267 Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
Steve Naroffc39ca262007-09-18 23:55:05 +00002268 Expr *RExpr = static_cast<Expr *>(receiver);
Steve Narofffa465d12007-10-02 20:01:56 +00002269 QualType receiverType = RExpr->getType();
Steve Naroffee1de132007-10-10 21:53:07 +00002270 QualType returnType;
Steve Naroff1e1c3912007-11-03 16:37:59 +00002271 ObjcMethodDecl *Method;
Steve Naroffee1de132007-10-10 21:53:07 +00002272
Steve Naroff0091d142007-11-11 17:52:25 +00002273 if (receiverType == Context.getObjcIdType() ||
2274 receiverType == Context.getObjcClassType()) {
Steve Naroff1e1c3912007-11-03 16:37:59 +00002275 Method = InstanceMethodPool[Sel].Method;
Steve Narofffe9eb6a2007-12-18 01:30:32 +00002276 if (!Method)
2277 Method = FactoryMethodPool[Sel].Method;
Steve Naroff7e461452007-10-16 20:39:36 +00002278 if (!Method) {
2279 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2280 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002281 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002282 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002283 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002284 if (Sel.getNumArgs())
2285 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2286 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002287 }
Steve Naroffee1de132007-10-10 21:53:07 +00002288 } else {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002289 bool receiverIsQualId =
2290 dyn_cast<ObjcQualifiedIdType>(RExpr->getType()) != 0;
Chris Lattner71c01112007-10-10 23:42:28 +00002291 // FIXME (snaroff): checking in this code from Patrick. Needs to be
2292 // revisited. how do we get the ClassDecl from the receiver expression?
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002293 if (!receiverIsQualId)
2294 while (receiverType->isPointerType()) {
2295 PointerType *pointerType =
2296 static_cast<PointerType*>(receiverType.getTypePtr());
2297 receiverType = pointerType->getPointeeType();
2298 }
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002299 ObjcInterfaceDecl* ClassDecl;
2300 if (ObjcQualifiedInterfaceType *QIT =
2301 dyn_cast<ObjcQualifiedInterfaceType>(receiverType)) {
Fariborz Jahanian0c2f2142007-12-13 20:47:42 +00002302 ClassDecl = QIT->getDecl();
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002303 Method = ClassDecl->lookupInstanceMethod(Sel);
2304 if (!Method) {
2305 // search protocols
2306 for (unsigned i = 0; i < QIT->getNumProtocols(); i++) {
2307 ObjcProtocolDecl *PDecl = QIT->getProtocols(i);
2308 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
2309 break;
2310 }
2311 }
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002312 if (!Method)
2313 Diag(lbrac, diag::warn_method_not_found_in_protocol,
2314 std::string("-"), Sel.getName(),
2315 SourceRange(lbrac, rbrac));
2316 }
2317 else if (ObjcQualifiedIdType *QIT =
2318 dyn_cast<ObjcQualifiedIdType>(receiverType)) {
2319 // search protocols
2320 for (unsigned i = 0; i < QIT->getNumProtocols(); i++) {
2321 ObjcProtocolDecl *PDecl = QIT->getProtocols(i);
2322 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
2323 break;
2324 }
2325 if (!Method)
2326 Diag(lbrac, diag::warn_method_not_found_in_protocol,
2327 std::string("-"), Sel.getName(),
2328 SourceRange(lbrac, rbrac));
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002329 }
2330 else {
2331 assert(ObjcInterfaceType::classof(receiverType.getTypePtr()) &&
2332 "bad receiver type");
2333 ClassDecl = static_cast<ObjcInterfaceType*>(
2334 receiverType.getTypePtr())->getDecl();
2335 // FIXME: consider using InstanceMethodPool, since it will be faster
2336 // than the following method (which can do *many* linear searches). The
2337 // idea is to add class info to InstanceMethodPool...
2338 Method = ClassDecl->lookupInstanceMethod(Sel);
2339 }
Steve Naroff7e461452007-10-16 20:39:36 +00002340 if (!Method) {
Steve Naroffb1c7ad92007-11-11 00:10:47 +00002341 // If we have an implementation in scope, check "private" methods.
2342 if (ObjcImplementationDecl *ImpDecl =
2343 ObjcImplementations[ClassDecl->getIdentifier()])
2344 Method = ImpDecl->lookupInstanceMethod(Sel);
Steve Naroff20255552007-12-11 03:38:03 +00002345 // If we still haven't found a method, look in the global pool. This
2346 // behavior isn't very desirable, however we need it for GCC compatibility.
Steve Naroffc4793582007-12-07 20:41:14 +00002347 if (!Method)
2348 Method = InstanceMethodPool[Sel].Method;
Steve Naroffb1c7ad92007-11-11 00:10:47 +00002349 }
2350 if (!Method) {
Steve Naroff7e461452007-10-16 20:39:36 +00002351 Diag(lbrac, diag::warn_method_not_found, std::string("-"), Sel.getName(),
2352 SourceRange(lbrac, rbrac));
Steve Naroffae84af82007-10-31 18:42:27 +00002353 returnType = Context.getObjcIdType();
Steve Naroff7e461452007-10-16 20:39:36 +00002354 } else {
Steve Naroff171f5b12007-10-16 21:36:54 +00002355 returnType = Method->getResultType();
Steve Naroff52664182007-10-16 23:12:48 +00002356 if (Sel.getNumArgs())
2357 if (CheckMessageArgumentTypes(ArgExprs, Sel.getNumArgs(), Method))
2358 return true;
Steve Naroff7e461452007-10-16 20:39:36 +00002359 }
Steve Narofffa465d12007-10-02 20:01:56 +00002360 }
Steve Naroff1e1c3912007-11-03 16:37:59 +00002361 return new ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, rbrac,
Steve Naroff9f176d12007-11-15 13:05:42 +00002362 ArgExprs, NumArgs);
Steve Naroffd3f5ee42007-09-17 21:01:15 +00002363}