blob: 7fafb1459168d9053259652cd1679acacaa97879 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Chris Lattner299b8842008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattner299b8842008-07-25 21:10:04 +000033/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
34void Sema::DefaultFunctionArrayConversion(Expr *&E) {
35 QualType Ty = E->getType();
36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
37
Chris Lattner299b8842008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000040 else if (Ty->isArrayType()) {
41 // In C90 mode, arrays only promote to pointers if the array expression is
42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
43 // type 'array of type' is converted to an expression that has type 'pointer
44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
45 // that has type 'array of type' ...". The relevant change is "an lvalue"
46 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000047 //
48 // C++ 4.2p1:
49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
50 // T" can be converted to an rvalue of type "pointer to T".
51 //
52 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
53 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattner299b8842008-07-25 21:10:04 +000056}
57
58/// UsualUnaryConversions - Performs various conversions that are common to most
59/// operators (C99 6.3). The conversions of array and function types are
60/// sometimes surpressed. For example, the array->pointer conversion doesn't
61/// apply if the array is an argument to the sizeof or address (&) operators.
62/// In these instances, this routine should *not* be called.
63Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
64 QualType Ty = Expr->getType();
65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
66
Chris Lattner299b8842008-07-25 21:10:04 +000067 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
68 ImpCastExprToType(Expr, Context.IntTy);
69 else
70 DefaultFunctionArrayConversion(Expr);
71
72 return Expr;
73}
74
Chris Lattner9305c3d2008-07-25 22:25:12 +000075/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
76/// do not have a prototype. Arguments that have type float are promoted to
77/// double. All other argument types are converted by UsualUnaryConversions().
78void Sema::DefaultArgumentPromotion(Expr *&Expr) {
79 QualType Ty = Expr->getType();
80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
81
82 // If this is a 'float' (CVR qualified or typedef) promote to double.
83 if (const BuiltinType *BT = Ty->getAsBuiltinType())
84 if (BT->getKind() == BuiltinType::Float)
85 return ImpCastExprToType(Expr, Context.DoubleTy);
86
87 UsualUnaryConversions(Expr);
88}
89
Chris Lattner299b8842008-07-25 21:10:04 +000090/// UsualArithmeticConversions - Performs various conversions that are common to
91/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
92/// routine returns the first non-arithmetic type found. The client is
93/// responsible for emitting appropriate error diagnostics.
94/// FIXME: verify the conversion rules for "complex int" are consistent with
95/// GCC.
96QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
97 bool isCompAssign) {
98 if (!isCompAssign) {
99 UsualUnaryConversions(lhsExpr);
100 UsualUnaryConversions(rhsExpr);
101 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000102
Chris Lattner299b8842008-07-25 21:10:04 +0000103 // For conversion purposes, we ignore any qualifiers.
104 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000105 QualType lhs =
106 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
107 QualType rhs =
108 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000109
110 // If both types are identical, no conversion is needed.
111 if (lhs == rhs)
112 return lhs;
113
114 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
115 // The caller can deal with this (e.g. pointer + int).
116 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
117 return lhs;
118
119 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
120 if (!isCompAssign) {
121 ImpCastExprToType(lhsExpr, destType);
122 ImpCastExprToType(rhsExpr, destType);
123 }
124 return destType;
125}
126
127QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
128 // Perform the usual unary conversions. We do this early so that
129 // integral promotions to "int" can allow us to exit early, in the
130 // lhs == rhs check. Also, for conversion purposes, we ignore any
131 // qualifiers. For example, "const float" and "float" are
132 // equivalent.
Douglas Gregor3d4492e2008-11-13 20:12:29 +0000133 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
134 else lhs = lhs.getUnqualifiedType();
135 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
136 else rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000137
Chris Lattner299b8842008-07-25 21:10:04 +0000138 // If both types are identical, no conversion is needed.
139 if (lhs == rhs)
140 return lhs;
141
142 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
143 // The caller can deal with this (e.g. pointer + int).
144 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
145 return lhs;
146
147 // At this point, we have two different arithmetic types.
148
149 // Handle complex types first (C99 6.3.1.8p1).
150 if (lhs->isComplexType() || rhs->isComplexType()) {
151 // if we have an integer operand, the result is the complex type.
152 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
153 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000154 return lhs;
155 }
156 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
157 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000158 return rhs;
159 }
160 // This handles complex/complex, complex/float, or float/complex.
161 // When both operands are complex, the shorter operand is converted to the
162 // type of the longer, and that is the type of the result. This corresponds
163 // to what is done when combining two real floating-point operands.
164 // The fun begins when size promotion occur across type domains.
165 // From H&S 6.3.4: When one operand is complex and the other is a real
166 // floating-point type, the less precise type is converted, within it's
167 // real or complex domain, to the precision of the other type. For example,
168 // when combining a "long double" with a "double _Complex", the
169 // "double _Complex" is promoted to "long double _Complex".
170 int result = Context.getFloatingTypeOrder(lhs, rhs);
171
172 if (result > 0) { // The left side is bigger, convert rhs.
173 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000174 } else if (result < 0) { // The right side is bigger, convert lhs.
175 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000176 }
177 // At this point, lhs and rhs have the same rank/size. Now, make sure the
178 // domains match. This is a requirement for our implementation, C99
179 // does not require this promotion.
180 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
181 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000182 return rhs;
183 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000184 return lhs;
185 }
186 }
187 return lhs; // The domain/size match exactly.
188 }
189 // Now handle "real" floating types (i.e. float, double, long double).
190 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
191 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000192 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000193 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000194 return lhs;
195 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000196 if (rhs->isComplexIntegerType()) {
197 // convert rhs to the complex floating point type.
198 return Context.getComplexType(lhs);
199 }
200 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000201 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000202 return rhs;
203 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000204 if (lhs->isComplexIntegerType()) {
205 // convert lhs to the complex floating point type.
206 return Context.getComplexType(rhs);
207 }
Chris Lattner299b8842008-07-25 21:10:04 +0000208 // We have two real floating types, float/complex combos were handled above.
209 // Convert the smaller operand to the bigger result.
210 int result = Context.getFloatingTypeOrder(lhs, rhs);
211
212 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000213 return lhs;
214 }
215 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000216 return rhs;
217 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000218 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000219 }
220 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
221 // Handle GCC complex int extension.
222 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
223 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
224
225 if (lhsComplexInt && rhsComplexInt) {
226 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
227 rhsComplexInt->getElementType()) >= 0) {
228 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000229 return lhs;
230 }
Chris Lattner299b8842008-07-25 21:10:04 +0000231 return rhs;
232 } else if (lhsComplexInt && rhs->isIntegerType()) {
233 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000234 return lhs;
235 } else if (rhsComplexInt && lhs->isIntegerType()) {
236 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000237 return rhs;
238 }
239 }
240 // Finally, we have two differing integer types.
241 // The rules for this case are in C99 6.3.1.8
242 int compare = Context.getIntegerTypeOrder(lhs, rhs);
243 bool lhsSigned = lhs->isSignedIntegerType(),
244 rhsSigned = rhs->isSignedIntegerType();
245 QualType destType;
246 if (lhsSigned == rhsSigned) {
247 // Same signedness; use the higher-ranked type
248 destType = compare >= 0 ? lhs : rhs;
249 } else if (compare != (lhsSigned ? 1 : -1)) {
250 // The unsigned type has greater than or equal rank to the
251 // signed type, so use the unsigned type
252 destType = lhsSigned ? rhs : lhs;
253 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
254 // The two types are different widths; if we are here, that
255 // means the signed type is larger than the unsigned type, so
256 // use the signed type.
257 destType = lhsSigned ? lhs : rhs;
258 } else {
259 // The signed type is higher-ranked than the unsigned type,
260 // but isn't actually any bigger (like unsigned int and long
261 // on most 32-bit systems). Use the unsigned type corresponding
262 // to the signed type.
263 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
264 }
Chris Lattner299b8842008-07-25 21:10:04 +0000265 return destType;
266}
267
268//===----------------------------------------------------------------------===//
269// Semantic Analysis for various Expression Types
270//===----------------------------------------------------------------------===//
271
272
Steve Naroff87d58b42007-09-16 03:34:24 +0000273/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000274/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
275/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
276/// multiple tokens. However, the common case is that StringToks points to one
277/// string.
278///
279Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000280Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000281 assert(NumStringToks && "Must have at least one string!");
282
283 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
284 if (Literal.hadError)
285 return ExprResult(true);
286
287 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
288 for (unsigned i = 0; i != NumStringToks; ++i)
289 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000290
291 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000292 if (Literal.Pascal && Literal.GetStringLength() > 256)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000293 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
294 << SourceRange(StringToks[0].getLocation(),
295 StringToks[NumStringToks-1].getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000296
Chris Lattnera6dcce32008-02-11 00:02:17 +0000297 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000298 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000299 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000300
301 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
302 if (getLangOptions().CPlusPlus)
303 StrTy.addConst();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000304
305 // Get an array type for the string, according to C99 6.4.5. This includes
306 // the nul terminator character as well as the string length for pascal
307 // strings.
308 StrTy = Context.getConstantArrayType(StrTy,
309 llvm::APInt(32, Literal.GetStringLength()+1),
310 ArrayType::Normal, 0);
311
Chris Lattner4b009652007-07-25 00:24:17 +0000312 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
313 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000314 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000315 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000316 StringToks[NumStringToks-1].getLocation());
317}
318
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000319/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
320/// CurBlock to VD should cause it to be snapshotted (as we do for auto
321/// variables defined outside the block) or false if this is not needed (e.g.
322/// for values inside the block or for globals).
323///
324/// FIXME: This will create BlockDeclRefExprs for global variables,
325/// function references, etc which is suboptimal :) and breaks
326/// things like "integer constant expression" tests.
327static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
328 ValueDecl *VD) {
329 // If the value is defined inside the block, we couldn't snapshot it even if
330 // we wanted to.
331 if (CurBlock->TheDecl == VD->getDeclContext())
332 return false;
333
334 // If this is an enum constant or function, it is constant, don't snapshot.
335 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
336 return false;
337
338 // If this is a reference to an extern, static, or global variable, no need to
339 // snapshot it.
340 // FIXME: What about 'const' variables in C++?
341 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
342 return Var->hasLocalStorage();
343
344 return true;
345}
346
347
348
Steve Naroff0acc9c92007-09-15 18:49:24 +0000349/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000350/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000351/// identifier is used in a function call context.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000352/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the
353/// class or namespace that the identifier must be a member of.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000354Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000355 IdentifierInfo &II,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000356 bool HasTrailingLParen,
357 const CXXScopeSpec *SS) {
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000358 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
359}
360
361/// ActOnDeclarationNameExpr - The parser has read some kind of name
362/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
363/// performs lookup on that name and returns an expression that refers
364/// to that name. This routine isn't directly called from the parser,
365/// because the parser doesn't know about DeclarationName. Rather,
366/// this routine is called by ActOnIdentifierExpr,
367/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
368/// which form the DeclarationName from the corresponding syntactic
369/// forms.
370///
371/// HasTrailingLParen indicates whether this identifier is used in a
372/// function call context. LookupCtx is only used for a C++
373/// qualified-id (foo::bar) to indicate the class or namespace that
374/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000375///
376/// If ForceResolution is true, then we will attempt to resolve the
377/// name even if it looks like a dependent name. This option is off by
378/// default.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000379Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
380 DeclarationName Name,
381 bool HasTrailingLParen,
Douglas Gregora133e262008-12-06 00:22:45 +0000382 const CXXScopeSpec *SS,
383 bool ForceResolution) {
384 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
385 HasTrailingLParen && !SS && !ForceResolution) {
386 // We've seen something of the form
387 // identifier(
388 // and we are in a template, so it is likely that 's' is a
389 // dependent name. However, we won't know until we've parsed all
390 // of the call arguments. So, build a CXXDependentNameExpr node
391 // to represent this name. Then, if it turns out that none of the
392 // arguments are type-dependent, we'll force the resolution of the
393 // dependent name at that point.
394 return new CXXDependentNameExpr(Name.getAsIdentifierInfo(),
395 Context.DependentTy, Loc);
396 }
397
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000398 // Could be enum-constant, value decl, instance variable, etc.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000399 Decl *D;
400 if (SS && !SS->isEmpty()) {
401 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
402 if (DC == 0)
403 return true;
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000404 D = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000405 } else
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000406 D = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Douglas Gregora133e262008-12-06 00:22:45 +0000407
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000408 // If this reference is in an Objective-C method, then ivar lookup happens as
409 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000410 IdentifierInfo *II = Name.getAsIdentifierInfo();
411 if (II && getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000412 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000413 // There are two cases to handle here. 1) scoped lookup could have failed,
414 // in which case we should look for an ivar. 2) scoped lookup could have
415 // found a decl, but that decl is outside the current method (i.e. a global
416 // variable). In these two cases, we do a lookup for an ivar with this
417 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000418 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000419 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000420 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000421 // FIXME: This should use a new expr for a direct reference, don't turn
422 // this into Self->ivar, just return a BareIVarExpr or something.
423 IdentifierInfo &II = Context.Idents.get("self");
424 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000425 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), Loc,
426 static_cast<Expr*>(SelfExpr.Val), true, true);
427 Context.setFieldDecl(IFace, IV, MRef);
428 return MRef;
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000429 }
430 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000431 // Needed to implement property "super.method" notation.
Chris Lattner87fada82008-11-20 05:35:30 +0000432 if (SD == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000433 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000434 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000435 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000436 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000437 }
Chris Lattner4b009652007-07-25 00:24:17 +0000438 if (D == 0) {
439 // Otherwise, this could be an implicitly declared function reference (legal
440 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000441 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000442 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000443 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000444 else {
445 // If this name wasn't predeclared and if this is not a function call,
446 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000447 if (SS && !SS->isEmpty())
Chris Lattner77d52da2008-11-20 06:06:08 +0000448 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattnerb1753422008-11-23 21:45:46 +0000449 << Name << SS->getRange();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000450 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
451 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000452 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000453 else
Chris Lattnerb1753422008-11-23 21:45:46 +0000454 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000455 }
456 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000457
Douglas Gregor8acb7272008-12-11 16:49:14 +0000458 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000459 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
460 if (MD->isStatic())
461 // "invalid use of member 'x' in static member function"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000462 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattner271d4c22008-11-24 05:29:24 +0000463 << FD->getDeclName();
Douglas Gregor8acb7272008-12-11 16:49:14 +0000464 if (MD->getParent() != FD->getDeclContext())
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000465 // "invalid use of nonstatic data member 'x'"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000466 return Diag(Loc, diag::err_invalid_non_static_member_use)
Chris Lattner271d4c22008-11-24 05:29:24 +0000467 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000468
469 if (FD->isInvalidDecl())
470 return true;
471
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +0000472 // FIXME: Handle 'mutable'.
473 return new DeclRefExpr(FD,
474 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000475 }
476
Chris Lattner271d4c22008-11-24 05:29:24 +0000477 return Diag(Loc, diag::err_invalid_non_static_member_use)
478 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000479 }
Chris Lattner4b009652007-07-25 00:24:17 +0000480 if (isa<TypedefDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000481 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremenek42730c52008-01-07 19:49:32 +0000482 if (isa<ObjCInterfaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000483 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000484 if (isa<NamespaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000485 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000486
Steve Naroffd6163f32008-09-05 22:11:13 +0000487 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000488 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
489 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
490
Steve Naroffd6163f32008-09-05 22:11:13 +0000491 ValueDecl *VD = cast<ValueDecl>(D);
492
493 // check if referencing an identifier with __attribute__((deprecated)).
494 if (VD->getAttr<DeprecatedAttr>())
Chris Lattner271d4c22008-11-24 05:29:24 +0000495 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Douglas Gregor48840c72008-12-10 23:01:14 +0000496
497 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
498 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
499 Scope *CheckS = S;
500 while (CheckS) {
501 if (CheckS->isWithinElse() &&
502 CheckS->getControlParent()->isDeclScope(Var)) {
503 if (Var->getType()->isBooleanType())
504 Diag(Loc, diag::warn_value_always_false) << Var->getDeclName();
505 else
506 Diag(Loc, diag::warn_value_always_zero) << Var->getDeclName();
507 break;
508 }
509
510 // Move up one more control parent to check again.
511 CheckS = CheckS->getControlParent();
512 if (CheckS)
513 CheckS = CheckS->getParent();
514 }
515 }
516 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000517
518 // Only create DeclRefExpr's for valid Decl's.
519 if (VD->isInvalidDecl())
520 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000521
522 // If the identifier reference is inside a block, and it refers to a value
523 // that is outside the block, create a BlockDeclRefExpr instead of a
524 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
525 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000526 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000527 // We do not do this for things like enum constants, global variables, etc,
528 // as they do not get snapshotted.
529 //
530 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000531 // The BlocksAttr indicates the variable is bound by-reference.
532 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000533 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
534 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000535
536 // Variable will be bound by-copy, make it const within the closure.
537 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000538 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
539 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000540 }
541 // If this reference is not in a block or if the referenced variable is
542 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000543
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000544 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000545 bool ValueDependent = false;
546 if (getLangOptions().CPlusPlus) {
547 // C++ [temp.dep.expr]p3:
548 // An id-expression is type-dependent if it contains:
549 // - an identifier that was declared with a dependent type,
550 if (VD->getType()->isDependentType())
551 TypeDependent = true;
552 // - FIXME: a template-id that is dependent,
553 // - a conversion-function-id that specifies a dependent type,
554 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
555 Name.getCXXNameType()->isDependentType())
556 TypeDependent = true;
557 // - a nested-name-specifier that contains a class-name that
558 // names a dependent type.
559 else if (SS && !SS->isEmpty()) {
560 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
561 DC; DC = DC->getParent()) {
562 // FIXME: could stop early at namespace scope.
563 if (DC->isCXXRecord()) {
564 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
565 if (Context.getTypeDeclType(Record)->isDependentType()) {
566 TypeDependent = true;
567 break;
568 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000569 }
570 }
571 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000572
Douglas Gregora5d84612008-12-10 20:57:37 +0000573 // C++ [temp.dep.constexpr]p2:
574 //
575 // An identifier is value-dependent if it is:
576 // - a name declared with a dependent type,
577 if (TypeDependent)
578 ValueDependent = true;
579 // - the name of a non-type template parameter,
580 else if (isa<NonTypeTemplateParmDecl>(VD))
581 ValueDependent = true;
582 // - a constant with integral or enumeration type and is
583 // initialized with an expression that is value-dependent
584 // (FIXME!).
585 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000586
587 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
588 TypeDependent, ValueDependent);
Chris Lattner4b009652007-07-25 00:24:17 +0000589}
590
Chris Lattner69909292008-08-10 01:53:14 +0000591Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000592 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000593 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000594
595 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000596 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000597 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
598 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
599 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000600 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000601
Chris Lattner7e637512008-01-12 08:14:25 +0000602 // Pre-defined identifiers are of type char[x], where x is the length of the
603 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000604 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000605 if (FunctionDecl *FD = getCurFunctionDecl())
606 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000607 else if (ObjCMethodDecl *MD = getCurMethodDecl())
608 Length = MD->getSynthesizedMethodSize();
609 else {
610 Diag(Loc, diag::ext_predef_outside_function);
611 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
612 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
613 }
614
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000615
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000616 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000617 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000618 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000619 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000620}
621
Steve Naroff87d58b42007-09-16 03:34:24 +0000622Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000623 llvm::SmallString<16> CharBuffer;
624 CharBuffer.resize(Tok.getLength());
625 const char *ThisTokBegin = &CharBuffer[0];
626 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
627
628 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
629 Tok.getLocation(), PP);
630 if (Literal.hadError())
631 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000632
633 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
634
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000635 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
636 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000637}
638
Steve Naroff87d58b42007-09-16 03:34:24 +0000639Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000640 // fast path for a single digit (which is quite common). A single digit
641 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
642 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000643 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000644
Chris Lattner8cd0e932008-03-05 18:54:05 +0000645 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000646 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000647 Context.IntTy,
648 Tok.getLocation()));
649 }
650 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000651 // Add padding so that NumericLiteralParser can overread by one character.
652 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000653 const char *ThisTokBegin = &IntegerBuffer[0];
654
655 // Get the spelling of the token, which eliminates trigraphs, etc.
656 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000657
Chris Lattner4b009652007-07-25 00:24:17 +0000658 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
659 Tok.getLocation(), PP);
660 if (Literal.hadError)
661 return ExprResult(true);
662
Chris Lattner1de66eb2007-08-26 03:42:43 +0000663 Expr *Res;
664
665 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000666 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000667 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000668 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000669 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000670 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000671 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000672 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000673
674 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
675
Ted Kremenekddedbe22007-11-29 00:56:49 +0000676 // isExact will be set by GetFloatValue().
677 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000678 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000679 Ty, Tok.getLocation());
680
Chris Lattner1de66eb2007-08-26 03:42:43 +0000681 } else if (!Literal.isIntegerLiteral()) {
682 return ExprResult(true);
683 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000684 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000685
Neil Booth7421e9c2007-08-29 22:00:19 +0000686 // long long is a C99 feature.
687 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000688 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000689 Diag(Tok.getLocation(), diag::ext_longlong);
690
Chris Lattner4b009652007-07-25 00:24:17 +0000691 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000692 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000693
694 if (Literal.GetIntegerValue(ResultVal)) {
695 // If this value didn't fit into uintmax_t, warn and force to ull.
696 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000697 Ty = Context.UnsignedLongLongTy;
698 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000699 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000700 } else {
701 // If this value fits into a ULL, try to figure out what else it fits into
702 // according to the rules of C99 6.4.4.1p5.
703
704 // Octal, Hexadecimal, and integers with a U suffix are allowed to
705 // be an unsigned int.
706 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
707
708 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000709 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000710 if (!Literal.isLong && !Literal.isLongLong) {
711 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000712 unsigned IntSize = Context.Target.getIntWidth();
713
Chris Lattner4b009652007-07-25 00:24:17 +0000714 // Does it fit in a unsigned int?
715 if (ResultVal.isIntN(IntSize)) {
716 // Does it fit in a signed int?
717 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000718 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000719 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000720 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000721 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000722 }
Chris Lattner4b009652007-07-25 00:24:17 +0000723 }
724
725 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000726 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000727 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000728
729 // Does it fit in a unsigned long?
730 if (ResultVal.isIntN(LongSize)) {
731 // Does it fit in a signed long?
732 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000733 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000734 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000735 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000736 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000737 }
Chris Lattner4b009652007-07-25 00:24:17 +0000738 }
739
740 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000741 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000742 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000743
744 // Does it fit in a unsigned long long?
745 if (ResultVal.isIntN(LongLongSize)) {
746 // Does it fit in a signed long long?
747 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000748 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000749 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000750 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000751 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000752 }
753 }
754
755 // If we still couldn't decide a type, we probably have something that
756 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000757 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000758 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000759 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000760 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000761 }
Chris Lattnere4068872008-05-09 05:59:00 +0000762
763 if (ResultVal.getBitWidth() != Width)
764 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000765 }
766
Chris Lattner48d7f382008-04-02 04:24:33 +0000767 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000768 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000769
770 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
771 if (Literal.isImaginary)
772 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
773
774 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000775}
776
Steve Naroff87d58b42007-09-16 03:34:24 +0000777Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000778 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000779 Expr *E = (Expr *)Val;
780 assert((E != 0) && "ActOnParenExpr() missing expr");
781 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000782}
783
784/// The UsualUnaryConversions() function is *not* called by this routine.
785/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000786bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
787 SourceLocation OpLoc,
788 const SourceRange &ExprRange,
789 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000790 // C99 6.5.3.4p1:
791 if (isa<FunctionType>(exprType) && isSizeof)
792 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000793 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +0000794 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000795 Diag(OpLoc, diag::ext_sizeof_void_type)
796 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
797 else if (exprType->isIncompleteType())
798 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
799 diag::err_alignof_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000800 << exprType << ExprRange;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000801
802 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000803}
804
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000805/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
806/// the same for @c alignof and @c __alignof
807/// Note that the ArgRange is invalid if isType is false.
808Action::ExprResult
809Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
810 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +0000811 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000812 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000813
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000814 QualType ArgTy;
815 SourceRange Range;
816 if (isType) {
817 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
818 Range = ArgRange;
819 } else {
820 // Get the end location.
821 Expr *ArgEx = (Expr *)TyOrEx;
822 Range = ArgEx->getSourceRange();
823 ArgTy = ArgEx->getType();
824 }
825
826 // Verify that the operand is valid.
827 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +0000828 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000829
830 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
831 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
832 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +0000833}
834
Chris Lattner5110ad52007-08-24 21:41:10 +0000835QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000836 DefaultFunctionArrayConversion(V);
837
Chris Lattnera16e42d2007-08-26 05:39:26 +0000838 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000839 if (const ComplexType *CT = V->getType()->getAsComplexType())
840 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000841
842 // Otherwise they pass through real integer and floating point types here.
843 if (V->getType()->isArithmeticType())
844 return V->getType();
845
846 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +0000847 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000848 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000849}
850
851
Chris Lattner4b009652007-07-25 00:24:17 +0000852
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000853Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000854 tok::TokenKind Kind,
855 ExprTy *Input) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000856 Expr *Arg = (Expr *)Input;
857
Chris Lattner4b009652007-07-25 00:24:17 +0000858 UnaryOperator::Opcode Opc;
859 switch (Kind) {
860 default: assert(0 && "Unknown unary op!");
861 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
862 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
863 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000864
865 if (getLangOptions().CPlusPlus &&
866 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
867 // Which overloaded operator?
868 OverloadedOperatorKind OverOp =
869 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
870
871 // C++ [over.inc]p1:
872 //
873 // [...] If the function is a member function with one
874 // parameter (which shall be of type int) or a non-member
875 // function with two parameters (the second of which shall be
876 // of type int), it defines the postfix increment operator ++
877 // for objects of that type. When the postfix increment is
878 // called as a result of using the ++ operator, the int
879 // argument will have value zero.
880 Expr *Args[2] = {
881 Arg,
882 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
883 /*isSigned=*/true),
884 Context.IntTy, SourceLocation())
885 };
886
887 // Build the candidate set for overloading
888 OverloadCandidateSet CandidateSet;
889 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
890
891 // Perform overload resolution.
892 OverloadCandidateSet::iterator Best;
893 switch (BestViableFunction(CandidateSet, Best)) {
894 case OR_Success: {
895 // We found a built-in operator or an overloaded operator.
896 FunctionDecl *FnDecl = Best->Function;
897
898 if (FnDecl) {
899 // We matched an overloaded operator. Build a call to that
900 // operator.
901
902 // Convert the arguments.
903 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
904 if (PerformObjectArgumentInitialization(Arg, Method))
905 return true;
906 } else {
907 // Convert the arguments.
908 if (PerformCopyInitialization(Arg,
909 FnDecl->getParamDecl(0)->getType(),
910 "passing"))
911 return true;
912 }
913
914 // Determine the result type
915 QualType ResultTy
916 = FnDecl->getType()->getAsFunctionType()->getResultType();
917 ResultTy = ResultTy.getNonReferenceType();
918
919 // Build the actual expression node.
920 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
921 SourceLocation());
922 UsualUnaryConversions(FnExpr);
923
924 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
925 } else {
926 // We matched a built-in operator. Convert the arguments, then
927 // break out so that we will build the appropriate built-in
928 // operator node.
929 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
930 "passing"))
931 return true;
932
933 break;
934 }
935 }
936
937 case OR_No_Viable_Function:
938 // No viable function; fall through to handling this as a
939 // built-in operator, which will produce an error message for us.
940 break;
941
942 case OR_Ambiguous:
943 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
944 << UnaryOperator::getOpcodeStr(Opc)
945 << Arg->getSourceRange();
946 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
947 return true;
948 }
949
950 // Either we found no viable overloaded operator or we matched a
951 // built-in operator. In either case, fall through to trying to
952 // build a built-in operation.
953 }
954
Sebastian Redl0440c8c2008-12-20 09:35:34 +0000955 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
956 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +0000957 if (result.isNull())
958 return true;
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000959 return new UnaryOperator(Arg, Opc, result, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000960}
961
962Action::ExprResult Sema::
Douglas Gregor80723c52008-11-19 17:17:41 +0000963ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000964 ExprTy *Idx, SourceLocation RLoc) {
965 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
966
Douglas Gregor80723c52008-11-19 17:17:41 +0000967 if (getLangOptions().CPlusPlus &&
Eli Friedmane658bf52008-12-15 22:34:21 +0000968 (LHSExp->getType()->isRecordType() ||
969 LHSExp->getType()->isEnumeralType() ||
970 RHSExp->getType()->isRecordType() ||
971 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +0000972 // Add the appropriate overloaded operators (C++ [over.match.oper])
973 // to the candidate set.
974 OverloadCandidateSet CandidateSet;
975 Expr *Args[2] = { LHSExp, RHSExp };
976 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
977
978 // Perform overload resolution.
979 OverloadCandidateSet::iterator Best;
980 switch (BestViableFunction(CandidateSet, Best)) {
981 case OR_Success: {
982 // We found a built-in operator or an overloaded operator.
983 FunctionDecl *FnDecl = Best->Function;
984
985 if (FnDecl) {
986 // We matched an overloaded operator. Build a call to that
987 // operator.
988
989 // Convert the arguments.
990 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
991 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
992 PerformCopyInitialization(RHSExp,
993 FnDecl->getParamDecl(0)->getType(),
994 "passing"))
995 return true;
996 } else {
997 // Convert the arguments.
998 if (PerformCopyInitialization(LHSExp,
999 FnDecl->getParamDecl(0)->getType(),
1000 "passing") ||
1001 PerformCopyInitialization(RHSExp,
1002 FnDecl->getParamDecl(1)->getType(),
1003 "passing"))
1004 return true;
1005 }
1006
1007 // Determine the result type
1008 QualType ResultTy
1009 = FnDecl->getType()->getAsFunctionType()->getResultType();
1010 ResultTy = ResultTy.getNonReferenceType();
1011
1012 // Build the actual expression node.
1013 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1014 SourceLocation());
1015 UsualUnaryConversions(FnExpr);
1016
1017 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
1018 } else {
1019 // We matched a built-in operator. Convert the arguments, then
1020 // break out so that we will build the appropriate built-in
1021 // operator node.
1022 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1023 "passing") ||
1024 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1025 "passing"))
1026 return true;
1027
1028 break;
1029 }
1030 }
1031
1032 case OR_No_Viable_Function:
1033 // No viable function; fall through to handling this as a
1034 // built-in operator, which will produce an error message for us.
1035 break;
1036
1037 case OR_Ambiguous:
1038 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1039 << "[]"
1040 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1041 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1042 return true;
1043 }
1044
1045 // Either we found no viable overloaded operator or we matched a
1046 // built-in operator. In either case, fall through to trying to
1047 // build a built-in operation.
1048 }
1049
Chris Lattner4b009652007-07-25 00:24:17 +00001050 // Perform default conversions.
1051 DefaultFunctionArrayConversion(LHSExp);
1052 DefaultFunctionArrayConversion(RHSExp);
1053
1054 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1055
1056 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001057 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001058 // in the subscript position. As a result, we need to derive the array base
1059 // and index from the expression types.
1060 Expr *BaseExpr, *IndexExpr;
1061 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001062 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001063 BaseExpr = LHSExp;
1064 IndexExpr = RHSExp;
1065 // FIXME: need to deal with const...
1066 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001067 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001068 // Handle the uncommon case of "123[Ptr]".
1069 BaseExpr = RHSExp;
1070 IndexExpr = LHSExp;
1071 // FIXME: need to deal with const...
1072 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001073 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1074 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001075 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +00001076
1077 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +00001078 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1079 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001080 return Diag(LLoc, diag::err_ext_vector_component_access)
1081 << SourceRange(LLoc, RLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001082 // FIXME: need to deal with const...
1083 ResultType = VTy->getElementType();
1084 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001085 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
1086 << RHSExp->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001087 }
1088 // C99 6.5.2.1p1
1089 if (!IndexExpr->getType()->isIntegerType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001090 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
1091 << IndexExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001092
1093 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1094 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001095 // void (*)(int)) and pointers to incomplete types. Functions are not
1096 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001097 if (!ResultType->isObjectType())
1098 return Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001099 diag::err_typecheck_subscript_not_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001100 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001101
1102 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
1103}
1104
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001105QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001106CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001107 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001108 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001109
1110 // This flag determines whether or not the component is to be treated as a
1111 // special name, or a regular GLSL-style component access.
1112 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001113
1114 // The vector accessor can't exceed the number of elements.
1115 const char *compStr = CompName.getName();
1116 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001117 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001118 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001119 return QualType();
1120 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001121
1122 // Check that we've found one of the special components, or that the component
1123 // names must come from the same set.
1124 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1125 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1126 SpecialComponent = true;
1127 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001128 do
1129 compStr++;
1130 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1131 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1132 do
1133 compStr++;
1134 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1135 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1136 do
1137 compStr++;
1138 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1139 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001140
Nate Begemanc8e51f82008-05-09 06:41:27 +00001141 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001142 // We didn't get to the end of the string. This means the component names
1143 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001144 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1145 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001146 return QualType();
1147 }
1148 // Each component accessor can't exceed the vector type.
1149 compStr = CompName.getName();
1150 while (*compStr) {
1151 if (vecType->isAccessorWithinNumElements(*compStr))
1152 compStr++;
1153 else
1154 break;
1155 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001156 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001157 // We didn't get to the end of the string. This means a component accessor
1158 // exceeds the number of elements in the vector.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001159 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001160 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001161 return QualType();
1162 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001163
1164 // If we have a special component name, verify that the current vector length
1165 // is an even number, since all special component names return exactly half
1166 // the elements.
1167 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001168 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001169 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001170 return QualType();
1171 }
1172
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001173 // The component accessor looks fine - now we need to compute the actual type.
1174 // The vector type is implied by the component accessor. For example,
1175 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001176 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1177 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner65cae292008-11-19 08:23:25 +00001178 : CompName.getLength();
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001179 if (CompSize == 1)
1180 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001181
Nate Begemanaf6ed502008-04-18 23:10:10 +00001182 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001183 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001184 // diagostics look bad. We want extended vector types to appear built-in.
1185 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1186 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1187 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001188 }
1189 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001190}
1191
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001192/// constructSetterName - Return the setter name for the given
1193/// identifier, i.e. "set" + Name where the initial character of Name
1194/// has been capitalized.
1195// FIXME: Merge with same routine in Parser. But where should this
1196// live?
1197static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1198 const IdentifierInfo *Name) {
1199 llvm::SmallString<100> SelectorName;
1200 SelectorName = "set";
1201 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1202 SelectorName[3] = toupper(SelectorName[3]);
1203 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1204}
1205
Chris Lattner4b009652007-07-25 00:24:17 +00001206Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001207ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001208 tok::TokenKind OpKind, SourceLocation MemberLoc,
1209 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001210 Expr *BaseExpr = static_cast<Expr *>(Base);
1211 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001212
1213 // Perform default conversions.
1214 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +00001215
Steve Naroff2cb66382007-07-26 03:11:44 +00001216 QualType BaseType = BaseExpr->getType();
1217 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001218
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001219 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1220 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001221 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001222 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001223 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001224 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
1225 return BuildOverloadedArrowExpr(BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroff2cb66382007-07-26 03:11:44 +00001226 else
Chris Lattner8ba580c2008-11-19 05:08:23 +00001227 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001228 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001229 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001230
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001231 // Handle field access to simple records. This also handles access to fields
1232 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001233 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001234 RecordDecl *RDecl = RTy->getDecl();
1235 if (RTy->isIncompleteType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001236 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattner271d4c22008-11-24 05:29:24 +00001237 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroff2cb66382007-07-26 03:11:44 +00001238 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001239 // FIXME: Qualified name lookup for C++ is a bit more complicated
1240 // than this.
1241 DeclContext::lookup_result Lookup = RDecl->lookup(Context, &Member);
1242 if (Lookup.first == Lookup.second) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001243 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner65cae292008-11-19 08:23:25 +00001244 << &Member << BaseExpr->getSourceRange();
Douglas Gregor8acb7272008-12-11 16:49:14 +00001245 }
1246
Douglas Gregor82d44772008-12-20 23:49:58 +00001247 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(*Lookup.first)) {
1248 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1249 // FIXME: Handle address space modifiers
1250 QualType MemberType = MemberDecl->getType();
1251 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1252 MemberType = Ref->getPointeeType();
1253 else {
1254 unsigned combinedQualifiers =
1255 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
1256 if (MemberDecl->isMutable())
1257 combinedQualifiers &= ~QualType::Const;
1258 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1259 }
Eli Friedman76b49832008-02-06 22:48:16 +00001260
Douglas Gregor82d44772008-12-20 23:49:58 +00001261 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
1262 MemberLoc, MemberType);
1263 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(*Lookup.first))
1264 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Var, MemberLoc,
1265 Var->getType().getNonReferenceType());
1266 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(*Lookup.first))
1267 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberFn, MemberLoc,
1268 MemberFn->getType());
1269 else if (OverloadedFunctionDecl *Ovl
1270 = dyn_cast<OverloadedFunctionDecl>(*Lookup.first))
1271 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl, MemberLoc,
1272 Context.OverloadTy);
1273 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(*Lookup.first))
1274 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Enum, MemberLoc,
1275 Enum->getType());
1276 else if (isa<TypeDecl>(*Lookup.first))
1277 return Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1278 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Eli Friedman76b49832008-02-06 22:48:16 +00001279
Douglas Gregor82d44772008-12-20 23:49:58 +00001280 // We found a declaration kind that we didn't expect. This is a
1281 // generic error message that tells the user that she can't refer
1282 // to this member with '.' or '->'.
1283 return Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1284 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Chris Lattnera57cf472008-07-21 04:28:12 +00001285 }
1286
Chris Lattnere9d71612008-07-21 04:59:05 +00001287 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1288 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001289 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001290 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Fariborz Jahanianea944842008-12-18 17:29:46 +00001291 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc,
1292 BaseExpr,
1293 OpKind == tok::arrow);
1294 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
1295 return MRef;
Fariborz Jahanian09772392008-12-13 22:20:28 +00001296 }
Chris Lattner8ba580c2008-11-19 05:08:23 +00001297 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattner271d4c22008-11-24 05:29:24 +00001298 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattner8ba580c2008-11-19 05:08:23 +00001299 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001300 }
1301
Chris Lattnere9d71612008-07-21 04:59:05 +00001302 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1303 // pointer to a (potentially qualified) interface type.
1304 const PointerType *PTy;
1305 const ObjCInterfaceType *IFTy;
1306 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1307 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1308 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001309
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001310 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001311 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1312 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1313
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001314 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001315 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1316 E = IFTy->qual_end(); I != E; ++I)
1317 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1318 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001319
1320 // If that failed, look for an "implicit" property by seeing if the nullary
1321 // selector is implemented.
1322
1323 // FIXME: The logic for looking up nullary and unary selectors should be
1324 // shared with the code in ActOnInstanceMessage.
1325
1326 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1327 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1328
1329 // If this reference is in an @implementation, check for 'private' methods.
1330 if (!Getter)
1331 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1332 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1333 if (ObjCImplementationDecl *ImpDecl =
1334 ObjCImplementations[ClassDecl->getIdentifier()])
1335 Getter = ImpDecl->getInstanceMethod(Sel);
1336
Steve Naroff04151f32008-10-22 19:16:27 +00001337 // Look through local category implementations associated with the class.
1338 if (!Getter) {
1339 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1340 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1341 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1342 }
1343 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001344 if (Getter) {
1345 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001346 // will look for the matching setter, in case it is needed.
1347 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1348 &Member);
1349 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1350 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1351 if (!Setter) {
1352 // If this reference is in an @implementation, also check for 'private'
1353 // methods.
1354 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1355 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1356 if (ObjCImplementationDecl *ImpDecl =
1357 ObjCImplementations[ClassDecl->getIdentifier()])
1358 Setter = ImpDecl->getInstanceMethod(SetterSel);
1359 }
1360 // Look through local category implementations associated with the class.
1361 if (!Setter) {
1362 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1363 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1364 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1365 }
1366 }
1367
1368 // FIXME: we must check that the setter has property type.
1369 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00001370 MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001371 }
Anders Carlsson96095fc2008-12-19 17:27:57 +00001372
1373 return Diag(MemberLoc, diag::err_property_not_found) <<
1374 &Member << BaseType;
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001375 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001376 // Handle properties on qualified "id" protocols.
1377 const ObjCQualifiedIdType *QIdTy;
1378 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1379 // Check protocols on qualified interfaces.
1380 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001381 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001382 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1383 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001384 // Also must look for a getter name which uses property syntax.
1385 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1386 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1387 return new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(), OMD,
1388 OpLoc, MemberLoc, NULL, 0);
1389 }
1390 }
Anders Carlsson96095fc2008-12-19 17:27:57 +00001391
1392 return Diag(MemberLoc, diag::err_property_not_found) <<
1393 &Member << BaseType;
Steve Naroffd1d44402008-10-20 22:53:06 +00001394 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001395 // Handle 'field access' to vectors, such as 'V.xx'.
1396 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1397 // Component access limited to variables (reject vec4.rg.g).
1398 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1399 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001400 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1401 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001402 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1403 if (ret.isNull())
1404 return true;
1405 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1406 }
1407
Chris Lattner8ba580c2008-11-19 05:08:23 +00001408 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001409 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001410}
1411
Steve Naroff87d58b42007-09-16 03:34:24 +00001412/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001413/// This provides the location of the left/right parens and a list of comma
1414/// locations.
1415Action::ExprResult Sema::
Douglas Gregora133e262008-12-06 00:22:45 +00001416ActOnCallExpr(Scope *S, ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001417 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001418 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1419 Expr *Fn = static_cast<Expr *>(fn);
1420 Expr **Args = reinterpret_cast<Expr**>(args);
1421 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001422 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001423 OverloadedFunctionDecl *Ovl = NULL;
1424
Douglas Gregora133e262008-12-06 00:22:45 +00001425 // Determine whether this is a dependent call inside a C++ template,
1426 // in which case we won't do any semantic analysis now.
1427 bool Dependent = false;
1428 if (Fn->isTypeDependent()) {
1429 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1430 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1431 Dependent = true;
1432 else {
1433 // Resolve the CXXDependentNameExpr to an actual identifier;
1434 // it wasn't really a dependent name after all.
1435 ExprResult Resolved
1436 = ActOnDeclarationNameExpr(S, FnName->getLocation(), FnName->getName(),
1437 /*HasTrailingLParen=*/true,
1438 /*SS=*/0,
1439 /*ForceResolution=*/true);
1440 if (Resolved.isInvalid)
1441 return true;
1442 else {
1443 delete Fn;
1444 Fn = (Expr *)Resolved.Val;
1445 }
1446 }
1447 } else
1448 Dependent = true;
1449 } else
1450 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1451
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001452 // FIXME: Will need to cache the results of name lookup (including
1453 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001454 if (Dependent)
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001455 return new CallExpr(Fn, Args, NumArgs, Context.DependentTy, RParenLoc);
1456
Douglas Gregord2baafd2008-10-21 16:13:35 +00001457 // If we're directly calling a function or a set of overloaded
1458 // functions, get the appropriate declaration.
1459 {
1460 DeclRefExpr *DRExpr = NULL;
1461 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1462 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1463 else
1464 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1465
1466 if (DRExpr) {
1467 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1468 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1469 }
1470 }
1471
Douglas Gregord2baafd2008-10-21 16:13:35 +00001472 if (Ovl) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001473 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1474 RParenLoc);
1475 if (!FDecl)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001476 return true;
1477
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001478 // Update Fn to refer to the actual function selected.
1479 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1480 Fn->getSourceRange().getBegin());
1481 Fn->Destroy(Context);
1482 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001483 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001484
Douglas Gregor10f3c502008-11-19 21:05:33 +00001485 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Douglas Gregora133e262008-12-06 00:22:45 +00001486 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregor10f3c502008-11-19 21:05:33 +00001487 CommaLocs, RParenLoc);
1488
Chris Lattner3e254fb2008-04-08 04:40:51 +00001489 // Promote the function operand.
1490 UsualUnaryConversions(Fn);
1491
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001492 // Make the call expr early, before semantic checks. This guarantees cleanup
1493 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001494 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001495 Context.BoolTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001496
Steve Naroffd6163f32008-09-05 22:11:13 +00001497 const FunctionType *FuncT;
1498 if (!Fn->getType()->isBlockPointerType()) {
1499 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1500 // have type pointer to function".
1501 const PointerType *PT = Fn->getType()->getAsPointerType();
1502 if (PT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001503 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001504 << Fn->getType() << Fn->getSourceRange();
Steve Naroffd6163f32008-09-05 22:11:13 +00001505 FuncT = PT->getPointeeType()->getAsFunctionType();
1506 } else { // This is a block call.
1507 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1508 getAsFunctionType();
1509 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001510 if (FuncT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001511 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001512 << Fn->getType() << Fn->getSourceRange();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001513
1514 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001515 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001516
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001517 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001518 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1519 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001520 unsigned NumArgsInProto = Proto->getNumArgs();
1521 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001522
Chris Lattner3e254fb2008-04-08 04:40:51 +00001523 // If too few arguments are available (and we don't have default
1524 // arguments for the remaining parameters), don't make the call.
1525 if (NumArgs < NumArgsInProto) {
Chris Lattner66beaba2008-11-21 18:44:24 +00001526 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1527 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1528 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1529 // Use default arguments for missing arguments
1530 NumArgsToCheck = NumArgsInProto;
1531 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001532 }
1533
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001534 // If too many are passed and not variadic, error on the extras and drop
1535 // them.
1536 if (NumArgs > NumArgsInProto) {
1537 if (!Proto->isVariadic()) {
Chris Lattner66beaba2008-11-21 18:44:24 +00001538 Diag(Args[NumArgsInProto]->getLocStart(),
1539 diag::err_typecheck_call_too_many_args)
1540 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
Chris Lattner8ba580c2008-11-19 05:08:23 +00001541 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1542 Args[NumArgs-1]->getLocEnd());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001543 // This deletes the extra arguments.
1544 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001545 }
1546 NumArgsToCheck = NumArgsInProto;
1547 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001548
Chris Lattner4b009652007-07-25 00:24:17 +00001549 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001550 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001551 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001552
1553 Expr *Arg;
1554 if (i < NumArgs)
1555 Arg = Args[i];
1556 else
1557 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001558 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001559
Douglas Gregor81c29152008-10-29 00:13:59 +00001560 // Pass the argument.
1561 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner005ed752008-01-04 18:04:52 +00001562 return true;
Douglas Gregor81c29152008-10-29 00:13:59 +00001563
1564 TheCall->setArg(i, Arg);
Chris Lattner4b009652007-07-25 00:24:17 +00001565 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001566
1567 // If this is a variadic call, handle args passed through "...".
1568 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001569 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001570 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1571 Expr *Arg = Args[i];
1572 DefaultArgumentPromotion(Arg);
1573 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001574 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001575 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001576 } else {
1577 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1578
Steve Naroffdb65e052007-08-28 23:30:39 +00001579 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001580 for (unsigned i = 0; i != NumArgs; i++) {
1581 Expr *Arg = Args[i];
1582 DefaultArgumentPromotion(Arg);
1583 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001584 }
Chris Lattner4b009652007-07-25 00:24:17 +00001585 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001586
Chris Lattner2e64c072007-08-10 20:18:51 +00001587 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001588 if (FDecl)
1589 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001590
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001591 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001592}
1593
1594Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001595ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001596 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001597 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001598 QualType literalType = QualType::getFromOpaquePtr(Ty);
1599 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001600 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001601 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001602
Eli Friedman8c2173d2008-05-20 05:22:08 +00001603 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001604 if (literalType->isVariableArrayType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001605 return Diag(LParenLoc, diag::err_variable_object_no_init)
1606 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001607 } else if (literalType->isIncompleteType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001608 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +00001609 << literalType
Chris Lattner8ba580c2008-11-19 05:08:23 +00001610 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001611 }
1612
Douglas Gregor6428e762008-11-05 15:29:30 +00001613 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Chris Lattner271d4c22008-11-24 05:29:24 +00001614 DeclarationName()))
Steve Naroff92590f92008-01-09 20:58:06 +00001615 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001616
Chris Lattnere5cb5862008-12-04 23:50:19 +00001617 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001618 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001619 if (CheckForConstantInitializer(literalExpr, literalType))
1620 return true;
1621 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001622 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1623 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001624}
1625
1626Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001627ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001628 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001629 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001630 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001631
Steve Naroff0acc9c92007-09-15 18:49:24 +00001632 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001633 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001634
Chris Lattner71ca8c82008-10-26 23:43:26 +00001635 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1636 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001637 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1638 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001639}
1640
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001641/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001642bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001643 UsualUnaryConversions(castExpr);
1644
1645 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1646 // type needs to be scalar.
1647 if (castType->isVoidType()) {
1648 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001649 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1650 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001651 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1652 // GCC struct/union extension: allow cast to self.
1653 if (Context.getCanonicalType(castType) !=
1654 Context.getCanonicalType(castExpr->getType()) ||
1655 (!castType->isStructureType() && !castType->isUnionType())) {
1656 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001657 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001658 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001659 }
1660
1661 // accept this, but emit an ext-warn.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001662 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001663 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001664 } else if (!castExpr->getType()->isScalarType() &&
1665 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001666 return Diag(castExpr->getLocStart(),
1667 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001668 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001669 } else if (castExpr->getType()->isVectorType()) {
1670 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1671 return true;
1672 } else if (castType->isVectorType()) {
1673 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1674 return true;
1675 }
1676 return false;
1677}
1678
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001679bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001680 assert(VectorTy->isVectorType() && "Not a vector type!");
1681
1682 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001683 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001684 return Diag(R.getBegin(),
1685 Ty->isVectorType() ?
1686 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00001687 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001688 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001689 } else
1690 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001691 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001692 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001693
1694 return false;
1695}
1696
Chris Lattner4b009652007-07-25 00:24:17 +00001697Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001698ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001699 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001700 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001701
1702 Expr *castExpr = static_cast<Expr*>(Op);
1703 QualType castType = QualType::getFromOpaquePtr(Ty);
1704
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001705 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1706 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00001707 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001708}
1709
Chris Lattner98a425c2007-11-26 01:40:58 +00001710/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1711/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001712inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1713 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1714 UsualUnaryConversions(cond);
1715 UsualUnaryConversions(lex);
1716 UsualUnaryConversions(rex);
1717 QualType condT = cond->getType();
1718 QualType lexT = lex->getType();
1719 QualType rexT = rex->getType();
1720
1721 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001722 if (!cond->isTypeDependent()) {
1723 if (!condT->isScalarType()) { // C99 6.5.15p2
1724 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
1725 return QualType();
1726 }
Chris Lattner4b009652007-07-25 00:24:17 +00001727 }
Chris Lattner992ae932008-01-06 22:42:25 +00001728
1729 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001730 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
1731 return Context.DependentTy;
1732
Chris Lattner992ae932008-01-06 22:42:25 +00001733 // If both operands have arithmetic type, do the usual arithmetic conversions
1734 // to find a common type: C99 6.5.15p3,5.
1735 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001736 UsualArithmeticConversions(lex, rex);
1737 return lex->getType();
1738 }
Chris Lattner992ae932008-01-06 22:42:25 +00001739
1740 // If both operands are the same structure or union type, the result is that
1741 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001742 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001743 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001744 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001745 // "If both the operands have structure or union type, the result has
1746 // that type." This implies that CV qualifiers are dropped.
1747 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001748 }
Chris Lattner992ae932008-01-06 22:42:25 +00001749
1750 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001751 // The following || allows only one side to be void (a GCC-ism).
1752 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001753 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001754 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
1755 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00001756 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001757 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
1758 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00001759 ImpCastExprToType(lex, Context.VoidTy);
1760 ImpCastExprToType(rex, Context.VoidTy);
1761 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001762 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001763 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1764 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001765 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1766 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001767 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001768 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001769 return lexT;
1770 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001771 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1772 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001773 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001774 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001775 return rexT;
1776 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001777 // Handle the case where both operands are pointers before we handle null
1778 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001779 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1780 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1781 // get the "pointed to" types
1782 QualType lhptee = LHSPT->getPointeeType();
1783 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001784
Chris Lattner71225142007-07-31 21:27:01 +00001785 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1786 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001787 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001788 // Figure out necessary qualifiers (C99 6.5.15p6)
1789 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001790 QualType destType = Context.getPointerType(destPointee);
1791 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1792 ImpCastExprToType(rex, destType); // promote to void*
1793 return destType;
1794 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001795 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001796 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001797 QualType destType = Context.getPointerType(destPointee);
1798 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1799 ImpCastExprToType(rex, destType); // promote to void*
1800 return destType;
1801 }
Chris Lattner4b009652007-07-25 00:24:17 +00001802
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001803 QualType compositeType = lexT;
1804
1805 // If either type is an Objective-C object type then check
1806 // compatibility according to Objective-C.
1807 if (Context.isObjCObjectPointerType(lexT) ||
1808 Context.isObjCObjectPointerType(rexT)) {
1809 // If both operands are interfaces and either operand can be
1810 // assigned to the other, use that type as the composite
1811 // type. This allows
1812 // xxx ? (A*) a : (B*) b
1813 // where B is a subclass of A.
1814 //
1815 // Additionally, as for assignment, if either type is 'id'
1816 // allow silent coercion. Finally, if the types are
1817 // incompatible then make sure to use 'id' as the composite
1818 // type so the result is acceptable for sending messages to.
1819
1820 // FIXME: This code should not be localized to here. Also this
1821 // should use a compatible check instead of abusing the
1822 // canAssignObjCInterfaces code.
1823 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1824 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1825 if (LHSIface && RHSIface &&
1826 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1827 compositeType = lexT;
1828 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00001829 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001830 compositeType = rexT;
1831 } else if (Context.isObjCIdType(lhptee) ||
1832 Context.isObjCIdType(rhptee)) {
1833 // FIXME: This code looks wrong, because isObjCIdType checks
1834 // the struct but getObjCIdType returns the pointer to
1835 // struct. This is horrible and should be fixed.
1836 compositeType = Context.getObjCIdType();
1837 } else {
1838 QualType incompatTy = Context.getObjCIdType();
1839 ImpCastExprToType(lex, incompatTy);
1840 ImpCastExprToType(rex, incompatTy);
1841 return incompatTy;
1842 }
1843 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1844 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00001845 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001846 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001847 // In this situation, we assume void* type. No especially good
1848 // reason, but this is what gcc does, and we do have to pick
1849 // to get a consistent AST.
1850 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001851 ImpCastExprToType(lex, incompatTy);
1852 ImpCastExprToType(rex, incompatTy);
1853 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001854 }
1855 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001856 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1857 // differently qualified versions of compatible types, the result type is
1858 // a pointer to an appropriately qualified version of the *composite*
1859 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001860 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001861 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001862 ImpCastExprToType(lex, compositeType);
1863 ImpCastExprToType(rex, compositeType);
1864 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001865 }
Chris Lattner4b009652007-07-25 00:24:17 +00001866 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001867 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1868 // evaluates to "struct objc_object *" (and is handled above when comparing
1869 // id with statically typed objects).
1870 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1871 // GCC allows qualified id and any Objective-C type to devolve to
1872 // id. Currently localizing to here until clear this should be
1873 // part of ObjCQualifiedIdTypesAreCompatible.
1874 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1875 (lexT->isObjCQualifiedIdType() &&
1876 Context.isObjCObjectPointerType(rexT)) ||
1877 (rexT->isObjCQualifiedIdType() &&
1878 Context.isObjCObjectPointerType(lexT))) {
1879 // FIXME: This is not the correct composite type. This only
1880 // happens to work because id can more or less be used anywhere,
1881 // however this may change the type of method sends.
1882 // FIXME: gcc adds some type-checking of the arguments and emits
1883 // (confusing) incompatible comparison warnings in some
1884 // cases. Investigate.
1885 QualType compositeType = Context.getObjCIdType();
1886 ImpCastExprToType(lex, compositeType);
1887 ImpCastExprToType(rex, compositeType);
1888 return compositeType;
1889 }
1890 }
1891
Steve Naroff3eac7692008-09-10 19:17:48 +00001892 // Selection between block pointer types is ok as long as they are the same.
1893 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1894 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1895 return lexT;
1896
Chris Lattner992ae932008-01-06 22:42:25 +00001897 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00001898 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001899 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001900 return QualType();
1901}
1902
Steve Naroff87d58b42007-09-16 03:34:24 +00001903/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001904/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001905Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001906 SourceLocation ColonLoc,
1907 ExprTy *Cond, ExprTy *LHS,
1908 ExprTy *RHS) {
1909 Expr *CondExpr = (Expr *) Cond;
1910 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001911
1912 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1913 // was the condition.
1914 bool isLHSNull = LHSExpr == 0;
1915 if (isLHSNull)
1916 LHSExpr = CondExpr;
1917
Chris Lattner4b009652007-07-25 00:24:17 +00001918 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1919 RHSExpr, QuestionLoc);
1920 if (result.isNull())
1921 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001922 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1923 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001924}
1925
Chris Lattner4b009652007-07-25 00:24:17 +00001926
1927// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1928// being closely modeled after the C99 spec:-). The odd characteristic of this
1929// routine is it effectively iqnores the qualifiers on the top level pointee.
1930// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1931// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001932Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001933Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1934 QualType lhptee, rhptee;
1935
1936 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001937 lhptee = lhsType->getAsPointerType()->getPointeeType();
1938 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001939
1940 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001941 lhptee = Context.getCanonicalType(lhptee);
1942 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001943
Chris Lattner005ed752008-01-04 18:04:52 +00001944 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001945
1946 // C99 6.5.16.1p1: This following citation is common to constraints
1947 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1948 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001949 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001950 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001951 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001952
1953 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1954 // incomplete type and the other is a pointer to a qualified or unqualified
1955 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001956 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001957 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001958 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001959
1960 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001961 assert(rhptee->isFunctionType());
1962 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001963 }
1964
1965 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001966 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001967 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001968
1969 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001970 assert(lhptee->isFunctionType());
1971 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001972 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001973
1974 // Check for ObjC interfaces
1975 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1976 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1977 if (LHSIface && RHSIface &&
1978 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1979 return ConvTy;
1980
1981 // ID acts sort of like void* for ObjC interfaces
1982 if (LHSIface && Context.isObjCIdType(rhptee))
1983 return ConvTy;
1984 if (RHSIface && Context.isObjCIdType(lhptee))
1985 return ConvTy;
1986
Chris Lattner4b009652007-07-25 00:24:17 +00001987 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1988 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001989 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1990 rhptee.getUnqualifiedType()))
1991 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001992 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001993}
1994
Steve Naroff3454b6c2008-09-04 15:10:53 +00001995/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1996/// block pointer types are compatible or whether a block and normal pointer
1997/// are compatible. It is more restrict than comparing two function pointer
1998// types.
1999Sema::AssignConvertType
2000Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2001 QualType rhsType) {
2002 QualType lhptee, rhptee;
2003
2004 // get the "pointed to" type (ignoring qualifiers at the top level)
2005 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2006 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2007
2008 // make sure we operate on the canonical type
2009 lhptee = Context.getCanonicalType(lhptee);
2010 rhptee = Context.getCanonicalType(rhptee);
2011
2012 AssignConvertType ConvTy = Compatible;
2013
2014 // For blocks we enforce that qualifiers are identical.
2015 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2016 ConvTy = CompatiblePointerDiscardsQualifiers;
2017
2018 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2019 return IncompatibleBlockPointer;
2020 return ConvTy;
2021}
2022
Chris Lattner4b009652007-07-25 00:24:17 +00002023/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2024/// has code to accommodate several GCC extensions when type checking
2025/// pointers. Here are some objectionable examples that GCC considers warnings:
2026///
2027/// int a, *pint;
2028/// short *pshort;
2029/// struct foo *pfoo;
2030///
2031/// pint = pshort; // warning: assignment from incompatible pointer type
2032/// a = pint; // warning: assignment makes integer from pointer without a cast
2033/// pint = a; // warning: assignment makes pointer from integer without a cast
2034/// pint = pfoo; // warning: assignment from incompatible pointer type
2035///
2036/// As a result, the code for dealing with pointers is more complex than the
2037/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002038///
Chris Lattner005ed752008-01-04 18:04:52 +00002039Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002040Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002041 // Get canonical types. We're not formatting these types, just comparing
2042 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002043 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2044 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002045
2046 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002047 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002048
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002049 // If the left-hand side is a reference type, then we are in a
2050 // (rare!) case where we've allowed the use of references in C,
2051 // e.g., as a parameter type in a built-in function. In this case,
2052 // just make sure that the type referenced is compatible with the
2053 // right-hand side type. The caller is responsible for adjusting
2054 // lhsType so that the resulting expression does not have reference
2055 // type.
2056 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2057 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002058 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002059 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002060 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002061
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002062 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2063 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002064 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002065 // Relax integer conversions like we do for pointers below.
2066 if (rhsType->isIntegerType())
2067 return IntToPointer;
2068 if (lhsType->isIntegerType())
2069 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002070 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002071 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002072
Nate Begemanc5f0f652008-07-14 18:02:46 +00002073 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002074 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002075 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2076 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002077 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002078
Nate Begemanc5f0f652008-07-14 18:02:46 +00002079 // If we are allowing lax vector conversions, and LHS and RHS are both
2080 // vectors, the total size only needs to be the same. This is a bitcast;
2081 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002082 if (getLangOptions().LaxVectorConversions &&
2083 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002084 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2085 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002086 }
2087 return Incompatible;
2088 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002089
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002090 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002091 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002092
Chris Lattner390564e2008-04-07 06:49:41 +00002093 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002094 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002095 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002096
Chris Lattner390564e2008-04-07 06:49:41 +00002097 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002098 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002099
Steve Naroffa982c712008-09-29 18:10:17 +00002100 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002101 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002102 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002103
2104 // Treat block pointers as objects.
2105 if (getLangOptions().ObjC1 &&
2106 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2107 return Compatible;
2108 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002109 return Incompatible;
2110 }
2111
2112 if (isa<BlockPointerType>(lhsType)) {
2113 if (rhsType->isIntegerType())
2114 return IntToPointer;
2115
Steve Naroffa982c712008-09-29 18:10:17 +00002116 // Treat block pointers as objects.
2117 if (getLangOptions().ObjC1 &&
2118 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2119 return Compatible;
2120
Steve Naroff3454b6c2008-09-04 15:10:53 +00002121 if (rhsType->isBlockPointerType())
2122 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2123
2124 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2125 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002126 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002127 }
Chris Lattner1853da22008-01-04 23:18:45 +00002128 return Incompatible;
2129 }
2130
Chris Lattner390564e2008-04-07 06:49:41 +00002131 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002132 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002133 if (lhsType == Context.BoolTy)
2134 return Compatible;
2135
2136 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002137 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002138
Chris Lattner390564e2008-04-07 06:49:41 +00002139 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002140 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002141
2142 if (isa<BlockPointerType>(lhsType) &&
2143 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002144 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002145 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002146 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002147
Chris Lattner1853da22008-01-04 23:18:45 +00002148 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002149 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002150 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002151 }
2152 return Incompatible;
2153}
2154
Chris Lattner005ed752008-01-04 18:04:52 +00002155Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002156Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002157 if (getLangOptions().CPlusPlus) {
2158 if (!lhsType->isRecordType()) {
2159 // C++ 5.17p3: If the left operand is not of class type, the
2160 // expression is implicitly converted (C++ 4) to the
2161 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002162 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2163 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002164 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002165 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002166 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002167 }
2168
2169 // FIXME: Currently, we fall through and treat C++ classes like C
2170 // structures.
2171 }
2172
Steve Naroffcdee22d2007-11-27 17:58:44 +00002173 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2174 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002175 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2176 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002177 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002178 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002179 return Compatible;
2180 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002181
2182 // We don't allow conversion of non-null-pointer constants to integers.
2183 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2184 return IntToBlockPointer;
2185
Chris Lattner5f505bf2007-10-16 02:55:40 +00002186 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002187 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002188 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002189 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002190 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002191 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002192 if (!lhsType->isReferenceType())
2193 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002194
Chris Lattner005ed752008-01-04 18:04:52 +00002195 Sema::AssignConvertType result =
2196 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002197
2198 // C99 6.5.16.1p2: The value of the right operand is converted to the
2199 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002200 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2201 // so that we can use references in built-in functions even in C.
2202 // The getNonReferenceType() call makes sure that the resulting expression
2203 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002204 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002205 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002206 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002207}
2208
Chris Lattner005ed752008-01-04 18:04:52 +00002209Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002210Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2211 return CheckAssignmentConstraints(lhsType, rhsType);
2212}
2213
Chris Lattner1eafdea2008-11-18 01:30:42 +00002214QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002215 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002216 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002217 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002218 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002219}
2220
Chris Lattner1eafdea2008-11-18 01:30:42 +00002221inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002222 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002223 // For conversion purposes, we ignore any qualifiers.
2224 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002225 QualType lhsType =
2226 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2227 QualType rhsType =
2228 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002229
Nate Begemanc5f0f652008-07-14 18:02:46 +00002230 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002231 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002232 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002233
Nate Begemanc5f0f652008-07-14 18:02:46 +00002234 // Handle the case of a vector & extvector type of the same size and element
2235 // type. It would be nice if we only had one vector type someday.
2236 if (getLangOptions().LaxVectorConversions)
2237 if (const VectorType *LV = lhsType->getAsVectorType())
2238 if (const VectorType *RV = rhsType->getAsVectorType())
2239 if (LV->getElementType() == RV->getElementType() &&
2240 LV->getNumElements() == RV->getNumElements())
2241 return lhsType->isExtVectorType() ? lhsType : rhsType;
2242
2243 // If the lhs is an extended vector and the rhs is a scalar of the same type
2244 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002245 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002246 QualType eltType = V->getElementType();
2247
2248 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2249 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2250 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002251 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002252 return lhsType;
2253 }
2254 }
2255
Nate Begemanc5f0f652008-07-14 18:02:46 +00002256 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002257 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002258 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002259 QualType eltType = V->getElementType();
2260
2261 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2262 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2263 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002264 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002265 return rhsType;
2266 }
2267 }
2268
Chris Lattner4b009652007-07-25 00:24:17 +00002269 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002270 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002271 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002272 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002273 return QualType();
2274}
2275
2276inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002277 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002278{
2279 QualType lhsType = lex->getType(), rhsType = rex->getType();
2280
2281 if (lhsType->isVectorType() || rhsType->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002282 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002283
Steve Naroff8f708362007-08-24 19:07:16 +00002284 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002285
Chris Lattner4b009652007-07-25 00:24:17 +00002286 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002287 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002288 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002289}
2290
2291inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002292 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002293{
2294 QualType lhsType = lex->getType(), rhsType = rex->getType();
2295
Steve Naroff8f708362007-08-24 19:07:16 +00002296 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002297
Chris Lattner4b009652007-07-25 00:24:17 +00002298 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002299 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002300 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002301}
2302
2303inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002304 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002305{
2306 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002307 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002308
Steve Naroff8f708362007-08-24 19:07:16 +00002309 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002310
Chris Lattner4b009652007-07-25 00:24:17 +00002311 // handle the common case first (both operands are arithmetic).
2312 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002313 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002314
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002315 // Put any potential pointer into PExp
2316 Expr* PExp = lex, *IExp = rex;
2317 if (IExp->getType()->isPointerType())
2318 std::swap(PExp, IExp);
2319
2320 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2321 if (IExp->getType()->isIntegerType()) {
2322 // Check for arithmetic on pointers to incomplete types
2323 if (!PTy->getPointeeType()->isObjectType()) {
2324 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002325 Diag(Loc, diag::ext_gnu_void_ptr)
2326 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002327 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002328 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002329 << lex->getType() << lex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002330 return QualType();
2331 }
2332 }
2333 return PExp->getType();
2334 }
2335 }
2336
Chris Lattner1eafdea2008-11-18 01:30:42 +00002337 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002338}
2339
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002340// C99 6.5.6
2341QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002342 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002343 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002344 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002345
Steve Naroff8f708362007-08-24 19:07:16 +00002346 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002347
Chris Lattnerf6da2912007-12-09 21:53:25 +00002348 // Enforce type constraints: C99 6.5.6p3.
2349
2350 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002351 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002352 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002353
2354 // Either ptr - int or ptr - ptr.
2355 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002356 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002357
Chris Lattnerf6da2912007-12-09 21:53:25 +00002358 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002359 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002360 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002361 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002362 Diag(Loc, diag::ext_gnu_void_ptr)
2363 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002364 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002365 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002366 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002367 return QualType();
2368 }
2369 }
2370
2371 // The result type of a pointer-int computation is the pointer type.
2372 if (rex->getType()->isIntegerType())
2373 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002374
Chris Lattnerf6da2912007-12-09 21:53:25 +00002375 // Handle pointer-pointer subtractions.
2376 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002377 QualType rpointee = RHSPTy->getPointeeType();
2378
Chris Lattnerf6da2912007-12-09 21:53:25 +00002379 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002380 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002381 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002382 if (rpointee->isVoidType()) {
2383 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002384 Diag(Loc, diag::ext_gnu_void_ptr)
2385 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002386 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002387 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002388 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002389 return QualType();
2390 }
2391 }
2392
2393 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002394 if (!Context.typesAreCompatible(
2395 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2396 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002397 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002398 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002399 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002400 return QualType();
2401 }
2402
2403 return Context.getPointerDiffType();
2404 }
2405 }
2406
Chris Lattner1eafdea2008-11-18 01:30:42 +00002407 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002408}
2409
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002410// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002411QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002412 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002413 // C99 6.5.7p2: Each of the operands shall have integer type.
2414 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002415 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002416
Chris Lattner2c8bff72007-12-12 05:47:28 +00002417 // Shifts don't perform usual arithmetic conversions, they just do integer
2418 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002419 if (!isCompAssign)
2420 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002421 UsualUnaryConversions(rex);
2422
2423 // "The type of the result is that of the promoted left operand."
2424 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002425}
2426
Eli Friedman0d9549b2008-08-22 00:56:42 +00002427static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2428 ASTContext& Context) {
2429 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2430 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2431 // ID acts sort of like void* for ObjC interfaces
2432 if (LHSIface && Context.isObjCIdType(RHS))
2433 return true;
2434 if (RHSIface && Context.isObjCIdType(LHS))
2435 return true;
2436 if (!LHSIface || !RHSIface)
2437 return false;
2438 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2439 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2440}
2441
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002442// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002443QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002444 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002445 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002446 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002447
Chris Lattner254f3bc2007-08-26 01:18:55 +00002448 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002449 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2450 UsualArithmeticConversions(lex, rex);
2451 else {
2452 UsualUnaryConversions(lex);
2453 UsualUnaryConversions(rex);
2454 }
Chris Lattner4b009652007-07-25 00:24:17 +00002455 QualType lType = lex->getType();
2456 QualType rType = rex->getType();
2457
Ted Kremenek486509e2007-10-29 17:13:39 +00002458 // For non-floating point types, check for self-comparisons of the form
2459 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2460 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002461 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002462 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2463 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002464 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002465 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002466 }
2467
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002468 // The result of comparisons is 'bool' in C++, 'int' in C.
2469 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2470
Chris Lattner254f3bc2007-08-26 01:18:55 +00002471 if (isRelational) {
2472 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002473 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002474 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002475 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002476 if (lType->isFloatingType()) {
2477 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002478 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002479 }
2480
Chris Lattner254f3bc2007-08-26 01:18:55 +00002481 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002482 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002483 }
Chris Lattner4b009652007-07-25 00:24:17 +00002484
Chris Lattner22be8422007-08-26 01:10:14 +00002485 bool LHSIsNull = lex->isNullPointerConstant(Context);
2486 bool RHSIsNull = rex->isNullPointerConstant(Context);
2487
Chris Lattner254f3bc2007-08-26 01:18:55 +00002488 // All of the following pointer related warnings are GCC extensions, except
2489 // when handling null pointer constants. One day, we can consider making them
2490 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002491 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002492 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002493 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002494 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002495 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002496
Steve Naroff3b435622007-11-13 14:57:38 +00002497 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002498 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2499 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002500 RCanPointeeTy.getUnqualifiedType()) &&
2501 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002502 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002503 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002504 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002505 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002506 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002507 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002508 // Handle block pointer types.
2509 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2510 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2511 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2512
2513 if (!LHSIsNull && !RHSIsNull &&
2514 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002515 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002516 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002517 }
2518 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002519 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002520 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002521 // Allow block pointers to be compared with null pointer constants.
2522 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2523 (lType->isPointerType() && rType->isBlockPointerType())) {
2524 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002525 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002526 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002527 }
2528 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002529 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002530 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002531
Steve Naroff936c4362008-06-03 14:04:54 +00002532 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002533 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002534 const PointerType *LPT = lType->getAsPointerType();
2535 const PointerType *RPT = rType->getAsPointerType();
2536 bool LPtrToVoid = LPT ?
2537 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2538 bool RPtrToVoid = RPT ?
2539 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2540
2541 if (!LPtrToVoid && !RPtrToVoid &&
2542 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002543 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002544 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002545 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002546 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002547 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002548 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002549 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002550 }
Steve Naroff936c4362008-06-03 14:04:54 +00002551 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2552 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002553 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002554 } else {
2555 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002556 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002557 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002558 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002559 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002560 }
Steve Naroff936c4362008-06-03 14:04:54 +00002561 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002562 }
Steve Naroff936c4362008-06-03 14:04:54 +00002563 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2564 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002565 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002566 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002567 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002568 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002569 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002570 }
Steve Naroff936c4362008-06-03 14:04:54 +00002571 if (lType->isIntegerType() &&
2572 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002573 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002574 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002575 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002576 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002577 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002578 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002579 // Handle block pointers.
2580 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2581 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002582 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002583 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002584 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002585 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002586 }
2587 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2588 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002589 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002590 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002591 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002592 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002593 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002594 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002595}
2596
Nate Begemanc5f0f652008-07-14 18:02:46 +00002597/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2598/// operates on extended vector types. Instead of producing an IntTy result,
2599/// like a scalar comparison, a vector comparison produces a vector of integer
2600/// types.
2601QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002602 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002603 bool isRelational) {
2604 // Check to make sure we're operating on vectors of the same type and width,
2605 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002606 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002607 if (vType.isNull())
2608 return vType;
2609
2610 QualType lType = lex->getType();
2611 QualType rType = rex->getType();
2612
2613 // For non-floating point types, check for self-comparisons of the form
2614 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2615 // often indicate logic errors in the program.
2616 if (!lType->isFloatingType()) {
2617 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2618 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2619 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002620 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002621 }
2622
2623 // Check for comparisons of floating point operands using != and ==.
2624 if (!isRelational && lType->isFloatingType()) {
2625 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002626 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002627 }
2628
2629 // Return the type for the comparison, which is the same as vector type for
2630 // integer vectors, or an integer type of identical size and number of
2631 // elements for floating point vectors.
2632 if (lType->isIntegerType())
2633 return lType;
2634
2635 const VectorType *VTy = lType->getAsVectorType();
2636
2637 // FIXME: need to deal with non-32b int / non-64b long long
2638 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2639 if (TypeSize == 32) {
2640 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2641 }
2642 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2643 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2644}
2645
Chris Lattner4b009652007-07-25 00:24:17 +00002646inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002647 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002648{
2649 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002650 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002651
Steve Naroff8f708362007-08-24 19:07:16 +00002652 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002653
2654 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002655 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002656 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002657}
2658
2659inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00002660 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00002661{
2662 UsualUnaryConversions(lex);
2663 UsualUnaryConversions(rex);
2664
Eli Friedmanbea3f842008-05-13 20:16:47 +00002665 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002666 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002667 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002668}
2669
Chris Lattner4c2642c2008-11-18 01:22:49 +00002670/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2671/// emit an error and return true. If so, return false.
2672static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2673 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2674 if (IsLV == Expr::MLV_Valid)
2675 return false;
2676
2677 unsigned Diag = 0;
2678 bool NeedType = false;
2679 switch (IsLV) { // C99 6.5.16p2
2680 default: assert(0 && "Unknown result from isModifiableLvalue!");
2681 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00002682 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002683 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2684 NeedType = true;
2685 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002686 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002687 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2688 NeedType = true;
2689 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00002690 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002691 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2692 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002693 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002694 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2695 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002696 case Expr::MLV_IncompleteType:
2697 case Expr::MLV_IncompleteVoidType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002698 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2699 NeedType = true;
2700 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002701 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002702 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2703 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00002704 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002705 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2706 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00002707 case Expr::MLV_ReadonlyProperty:
2708 Diag = diag::error_readonly_property_assignment;
2709 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00002710 case Expr::MLV_NoSetterProperty:
2711 Diag = diag::error_nosetter_property_assignment;
2712 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002713 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002714
Chris Lattner4c2642c2008-11-18 01:22:49 +00002715 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002716 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002717 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00002718 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002719 return true;
2720}
2721
2722
2723
2724// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00002725QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
2726 SourceLocation Loc,
2727 QualType CompoundType) {
2728 // Verify that LHS is a modifiable lvalue, and emit error if not.
2729 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00002730 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00002731
2732 QualType LHSType = LHS->getType();
2733 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00002734
Chris Lattner005ed752008-01-04 18:04:52 +00002735 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002736 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00002737 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002738 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner34c85082008-08-21 18:04:13 +00002739
2740 // If the RHS is a unary plus or minus, check to see if they = and + are
2741 // right next to each other. If so, the user may have typo'd "x =+ 4"
2742 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002743 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00002744 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2745 RHSCheck = ICE->getSubExpr();
2746 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2747 if ((UO->getOpcode() == UnaryOperator::Plus ||
2748 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00002749 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00002750 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002751 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00002752 Diag(Loc, diag::warn_not_compound_assign)
2753 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
2754 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00002755 }
2756 } else {
2757 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00002758 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00002759 }
Chris Lattner005ed752008-01-04 18:04:52 +00002760
Chris Lattner1eafdea2008-11-18 01:30:42 +00002761 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
2762 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00002763 return QualType();
2764
Chris Lattner4b009652007-07-25 00:24:17 +00002765 // C99 6.5.16p3: The type of an assignment expression is the type of the
2766 // left operand unless the left operand has qualified type, in which case
2767 // it is the unqualified version of the type of the left operand.
2768 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2769 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002770 // C++ 5.17p1: the type of the assignment expression is that of its left
2771 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002772 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002773}
2774
Chris Lattner1eafdea2008-11-18 01:30:42 +00002775// C99 6.5.17
2776QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
2777 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00002778
2779 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002780 DefaultFunctionArrayConversion(RHS);
2781 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002782}
2783
2784/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2785/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00002786QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
2787 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00002788 QualType ResType = Op->getType();
2789 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002790
Sebastian Redl0440c8c2008-12-20 09:35:34 +00002791 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
2792 // Decrement of bool is not allowed.
2793 if (!isInc) {
2794 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
2795 return QualType();
2796 }
2797 // Increment of bool sets it to true, but is deprecated.
2798 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
2799 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00002800 // OK!
2801 } else if (const PointerType *PT = ResType->getAsPointerType()) {
2802 // C99 6.5.2.4p2, 6.5.6p2
2803 if (PT->getPointeeType()->isObjectType()) {
2804 // Pointer to object is ok!
2805 } else if (PT->getPointeeType()->isVoidType()) {
2806 // Pointer to void is extension.
2807 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
2808 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +00002809 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002810 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002811 return QualType();
2812 }
Chris Lattnere65182c2008-11-21 07:05:48 +00002813 } else if (ResType->isComplexType()) {
2814 // C99 does not support ++/-- on complex types, we allow as an extension.
2815 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002816 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002817 } else {
2818 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002819 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002820 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002821 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002822 // At this point, we know we have a real, complex or pointer type.
2823 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00002824 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00002825 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00002826 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00002827}
2828
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002829/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002830/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002831/// where the declaration is needed for type checking. We only need to
2832/// handle cases when the expression references a function designator
2833/// or is an lvalue. Here are some examples:
2834/// - &(x) => x
2835/// - &*****f => f for f a function designator.
2836/// - &s.xx => s
2837/// - &s.zz[1].yy -> s, if zz is an array
2838/// - *(x + 1) -> x, if x is an array
2839/// - &"123"[2] -> 0
2840/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002841static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002842 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002843 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002844 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002845 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002846 // Fields cannot be declared with a 'register' storage class.
2847 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002848 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002849 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002850 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002851 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002852 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002853
Douglas Gregord2baafd2008-10-21 16:13:35 +00002854 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002855 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002856 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002857 return 0;
2858 else
2859 return VD;
2860 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002861 case Stmt::UnaryOperatorClass: {
2862 UnaryOperator *UO = cast<UnaryOperator>(E);
2863
2864 switch(UO->getOpcode()) {
2865 case UnaryOperator::Deref: {
2866 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002867 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2868 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2869 if (!VD || VD->getType()->isPointerType())
2870 return 0;
2871 return VD;
2872 }
2873 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002874 }
2875 case UnaryOperator::Real:
2876 case UnaryOperator::Imag:
2877 case UnaryOperator::Extension:
2878 return getPrimaryDecl(UO->getSubExpr());
2879 default:
2880 return 0;
2881 }
2882 }
2883 case Stmt::BinaryOperatorClass: {
2884 BinaryOperator *BO = cast<BinaryOperator>(E);
2885
2886 // Handle cases involving pointer arithmetic. The result of an
2887 // Assign or AddAssign is not an lvalue so they can be ignored.
2888
2889 // (x + n) or (n + x) => x
2890 if (BO->getOpcode() == BinaryOperator::Add) {
2891 if (BO->getLHS()->getType()->isPointerType()) {
2892 return getPrimaryDecl(BO->getLHS());
2893 } else if (BO->getRHS()->getType()->isPointerType()) {
2894 return getPrimaryDecl(BO->getRHS());
2895 }
2896 }
2897
2898 return 0;
2899 }
Chris Lattner4b009652007-07-25 00:24:17 +00002900 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002901 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002902 case Stmt::ImplicitCastExprClass:
2903 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002904 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002905 default:
2906 return 0;
2907 }
2908}
2909
2910/// CheckAddressOfOperand - The operand of & must be either a function
2911/// designator or an lvalue designating an object. If it is an lvalue, the
2912/// object cannot be declared with storage class register or be a bit field.
2913/// Note: The usual conversions are *not* applied to the operand of the &
2914/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00002915/// In C++, the operand might be an overloaded function name, in which case
2916/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00002917QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00002918 if (op->isTypeDependent())
2919 return Context.DependentTy;
2920
Steve Naroff9c6c3592008-01-13 17:10:08 +00002921 if (getLangOptions().C99) {
2922 // Implement C99-only parts of addressof rules.
2923 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2924 if (uOp->getOpcode() == UnaryOperator::Deref)
2925 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2926 // (assuming the deref expression is valid).
2927 return uOp->getSubExpr()->getType();
2928 }
2929 // Technically, there should be a check for array subscript
2930 // expressions here, but the result of one is always an lvalue anyway.
2931 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002932 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002933 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00002934
Chris Lattner4b009652007-07-25 00:24:17 +00002935 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002936 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2937 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00002938 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
2939 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002940 return QualType();
2941 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002942 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00002943 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
2944 if (Field->isBitField()) {
2945 Diag(OpLoc, diag::err_typecheck_address_of)
2946 << "bit-field" << op->getSourceRange();
2947 return QualType();
2948 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002949 }
2950 // Check for Apple extension for accessing vector components.
2951 } else if (isa<ArraySubscriptExpr>(op) &&
2952 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002953 Diag(OpLoc, diag::err_typecheck_address_of)
2954 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00002955 return QualType();
2956 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002957 // We have an lvalue with a decl. Make sure the decl is not declared
2958 // with the register storage-class specifier.
2959 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2960 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002961 Diag(OpLoc, diag::err_typecheck_address_of)
2962 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002963 return QualType();
2964 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00002965 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00002966 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00002967 } else if (isa<FieldDecl>(dcl)) {
2968 // Okay: we can take the address of a field.
Nuno Lopesdf239522008-12-16 22:58:26 +00002969 } else if (isa<FunctionDecl>(dcl)) {
2970 // Okay: we can take the address of a function.
Douglas Gregor5b82d612008-12-10 21:26:49 +00002971 }
Nuno Lopesdf239522008-12-16 22:58:26 +00002972 else
Chris Lattner4b009652007-07-25 00:24:17 +00002973 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002974 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002975
Chris Lattner4b009652007-07-25 00:24:17 +00002976 // If the operand has type "type", the result has type "pointer to type".
2977 return Context.getPointerType(op->getType());
2978}
2979
Chris Lattnerda5c0872008-11-23 09:13:29 +00002980QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
2981 UsualUnaryConversions(Op);
2982 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002983
Chris Lattnerda5c0872008-11-23 09:13:29 +00002984 // Note that per both C89 and C99, this is always legal, even if ptype is an
2985 // incomplete type or void. It would be possible to warn about dereferencing
2986 // a void pointer, but it's completely well-defined, and such a warning is
2987 // unlikely to catch any mistakes.
2988 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00002989 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00002990
Chris Lattner77d52da2008-11-20 06:06:08 +00002991 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002992 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002993 return QualType();
2994}
2995
2996static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2997 tok::TokenKind Kind) {
2998 BinaryOperator::Opcode Opc;
2999 switch (Kind) {
3000 default: assert(0 && "Unknown binop!");
3001 case tok::star: Opc = BinaryOperator::Mul; break;
3002 case tok::slash: Opc = BinaryOperator::Div; break;
3003 case tok::percent: Opc = BinaryOperator::Rem; break;
3004 case tok::plus: Opc = BinaryOperator::Add; break;
3005 case tok::minus: Opc = BinaryOperator::Sub; break;
3006 case tok::lessless: Opc = BinaryOperator::Shl; break;
3007 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3008 case tok::lessequal: Opc = BinaryOperator::LE; break;
3009 case tok::less: Opc = BinaryOperator::LT; break;
3010 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3011 case tok::greater: Opc = BinaryOperator::GT; break;
3012 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3013 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3014 case tok::amp: Opc = BinaryOperator::And; break;
3015 case tok::caret: Opc = BinaryOperator::Xor; break;
3016 case tok::pipe: Opc = BinaryOperator::Or; break;
3017 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3018 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3019 case tok::equal: Opc = BinaryOperator::Assign; break;
3020 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3021 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3022 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3023 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3024 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3025 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3026 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3027 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3028 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3029 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3030 case tok::comma: Opc = BinaryOperator::Comma; break;
3031 }
3032 return Opc;
3033}
3034
3035static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3036 tok::TokenKind Kind) {
3037 UnaryOperator::Opcode Opc;
3038 switch (Kind) {
3039 default: assert(0 && "Unknown unary op!");
3040 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3041 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3042 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3043 case tok::star: Opc = UnaryOperator::Deref; break;
3044 case tok::plus: Opc = UnaryOperator::Plus; break;
3045 case tok::minus: Opc = UnaryOperator::Minus; break;
3046 case tok::tilde: Opc = UnaryOperator::Not; break;
3047 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003048 case tok::kw___real: Opc = UnaryOperator::Real; break;
3049 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3050 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3051 }
3052 return Opc;
3053}
3054
Douglas Gregord7f915e2008-11-06 23:29:22 +00003055/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3056/// operator @p Opc at location @c TokLoc. This routine only supports
3057/// built-in operations; ActOnBinOp handles overloaded operators.
3058Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3059 unsigned Op,
3060 Expr *lhs, Expr *rhs) {
3061 QualType ResultTy; // Result type of the binary operator.
3062 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3063 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3064
3065 switch (Opc) {
3066 default:
3067 assert(0 && "Unknown binary expr!");
3068 case BinaryOperator::Assign:
3069 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3070 break;
3071 case BinaryOperator::Mul:
3072 case BinaryOperator::Div:
3073 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3074 break;
3075 case BinaryOperator::Rem:
3076 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3077 break;
3078 case BinaryOperator::Add:
3079 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3080 break;
3081 case BinaryOperator::Sub:
3082 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3083 break;
3084 case BinaryOperator::Shl:
3085 case BinaryOperator::Shr:
3086 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3087 break;
3088 case BinaryOperator::LE:
3089 case BinaryOperator::LT:
3090 case BinaryOperator::GE:
3091 case BinaryOperator::GT:
3092 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3093 break;
3094 case BinaryOperator::EQ:
3095 case BinaryOperator::NE:
3096 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3097 break;
3098 case BinaryOperator::And:
3099 case BinaryOperator::Xor:
3100 case BinaryOperator::Or:
3101 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3102 break;
3103 case BinaryOperator::LAnd:
3104 case BinaryOperator::LOr:
3105 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3106 break;
3107 case BinaryOperator::MulAssign:
3108 case BinaryOperator::DivAssign:
3109 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3110 if (!CompTy.isNull())
3111 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3112 break;
3113 case BinaryOperator::RemAssign:
3114 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3115 if (!CompTy.isNull())
3116 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3117 break;
3118 case BinaryOperator::AddAssign:
3119 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3120 if (!CompTy.isNull())
3121 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3122 break;
3123 case BinaryOperator::SubAssign:
3124 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3125 if (!CompTy.isNull())
3126 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3127 break;
3128 case BinaryOperator::ShlAssign:
3129 case BinaryOperator::ShrAssign:
3130 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3131 if (!CompTy.isNull())
3132 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3133 break;
3134 case BinaryOperator::AndAssign:
3135 case BinaryOperator::XorAssign:
3136 case BinaryOperator::OrAssign:
3137 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3138 if (!CompTy.isNull())
3139 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3140 break;
3141 case BinaryOperator::Comma:
3142 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3143 break;
3144 }
3145 if (ResultTy.isNull())
3146 return true;
3147 if (CompTy.isNull())
3148 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
3149 else
3150 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
3151}
3152
Chris Lattner4b009652007-07-25 00:24:17 +00003153// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003154Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3155 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00003156 ExprTy *LHS, ExprTy *RHS) {
3157 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3158 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
3159
Steve Naroff87d58b42007-09-16 03:34:24 +00003160 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3161 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003162
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003163 // If either expression is type-dependent, just build the AST.
3164 // FIXME: We'll need to perform some caching of the result of name
3165 // lookup for operator+.
3166 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3167 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3168 return new CompoundAssignOperator(lhs, rhs, Opc, Context.DependentTy,
3169 Context.DependentTy, TokLoc);
3170 else
3171 return new BinaryOperator(lhs, rhs, Opc, Context.DependentTy, TokLoc);
3172 }
3173
Douglas Gregord7f915e2008-11-06 23:29:22 +00003174 if (getLangOptions().CPlusPlus &&
3175 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3176 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003177 // If this is one of the assignment operators, we only perform
3178 // overload resolution if the left-hand side is a class or
3179 // enumeration type (C++ [expr.ass]p3).
3180 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3181 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3182 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3183 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003184
3185 // Determine which overloaded operator we're dealing with.
3186 static const OverloadedOperatorKind OverOps[] = {
3187 OO_Star, OO_Slash, OO_Percent,
3188 OO_Plus, OO_Minus,
3189 OO_LessLess, OO_GreaterGreater,
3190 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3191 OO_EqualEqual, OO_ExclaimEqual,
3192 OO_Amp,
3193 OO_Caret,
3194 OO_Pipe,
3195 OO_AmpAmp,
3196 OO_PipePipe,
3197 OO_Equal, OO_StarEqual,
3198 OO_SlashEqual, OO_PercentEqual,
3199 OO_PlusEqual, OO_MinusEqual,
3200 OO_LessLessEqual, OO_GreaterGreaterEqual,
3201 OO_AmpEqual, OO_CaretEqual,
3202 OO_PipeEqual,
3203 OO_Comma
3204 };
3205 OverloadedOperatorKind OverOp = OverOps[Opc];
3206
Douglas Gregor5ed15042008-11-18 23:14:02 +00003207 // Add the appropriate overloaded operators (C++ [over.match.oper])
3208 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003209 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003210 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003211 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003212
3213 // Perform overload resolution.
3214 OverloadCandidateSet::iterator Best;
3215 switch (BestViableFunction(CandidateSet, Best)) {
3216 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003217 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003218 FunctionDecl *FnDecl = Best->Function;
3219
Douglas Gregor70d26122008-11-12 17:17:38 +00003220 if (FnDecl) {
3221 // We matched an overloaded operator. Build a call to that
3222 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003223
Douglas Gregor70d26122008-11-12 17:17:38 +00003224 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003225 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3226 if (PerformObjectArgumentInitialization(lhs, Method) ||
3227 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3228 "passing"))
3229 return true;
3230 } else {
3231 // Convert the arguments.
3232 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3233 "passing") ||
3234 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3235 "passing"))
3236 return true;
3237 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003238
Douglas Gregor70d26122008-11-12 17:17:38 +00003239 // Determine the result type
3240 QualType ResultTy
3241 = FnDecl->getType()->getAsFunctionType()->getResultType();
3242 ResultTy = ResultTy.getNonReferenceType();
3243
3244 // Build the actual expression node.
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003245 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3246 SourceLocation());
3247 UsualUnaryConversions(FnExpr);
3248
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003249 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregor70d26122008-11-12 17:17:38 +00003250 } else {
3251 // We matched a built-in operator. Convert the arguments, then
3252 // break out so that we will build the appropriate built-in
3253 // operator node.
3254 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
3255 "passing") ||
3256 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
3257 "passing"))
3258 return true;
3259
3260 break;
3261 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003262 }
3263
3264 case OR_No_Viable_Function:
3265 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003266 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003267 break;
3268
3269 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003270 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3271 << BinaryOperator::getOpcodeStr(Opc)
3272 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003273 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3274 return true;
3275 }
3276
Douglas Gregor70d26122008-11-12 17:17:38 +00003277 // Either we found no viable overloaded operator or we matched a
3278 // built-in operator. In either case, fall through to trying to
3279 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003280 }
Chris Lattner4b009652007-07-25 00:24:17 +00003281
Douglas Gregord7f915e2008-11-06 23:29:22 +00003282 // Build a built-in binary operation.
3283 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003284}
3285
3286// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003287Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3288 tok::TokenKind Op, ExprTy *input) {
Chris Lattner4b009652007-07-25 00:24:17 +00003289 Expr *Input = (Expr*)input;
3290 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003291
3292 if (getLangOptions().CPlusPlus &&
3293 (Input->getType()->isRecordType()
3294 || Input->getType()->isEnumeralType())) {
3295 // Determine which overloaded operator we're dealing with.
3296 static const OverloadedOperatorKind OverOps[] = {
3297 OO_None, OO_None,
3298 OO_PlusPlus, OO_MinusMinus,
3299 OO_Amp, OO_Star,
3300 OO_Plus, OO_Minus,
3301 OO_Tilde, OO_Exclaim,
3302 OO_None, OO_None,
3303 OO_None,
3304 OO_None
3305 };
3306 OverloadedOperatorKind OverOp = OverOps[Opc];
3307
3308 // Add the appropriate overloaded operators (C++ [over.match.oper])
3309 // to the candidate set.
3310 OverloadCandidateSet CandidateSet;
3311 if (OverOp != OO_None)
3312 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3313
3314 // Perform overload resolution.
3315 OverloadCandidateSet::iterator Best;
3316 switch (BestViableFunction(CandidateSet, Best)) {
3317 case OR_Success: {
3318 // We found a built-in operator or an overloaded operator.
3319 FunctionDecl *FnDecl = Best->Function;
3320
3321 if (FnDecl) {
3322 // We matched an overloaded operator. Build a call to that
3323 // operator.
3324
3325 // Convert the arguments.
3326 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3327 if (PerformObjectArgumentInitialization(Input, Method))
3328 return true;
3329 } else {
3330 // Convert the arguments.
3331 if (PerformCopyInitialization(Input,
3332 FnDecl->getParamDecl(0)->getType(),
3333 "passing"))
3334 return true;
3335 }
3336
3337 // Determine the result type
3338 QualType ResultTy
3339 = FnDecl->getType()->getAsFunctionType()->getResultType();
3340 ResultTy = ResultTy.getNonReferenceType();
3341
3342 // Build the actual expression node.
3343 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3344 SourceLocation());
3345 UsualUnaryConversions(FnExpr);
3346
3347 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3348 } else {
3349 // We matched a built-in operator. Convert the arguments, then
3350 // break out so that we will build the appropriate built-in
3351 // operator node.
3352 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0],
3353 "passing"))
3354 return true;
3355
3356 break;
3357 }
3358 }
3359
3360 case OR_No_Viable_Function:
3361 // No viable function; fall through to handling this as a
3362 // built-in operator, which will produce an error message for us.
3363 break;
3364
3365 case OR_Ambiguous:
3366 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3367 << UnaryOperator::getOpcodeStr(Opc)
3368 << Input->getSourceRange();
3369 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3370 return true;
3371 }
3372
3373 // Either we found no viable overloaded operator or we matched a
3374 // built-in operator. In either case, fall through to trying to
3375 // build a built-in operation.
3376 }
3377
Chris Lattner4b009652007-07-25 00:24:17 +00003378 QualType resultType;
3379 switch (Opc) {
3380 default:
3381 assert(0 && "Unimplemented unary expr!");
3382 case UnaryOperator::PreInc:
3383 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003384 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3385 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003386 break;
3387 case UnaryOperator::AddrOf:
3388 resultType = CheckAddressOfOperand(Input, OpLoc);
3389 break;
3390 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003391 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003392 resultType = CheckIndirectionOperand(Input, OpLoc);
3393 break;
3394 case UnaryOperator::Plus:
3395 case UnaryOperator::Minus:
3396 UsualUnaryConversions(Input);
3397 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003398 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3399 break;
3400 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3401 resultType->isEnumeralType())
3402 break;
3403 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3404 Opc == UnaryOperator::Plus &&
3405 resultType->isPointerType())
3406 break;
3407
Chris Lattner77d52da2008-11-20 06:06:08 +00003408 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003409 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003410 case UnaryOperator::Not: // bitwise complement
3411 UsualUnaryConversions(Input);
3412 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003413 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3414 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3415 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003416 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003417 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003418 else if (!resultType->isIntegerType())
Chris Lattner77d52da2008-11-20 06:06:08 +00003419 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003420 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003421 break;
3422 case UnaryOperator::LNot: // logical negation
3423 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3424 DefaultFunctionArrayConversion(Input);
3425 resultType = Input->getType();
3426 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattner77d52da2008-11-20 06:06:08 +00003427 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003428 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003429 // LNot always has type int. C99 6.5.3.3p5.
3430 resultType = Context.IntTy;
3431 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003432 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003433 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003434 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003435 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003436 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003437 resultType = Input->getType();
3438 break;
3439 }
3440 if (resultType.isNull())
3441 return true;
3442 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3443}
3444
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003445/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3446Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003447 SourceLocation LabLoc,
3448 IdentifierInfo *LabelII) {
3449 // Look up the record for this label identifier.
3450 LabelStmt *&LabelDecl = LabelMap[LabelII];
3451
Daniel Dunbar879788d2008-08-04 16:51:22 +00003452 // If we haven't seen this label yet, create a forward reference. It
3453 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003454 if (LabelDecl == 0)
3455 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3456
3457 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003458 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3459 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003460}
3461
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003462Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003463 SourceLocation RPLoc) { // "({..})"
3464 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3465 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3466 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3467
3468 // FIXME: there are a variety of strange constraints to enforce here, for
3469 // example, it is not possible to goto into a stmt expression apparently.
3470 // More semantic analysis is needed.
3471
3472 // FIXME: the last statement in the compount stmt has its value used. We
3473 // should not warn about it being unused.
3474
3475 // If there are sub stmts in the compound stmt, take the type of the last one
3476 // as the type of the stmtexpr.
3477 QualType Ty = Context.VoidTy;
3478
Chris Lattner200964f2008-07-26 19:51:01 +00003479 if (!Compound->body_empty()) {
3480 Stmt *LastStmt = Compound->body_back();
3481 // If LastStmt is a label, skip down through into the body.
3482 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3483 LastStmt = Label->getSubStmt();
3484
3485 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003486 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003487 }
Chris Lattner4b009652007-07-25 00:24:17 +00003488
3489 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3490}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003491
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003492Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003493 SourceLocation TypeLoc,
3494 TypeTy *argty,
3495 OffsetOfComponent *CompPtr,
3496 unsigned NumComponents,
3497 SourceLocation RPLoc) {
3498 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3499 assert(!ArgTy.isNull() && "Missing type argument!");
3500
3501 // We must have at least one component that refers to the type, and the first
3502 // one is known to be a field designator. Verify that the ArgTy represents
3503 // a struct/union/class.
3504 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003505 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003506
3507 // Otherwise, create a compound literal expression as the base, and
3508 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003509 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003510
Chris Lattnerb37522e2007-08-31 21:49:13 +00003511 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3512 // GCC extension, diagnose them.
3513 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003514 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3515 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003516
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003517 for (unsigned i = 0; i != NumComponents; ++i) {
3518 const OffsetOfComponent &OC = CompPtr[i];
3519 if (OC.isBrackets) {
3520 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003521 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003522 if (!AT) {
3523 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003524 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003525 }
3526
Chris Lattner2af6a802007-08-30 17:59:59 +00003527 // FIXME: C++: Verify that operator[] isn't overloaded.
3528
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003529 // C99 6.5.2.1p1
3530 Expr *Idx = static_cast<Expr*>(OC.U.E);
3531 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003532 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3533 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003534
3535 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3536 continue;
3537 }
3538
3539 const RecordType *RC = Res->getType()->getAsRecordType();
3540 if (!RC) {
3541 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003542 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003543 }
3544
3545 // Get the decl corresponding to this.
3546 RecordDecl *RD = RC->getDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00003547 FieldDecl *MemberDecl = 0;
3548 DeclContext::lookup_result Lookup = RD->lookup(Context, OC.U.IdentInfo);
3549 if (Lookup.first != Lookup.second)
3550 MemberDecl = dyn_cast<FieldDecl>(*Lookup.first);
3551
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003552 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003553 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3554 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003555
3556 // FIXME: C++: Verify that MemberDecl isn't a static field.
3557 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003558 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3559 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003560 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3561 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003562 }
3563
3564 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3565 BuiltinLoc);
3566}
3567
3568
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003569Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003570 TypeTy *arg1, TypeTy *arg2,
3571 SourceLocation RPLoc) {
3572 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3573 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3574
3575 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3576
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003577 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003578}
3579
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003580Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003581 ExprTy *expr1, ExprTy *expr2,
3582 SourceLocation RPLoc) {
3583 Expr *CondExpr = static_cast<Expr*>(cond);
3584 Expr *LHSExpr = static_cast<Expr*>(expr1);
3585 Expr *RHSExpr = static_cast<Expr*>(expr2);
3586
3587 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3588
3589 // The conditional expression is required to be a constant expression.
3590 llvm::APSInt condEval(32);
3591 SourceLocation ExpLoc;
3592 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003593 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3594 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00003595
3596 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3597 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3598 RHSExpr->getType();
3599 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3600}
3601
Steve Naroff52a81c02008-09-03 18:15:37 +00003602//===----------------------------------------------------------------------===//
3603// Clang Extensions.
3604//===----------------------------------------------------------------------===//
3605
3606/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003607void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003608 // Analyze block parameters.
3609 BlockSemaInfo *BSI = new BlockSemaInfo();
3610
3611 // Add BSI to CurBlock.
3612 BSI->PrevBlockInfo = CurBlock;
3613 CurBlock = BSI;
3614
3615 BSI->ReturnType = 0;
3616 BSI->TheScope = BlockScope;
3617
Steve Naroff52059382008-10-10 01:28:17 +00003618 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003619 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00003620}
3621
3622void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003623 // Analyze arguments to block.
3624 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3625 "Not a function declarator!");
3626 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3627
Steve Naroff52059382008-10-10 01:28:17 +00003628 CurBlock->hasPrototype = FTI.hasPrototype;
3629 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003630
3631 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3632 // no arguments, not a function that takes a single void argument.
3633 if (FTI.hasPrototype &&
3634 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3635 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3636 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3637 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003638 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003639 } else if (FTI.hasPrototype) {
3640 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003641 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3642 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003643 }
Steve Naroff52059382008-10-10 01:28:17 +00003644 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3645
3646 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3647 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3648 // If this has an identifier, add it to the scope stack.
3649 if ((*AI)->getIdentifier())
3650 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003651}
3652
3653/// ActOnBlockError - If there is an error parsing a block, this callback
3654/// is invoked to pop the information about the block from the action impl.
3655void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3656 // Ensure that CurBlock is deleted.
3657 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3658
3659 // Pop off CurBlock, handle nested blocks.
3660 CurBlock = CurBlock->PrevBlockInfo;
3661
3662 // FIXME: Delete the ParmVarDecl objects as well???
3663
3664}
3665
3666/// ActOnBlockStmtExpr - This is called when the body of a block statement
3667/// literal was successfully completed. ^(int x){...}
3668Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3669 Scope *CurScope) {
3670 // Ensure that CurBlock is deleted.
3671 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3672 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3673
Steve Naroff52059382008-10-10 01:28:17 +00003674 PopDeclContext();
3675
Steve Naroff52a81c02008-09-03 18:15:37 +00003676 // Pop off CurBlock, handle nested blocks.
3677 CurBlock = CurBlock->PrevBlockInfo;
3678
3679 QualType RetTy = Context.VoidTy;
3680 if (BSI->ReturnType)
3681 RetTy = QualType(BSI->ReturnType, 0);
3682
3683 llvm::SmallVector<QualType, 8> ArgTypes;
3684 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3685 ArgTypes.push_back(BSI->Params[i]->getType());
3686
3687 QualType BlockTy;
3688 if (!BSI->hasPrototype)
3689 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3690 else
3691 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003692 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003693
3694 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003695
Steve Naroff95029d92008-10-08 18:44:00 +00003696 BSI->TheDecl->setBody(Body.take());
3697 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003698}
3699
Nate Begemanbd881ef2008-01-30 20:50:20 +00003700/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003701/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003702/// The number of arguments has already been validated to match the number of
3703/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003704static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3705 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003706 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003707 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003708 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3709 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003710
3711 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003712 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003713 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003714 return true;
3715}
3716
3717Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3718 SourceLocation *CommaLocs,
3719 SourceLocation BuiltinLoc,
3720 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003721 // __builtin_overload requires at least 2 arguments
3722 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003723 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3724 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003725
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003726 // The first argument is required to be a constant expression. It tells us
3727 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003728 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003729 Expr *NParamsExpr = Args[0];
3730 llvm::APSInt constEval(32);
3731 SourceLocation ExpLoc;
3732 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003733 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3734 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003735
3736 // Verify that the number of parameters is > 0
3737 unsigned NumParams = constEval.getZExtValue();
3738 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003739 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3740 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003741 // Verify that we have at least 1 + NumParams arguments to the builtin.
3742 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003743 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3744 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003745
3746 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003747 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003748 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003749 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3750 // UsualUnaryConversions will convert the function DeclRefExpr into a
3751 // pointer to function.
3752 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003753 const FunctionTypeProto *FnType = 0;
3754 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3755 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003756
3757 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3758 // parameters, and the number of parameters must match the value passed to
3759 // the builtin.
3760 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003761 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
3762 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003763
3764 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003765 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003766 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003767 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003768 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003769 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
3770 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00003771 // Remember our match, and continue processing the remaining arguments
3772 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003773 OE = new OverloadExpr(Args, NumArgs, i,
3774 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003775 BuiltinLoc, RParenLoc);
3776 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003777 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003778 // Return the newly created OverloadExpr node, if we succeded in matching
3779 // exactly one of the candidate functions.
3780 if (OE)
3781 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003782
3783 // If we didn't find a matching function Expr in the __builtin_overload list
3784 // the return an error.
3785 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003786 for (unsigned i = 0; i != NumParams; ++i) {
3787 if (i != 0) typeNames += ", ";
3788 typeNames += Args[i+1]->getType().getAsString();
3789 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003790
Chris Lattner77d52da2008-11-20 06:06:08 +00003791 return Diag(BuiltinLoc, diag::err_overload_no_match)
3792 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003793}
3794
Anders Carlsson36760332007-10-15 20:28:48 +00003795Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3796 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003797 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003798 Expr *E = static_cast<Expr*>(expr);
3799 QualType T = QualType::getFromOpaquePtr(type);
3800
3801 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003802
3803 // Get the va_list type
3804 QualType VaListType = Context.getBuiltinVaListType();
3805 // Deal with implicit array decay; for example, on x86-64,
3806 // va_list is an array, but it's supposed to decay to
3807 // a pointer for va_arg.
3808 if (VaListType->isArrayType())
3809 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003810 // Make sure the input expression also decays appropriately.
3811 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003812
3813 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003814 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00003815 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003816 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00003817
3818 // FIXME: Warn if a non-POD type is passed in.
3819
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003820 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003821}
3822
Douglas Gregorad4b3792008-11-29 04:51:27 +00003823Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
3824 // The type of __null will be int or long, depending on the size of
3825 // pointers on the target.
3826 QualType Ty;
3827 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
3828 Ty = Context.IntTy;
3829 else
3830 Ty = Context.LongTy;
3831
3832 return new GNUNullExpr(Ty, TokenLoc);
3833}
3834
Chris Lattner005ed752008-01-04 18:04:52 +00003835bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3836 SourceLocation Loc,
3837 QualType DstType, QualType SrcType,
3838 Expr *SrcExpr, const char *Flavor) {
3839 // Decode the result (notice that AST's are still created for extensions).
3840 bool isInvalid = false;
3841 unsigned DiagKind;
3842 switch (ConvTy) {
3843 default: assert(0 && "Unknown conversion type");
3844 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003845 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003846 DiagKind = diag::ext_typecheck_convert_pointer_int;
3847 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003848 case IntToPointer:
3849 DiagKind = diag::ext_typecheck_convert_int_pointer;
3850 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003851 case IncompatiblePointer:
3852 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3853 break;
3854 case FunctionVoidPointer:
3855 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3856 break;
3857 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003858 // If the qualifiers lost were because we were applying the
3859 // (deprecated) C++ conversion from a string literal to a char*
3860 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3861 // Ideally, this check would be performed in
3862 // CheckPointerTypesForAssignment. However, that would require a
3863 // bit of refactoring (so that the second argument is an
3864 // expression, rather than a type), which should be done as part
3865 // of a larger effort to fix CheckPointerTypesForAssignment for
3866 // C++ semantics.
3867 if (getLangOptions().CPlusPlus &&
3868 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3869 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003870 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3871 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003872 case IntToBlockPointer:
3873 DiagKind = diag::err_int_to_block_pointer;
3874 break;
3875 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003876 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003877 break;
Steve Naroff19608432008-10-14 22:18:38 +00003878 case IncompatibleObjCQualifiedId:
3879 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3880 // it can give a more specific diagnostic.
3881 DiagKind = diag::warn_incompatible_qualified_id;
3882 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003883 case Incompatible:
3884 DiagKind = diag::err_typecheck_convert_incompatible;
3885 isInvalid = true;
3886 break;
3887 }
3888
Chris Lattner271d4c22008-11-24 05:29:24 +00003889 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
3890 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00003891 return isInvalid;
3892}
Anders Carlssond5201b92008-11-30 19:50:32 +00003893
3894bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
3895{
3896 Expr::EvalResult EvalResult;
3897
3898 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
3899 EvalResult.HasSideEffects) {
3900 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
3901
3902 if (EvalResult.Diag) {
3903 // We only show the note if it's not the usual "invalid subexpression"
3904 // or if it's actually in a subexpression.
3905 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
3906 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
3907 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3908 }
3909
3910 return true;
3911 }
3912
3913 if (EvalResult.Diag) {
3914 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
3915 E->getSourceRange();
3916
3917 // Print the reason it's not a constant.
3918 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
3919 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3920 }
3921
3922 if (Result)
3923 *Result = EvalResult.Val.getInt();
3924 return false;
3925}