blob: cdaa2fc49c109edd5deec6ab8b3b7c7345a64bac [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)) {
Fariborz Jahanian09772392008-12-13 22:20:28 +0000421 FieldDecl *FD = IFace->lookupFieldDeclForIvar(Context, IV);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000422 // FIXME: This should use a new expr for a direct reference, don't turn
423 // this into Self->ivar, just return a BareIVarExpr or something.
424 IdentifierInfo &II = Context.Idents.get("self");
425 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Fariborz Jahanian09772392008-12-13 22:20:28 +0000426 return new ObjCIvarRefExpr(IV, FD, IV->getType(), Loc,
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000427 static_cast<Expr*>(SelfExpr.Val), true, true);
428 }
429 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000430 // Needed to implement property "super.method" notation.
Chris Lattner87fada82008-11-20 05:35:30 +0000431 if (SD == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000432 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000433 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000434 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000435 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000436 }
Chris Lattner4b009652007-07-25 00:24:17 +0000437 if (D == 0) {
438 // Otherwise, this could be an implicitly declared function reference (legal
439 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000440 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000441 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000442 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000443 else {
444 // If this name wasn't predeclared and if this is not a function call,
445 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000446 if (SS && !SS->isEmpty())
Chris Lattner77d52da2008-11-20 06:06:08 +0000447 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattnerb1753422008-11-23 21:45:46 +0000448 << Name << SS->getRange();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000449 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
450 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000451 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000452 else
Chris Lattnerb1753422008-11-23 21:45:46 +0000453 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000454 }
455 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000456
Douglas Gregor8acb7272008-12-11 16:49:14 +0000457 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000458 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
459 if (MD->isStatic())
460 // "invalid use of member 'x' in static member function"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000461 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattner271d4c22008-11-24 05:29:24 +0000462 << FD->getDeclName();
Douglas Gregor8acb7272008-12-11 16:49:14 +0000463 if (MD->getParent() != FD->getDeclContext())
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000464 // "invalid use of nonstatic data member 'x'"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000465 return Diag(Loc, diag::err_invalid_non_static_member_use)
Chris Lattner271d4c22008-11-24 05:29:24 +0000466 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000467
468 if (FD->isInvalidDecl())
469 return true;
470
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +0000471 // FIXME: Handle 'mutable'.
472 return new DeclRefExpr(FD,
473 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000474 }
475
Chris Lattner271d4c22008-11-24 05:29:24 +0000476 return Diag(Loc, diag::err_invalid_non_static_member_use)
477 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000478 }
Chris Lattner4b009652007-07-25 00:24:17 +0000479 if (isa<TypedefDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000480 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremenek42730c52008-01-07 19:49:32 +0000481 if (isa<ObjCInterfaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000482 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000483 if (isa<NamespaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000484 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000485
Steve Naroffd6163f32008-09-05 22:11:13 +0000486 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000487 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
488 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
489
Steve Naroffd6163f32008-09-05 22:11:13 +0000490 ValueDecl *VD = cast<ValueDecl>(D);
491
492 // check if referencing an identifier with __attribute__((deprecated)).
493 if (VD->getAttr<DeprecatedAttr>())
Chris Lattner271d4c22008-11-24 05:29:24 +0000494 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Douglas Gregor48840c72008-12-10 23:01:14 +0000495
496 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
497 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
498 Scope *CheckS = S;
499 while (CheckS) {
500 if (CheckS->isWithinElse() &&
501 CheckS->getControlParent()->isDeclScope(Var)) {
502 if (Var->getType()->isBooleanType())
503 Diag(Loc, diag::warn_value_always_false) << Var->getDeclName();
504 else
505 Diag(Loc, diag::warn_value_always_zero) << Var->getDeclName();
506 break;
507 }
508
509 // Move up one more control parent to check again.
510 CheckS = CheckS->getControlParent();
511 if (CheckS)
512 CheckS = CheckS->getParent();
513 }
514 }
515 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000516
517 // Only create DeclRefExpr's for valid Decl's.
518 if (VD->isInvalidDecl())
519 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000520
521 // If the identifier reference is inside a block, and it refers to a value
522 // that is outside the block, create a BlockDeclRefExpr instead of a
523 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
524 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000525 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000526 // We do not do this for things like enum constants, global variables, etc,
527 // as they do not get snapshotted.
528 //
529 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000530 // The BlocksAttr indicates the variable is bound by-reference.
531 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000532 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
533 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000534
535 // Variable will be bound by-copy, make it const within the closure.
536 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000537 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
538 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000539 }
540 // If this reference is not in a block or if the referenced variable is
541 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000542
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000543 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000544 bool ValueDependent = false;
545 if (getLangOptions().CPlusPlus) {
546 // C++ [temp.dep.expr]p3:
547 // An id-expression is type-dependent if it contains:
548 // - an identifier that was declared with a dependent type,
549 if (VD->getType()->isDependentType())
550 TypeDependent = true;
551 // - FIXME: a template-id that is dependent,
552 // - a conversion-function-id that specifies a dependent type,
553 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
554 Name.getCXXNameType()->isDependentType())
555 TypeDependent = true;
556 // - a nested-name-specifier that contains a class-name that
557 // names a dependent type.
558 else if (SS && !SS->isEmpty()) {
559 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
560 DC; DC = DC->getParent()) {
561 // FIXME: could stop early at namespace scope.
562 if (DC->isCXXRecord()) {
563 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
564 if (Context.getTypeDeclType(Record)->isDependentType()) {
565 TypeDependent = true;
566 break;
567 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000568 }
569 }
570 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000571
Douglas Gregora5d84612008-12-10 20:57:37 +0000572 // C++ [temp.dep.constexpr]p2:
573 //
574 // An identifier is value-dependent if it is:
575 // - a name declared with a dependent type,
576 if (TypeDependent)
577 ValueDependent = true;
578 // - the name of a non-type template parameter,
579 else if (isa<NonTypeTemplateParmDecl>(VD))
580 ValueDependent = true;
581 // - a constant with integral or enumeration type and is
582 // initialized with an expression that is value-dependent
583 // (FIXME!).
584 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000585
586 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
587 TypeDependent, ValueDependent);
Chris Lattner4b009652007-07-25 00:24:17 +0000588}
589
Chris Lattner69909292008-08-10 01:53:14 +0000590Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000591 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000592 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000593
594 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000595 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000596 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
597 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
598 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000599 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000600
Chris Lattner7e637512008-01-12 08:14:25 +0000601 // Pre-defined identifiers are of type char[x], where x is the length of the
602 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000603 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000604 if (FunctionDecl *FD = getCurFunctionDecl())
605 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000606 else if (ObjCMethodDecl *MD = getCurMethodDecl())
607 Length = MD->getSynthesizedMethodSize();
608 else {
609 Diag(Loc, diag::ext_predef_outside_function);
610 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
611 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
612 }
613
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000614
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000615 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000616 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000617 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000618 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000619}
620
Steve Naroff87d58b42007-09-16 03:34:24 +0000621Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000622 llvm::SmallString<16> CharBuffer;
623 CharBuffer.resize(Tok.getLength());
624 const char *ThisTokBegin = &CharBuffer[0];
625 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
626
627 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
628 Tok.getLocation(), PP);
629 if (Literal.hadError())
630 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000631
632 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
633
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000634 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
635 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000636}
637
Steve Naroff87d58b42007-09-16 03:34:24 +0000638Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000639 // fast path for a single digit (which is quite common). A single digit
640 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
641 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000642 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000643
Chris Lattner8cd0e932008-03-05 18:54:05 +0000644 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000645 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000646 Context.IntTy,
647 Tok.getLocation()));
648 }
649 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000650 // Add padding so that NumericLiteralParser can overread by one character.
651 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000652 const char *ThisTokBegin = &IntegerBuffer[0];
653
654 // Get the spelling of the token, which eliminates trigraphs, etc.
655 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000656
Chris Lattner4b009652007-07-25 00:24:17 +0000657 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
658 Tok.getLocation(), PP);
659 if (Literal.hadError)
660 return ExprResult(true);
661
Chris Lattner1de66eb2007-08-26 03:42:43 +0000662 Expr *Res;
663
664 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000665 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000666 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000667 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000668 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000669 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000670 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000671 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000672
673 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
674
Ted Kremenekddedbe22007-11-29 00:56:49 +0000675 // isExact will be set by GetFloatValue().
676 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000677 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000678 Ty, Tok.getLocation());
679
Chris Lattner1de66eb2007-08-26 03:42:43 +0000680 } else if (!Literal.isIntegerLiteral()) {
681 return ExprResult(true);
682 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000683 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000684
Neil Booth7421e9c2007-08-29 22:00:19 +0000685 // long long is a C99 feature.
686 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000687 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000688 Diag(Tok.getLocation(), diag::ext_longlong);
689
Chris Lattner4b009652007-07-25 00:24:17 +0000690 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000691 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000692
693 if (Literal.GetIntegerValue(ResultVal)) {
694 // If this value didn't fit into uintmax_t, warn and force to ull.
695 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000696 Ty = Context.UnsignedLongLongTy;
697 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000698 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000699 } else {
700 // If this value fits into a ULL, try to figure out what else it fits into
701 // according to the rules of C99 6.4.4.1p5.
702
703 // Octal, Hexadecimal, and integers with a U suffix are allowed to
704 // be an unsigned int.
705 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
706
707 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000708 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000709 if (!Literal.isLong && !Literal.isLongLong) {
710 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000711 unsigned IntSize = Context.Target.getIntWidth();
712
Chris Lattner4b009652007-07-25 00:24:17 +0000713 // Does it fit in a unsigned int?
714 if (ResultVal.isIntN(IntSize)) {
715 // Does it fit in a signed int?
716 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000717 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000718 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000719 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000720 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000721 }
Chris Lattner4b009652007-07-25 00:24:17 +0000722 }
723
724 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000725 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000726 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000727
728 // Does it fit in a unsigned long?
729 if (ResultVal.isIntN(LongSize)) {
730 // Does it fit in a signed long?
731 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000732 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000733 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000734 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000735 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000736 }
Chris Lattner4b009652007-07-25 00:24:17 +0000737 }
738
739 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000740 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000741 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000742
743 // Does it fit in a unsigned long long?
744 if (ResultVal.isIntN(LongLongSize)) {
745 // Does it fit in a signed long long?
746 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000747 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000748 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000749 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000750 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000751 }
752 }
753
754 // If we still couldn't decide a type, we probably have something that
755 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000756 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000757 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000758 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000759 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000760 }
Chris Lattnere4068872008-05-09 05:59:00 +0000761
762 if (ResultVal.getBitWidth() != Width)
763 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000764 }
765
Chris Lattner48d7f382008-04-02 04:24:33 +0000766 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000767 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000768
769 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
770 if (Literal.isImaginary)
771 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
772
773 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000774}
775
Steve Naroff87d58b42007-09-16 03:34:24 +0000776Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000777 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000778 Expr *E = (Expr *)Val;
779 assert((E != 0) && "ActOnParenExpr() missing expr");
780 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000781}
782
783/// The UsualUnaryConversions() function is *not* called by this routine.
784/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000785bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
786 SourceLocation OpLoc,
787 const SourceRange &ExprRange,
788 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000789 // C99 6.5.3.4p1:
790 if (isa<FunctionType>(exprType) && isSizeof)
791 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000792 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +0000793 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000794 Diag(OpLoc, diag::ext_sizeof_void_type)
795 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
796 else if (exprType->isIncompleteType())
797 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
798 diag::err_alignof_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000799 << exprType << ExprRange;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000800
801 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000802}
803
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000804/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
805/// the same for @c alignof and @c __alignof
806/// Note that the ArgRange is invalid if isType is false.
807Action::ExprResult
808Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
809 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +0000810 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000811 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000812
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000813 QualType ArgTy;
814 SourceRange Range;
815 if (isType) {
816 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
817 Range = ArgRange;
818 } else {
819 // Get the end location.
820 Expr *ArgEx = (Expr *)TyOrEx;
821 Range = ArgEx->getSourceRange();
822 ArgTy = ArgEx->getType();
823 }
824
825 // Verify that the operand is valid.
826 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +0000827 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000828
829 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
830 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
831 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +0000832}
833
Chris Lattner5110ad52007-08-24 21:41:10 +0000834QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000835 DefaultFunctionArrayConversion(V);
836
Chris Lattnera16e42d2007-08-26 05:39:26 +0000837 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000838 if (const ComplexType *CT = V->getType()->getAsComplexType())
839 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000840
841 // Otherwise they pass through real integer and floating point types here.
842 if (V->getType()->isArithmeticType())
843 return V->getType();
844
845 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +0000846 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000847 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000848}
849
850
Chris Lattner4b009652007-07-25 00:24:17 +0000851
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000852Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000853 tok::TokenKind Kind,
854 ExprTy *Input) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000855 Expr *Arg = (Expr *)Input;
856
Chris Lattner4b009652007-07-25 00:24:17 +0000857 UnaryOperator::Opcode Opc;
858 switch (Kind) {
859 default: assert(0 && "Unknown unary op!");
860 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
861 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
862 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000863
864 if (getLangOptions().CPlusPlus &&
865 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
866 // Which overloaded operator?
867 OverloadedOperatorKind OverOp =
868 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
869
870 // C++ [over.inc]p1:
871 //
872 // [...] If the function is a member function with one
873 // parameter (which shall be of type int) or a non-member
874 // function with two parameters (the second of which shall be
875 // of type int), it defines the postfix increment operator ++
876 // for objects of that type. When the postfix increment is
877 // called as a result of using the ++ operator, the int
878 // argument will have value zero.
879 Expr *Args[2] = {
880 Arg,
881 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
882 /*isSigned=*/true),
883 Context.IntTy, SourceLocation())
884 };
885
886 // Build the candidate set for overloading
887 OverloadCandidateSet CandidateSet;
888 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
889
890 // Perform overload resolution.
891 OverloadCandidateSet::iterator Best;
892 switch (BestViableFunction(CandidateSet, Best)) {
893 case OR_Success: {
894 // We found a built-in operator or an overloaded operator.
895 FunctionDecl *FnDecl = Best->Function;
896
897 if (FnDecl) {
898 // We matched an overloaded operator. Build a call to that
899 // operator.
900
901 // Convert the arguments.
902 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
903 if (PerformObjectArgumentInitialization(Arg, Method))
904 return true;
905 } else {
906 // Convert the arguments.
907 if (PerformCopyInitialization(Arg,
908 FnDecl->getParamDecl(0)->getType(),
909 "passing"))
910 return true;
911 }
912
913 // Determine the result type
914 QualType ResultTy
915 = FnDecl->getType()->getAsFunctionType()->getResultType();
916 ResultTy = ResultTy.getNonReferenceType();
917
918 // Build the actual expression node.
919 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
920 SourceLocation());
921 UsualUnaryConversions(FnExpr);
922
923 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
924 } else {
925 // We matched a built-in operator. Convert the arguments, then
926 // break out so that we will build the appropriate built-in
927 // operator node.
928 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
929 "passing"))
930 return true;
931
932 break;
933 }
934 }
935
936 case OR_No_Viable_Function:
937 // No viable function; fall through to handling this as a
938 // built-in operator, which will produce an error message for us.
939 break;
940
941 case OR_Ambiguous:
942 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
943 << UnaryOperator::getOpcodeStr(Opc)
944 << Arg->getSourceRange();
945 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
946 return true;
947 }
948
949 // Either we found no viable overloaded operator or we matched a
950 // built-in operator. In either case, fall through to trying to
951 // build a built-in operation.
952 }
953
954 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000955 if (result.isNull())
956 return true;
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000957 return new UnaryOperator(Arg, Opc, result, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000958}
959
960Action::ExprResult Sema::
Douglas Gregor80723c52008-11-19 17:17:41 +0000961ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000962 ExprTy *Idx, SourceLocation RLoc) {
963 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
964
Douglas Gregor80723c52008-11-19 17:17:41 +0000965 if (getLangOptions().CPlusPlus &&
Eli Friedmane658bf52008-12-15 22:34:21 +0000966 (LHSExp->getType()->isRecordType() ||
967 LHSExp->getType()->isEnumeralType() ||
968 RHSExp->getType()->isRecordType() ||
969 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +0000970 // Add the appropriate overloaded operators (C++ [over.match.oper])
971 // to the candidate set.
972 OverloadCandidateSet CandidateSet;
973 Expr *Args[2] = { LHSExp, RHSExp };
974 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
975
976 // Perform overload resolution.
977 OverloadCandidateSet::iterator Best;
978 switch (BestViableFunction(CandidateSet, Best)) {
979 case OR_Success: {
980 // We found a built-in operator or an overloaded operator.
981 FunctionDecl *FnDecl = Best->Function;
982
983 if (FnDecl) {
984 // We matched an overloaded operator. Build a call to that
985 // operator.
986
987 // Convert the arguments.
988 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
989 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
990 PerformCopyInitialization(RHSExp,
991 FnDecl->getParamDecl(0)->getType(),
992 "passing"))
993 return true;
994 } else {
995 // Convert the arguments.
996 if (PerformCopyInitialization(LHSExp,
997 FnDecl->getParamDecl(0)->getType(),
998 "passing") ||
999 PerformCopyInitialization(RHSExp,
1000 FnDecl->getParamDecl(1)->getType(),
1001 "passing"))
1002 return true;
1003 }
1004
1005 // Determine the result type
1006 QualType ResultTy
1007 = FnDecl->getType()->getAsFunctionType()->getResultType();
1008 ResultTy = ResultTy.getNonReferenceType();
1009
1010 // Build the actual expression node.
1011 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1012 SourceLocation());
1013 UsualUnaryConversions(FnExpr);
1014
1015 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
1016 } else {
1017 // We matched a built-in operator. Convert the arguments, then
1018 // break out so that we will build the appropriate built-in
1019 // operator node.
1020 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1021 "passing") ||
1022 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1023 "passing"))
1024 return true;
1025
1026 break;
1027 }
1028 }
1029
1030 case OR_No_Viable_Function:
1031 // No viable function; fall through to handling this as a
1032 // built-in operator, which will produce an error message for us.
1033 break;
1034
1035 case OR_Ambiguous:
1036 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1037 << "[]"
1038 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1039 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1040 return true;
1041 }
1042
1043 // Either we found no viable overloaded operator or we matched a
1044 // built-in operator. In either case, fall through to trying to
1045 // build a built-in operation.
1046 }
1047
Chris Lattner4b009652007-07-25 00:24:17 +00001048 // Perform default conversions.
1049 DefaultFunctionArrayConversion(LHSExp);
1050 DefaultFunctionArrayConversion(RHSExp);
1051
1052 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1053
1054 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001055 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001056 // in the subscript position. As a result, we need to derive the array base
1057 // and index from the expression types.
1058 Expr *BaseExpr, *IndexExpr;
1059 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001060 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001061 BaseExpr = LHSExp;
1062 IndexExpr = RHSExp;
1063 // FIXME: need to deal with const...
1064 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001065 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001066 // Handle the uncommon case of "123[Ptr]".
1067 BaseExpr = RHSExp;
1068 IndexExpr = LHSExp;
1069 // FIXME: need to deal with const...
1070 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001071 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1072 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001073 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +00001074
1075 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +00001076 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1077 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001078 return Diag(LLoc, diag::err_ext_vector_component_access)
1079 << SourceRange(LLoc, RLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001080 // FIXME: need to deal with const...
1081 ResultType = VTy->getElementType();
1082 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001083 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
1084 << RHSExp->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001085 }
1086 // C99 6.5.2.1p1
1087 if (!IndexExpr->getType()->isIntegerType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001088 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
1089 << IndexExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001090
1091 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1092 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001093 // void (*)(int)) and pointers to incomplete types. Functions are not
1094 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001095 if (!ResultType->isObjectType())
1096 return Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001097 diag::err_typecheck_subscript_not_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001098 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001099
1100 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
1101}
1102
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001103QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001104CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001105 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001106 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001107
1108 // This flag determines whether or not the component is to be treated as a
1109 // special name, or a regular GLSL-style component access.
1110 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001111
1112 // The vector accessor can't exceed the number of elements.
1113 const char *compStr = CompName.getName();
1114 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001115 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001116 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001117 return QualType();
1118 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001119
1120 // Check that we've found one of the special components, or that the component
1121 // names must come from the same set.
1122 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1123 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1124 SpecialComponent = true;
1125 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001126 do
1127 compStr++;
1128 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1129 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1130 do
1131 compStr++;
1132 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1133 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1134 do
1135 compStr++;
1136 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1137 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001138
Nate Begemanc8e51f82008-05-09 06:41:27 +00001139 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001140 // We didn't get to the end of the string. This means the component names
1141 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001142 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1143 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001144 return QualType();
1145 }
1146 // Each component accessor can't exceed the vector type.
1147 compStr = CompName.getName();
1148 while (*compStr) {
1149 if (vecType->isAccessorWithinNumElements(*compStr))
1150 compStr++;
1151 else
1152 break;
1153 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001154 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001155 // We didn't get to the end of the string. This means a component accessor
1156 // exceeds the number of elements in the vector.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001157 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001158 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001159 return QualType();
1160 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001161
1162 // If we have a special component name, verify that the current vector length
1163 // is an even number, since all special component names return exactly half
1164 // the elements.
1165 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001166 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001167 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001168 return QualType();
1169 }
1170
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001171 // The component accessor looks fine - now we need to compute the actual type.
1172 // The vector type is implied by the component accessor. For example,
1173 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001174 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1175 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner65cae292008-11-19 08:23:25 +00001176 : CompName.getLength();
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001177 if (CompSize == 1)
1178 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001179
Nate Begemanaf6ed502008-04-18 23:10:10 +00001180 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001181 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001182 // diagostics look bad. We want extended vector types to appear built-in.
1183 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1184 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1185 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001186 }
1187 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001188}
1189
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001190/// constructSetterName - Return the setter name for the given
1191/// identifier, i.e. "set" + Name where the initial character of Name
1192/// has been capitalized.
1193// FIXME: Merge with same routine in Parser. But where should this
1194// live?
1195static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1196 const IdentifierInfo *Name) {
1197 llvm::SmallString<100> SelectorName;
1198 SelectorName = "set";
1199 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1200 SelectorName[3] = toupper(SelectorName[3]);
1201 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1202}
1203
Chris Lattner4b009652007-07-25 00:24:17 +00001204Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001205ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001206 tok::TokenKind OpKind, SourceLocation MemberLoc,
1207 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001208 Expr *BaseExpr = static_cast<Expr *>(Base);
1209 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001210
1211 // Perform default conversions.
1212 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +00001213
Steve Naroff2cb66382007-07-26 03:11:44 +00001214 QualType BaseType = BaseExpr->getType();
1215 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001216
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001217 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1218 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001219 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001220 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001221 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001222 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
1223 return BuildOverloadedArrowExpr(BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroff2cb66382007-07-26 03:11:44 +00001224 else
Chris Lattner8ba580c2008-11-19 05:08:23 +00001225 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001226 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001227 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001228
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001229 // Handle field access to simple records. This also handles access to fields
1230 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001231 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001232 RecordDecl *RDecl = RTy->getDecl();
1233 if (RTy->isIncompleteType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001234 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattner271d4c22008-11-24 05:29:24 +00001235 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroff2cb66382007-07-26 03:11:44 +00001236 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001237 // FIXME: Qualified name lookup for C++ is a bit more complicated
1238 // than this.
1239 DeclContext::lookup_result Lookup = RDecl->lookup(Context, &Member);
1240 if (Lookup.first == Lookup.second) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001241 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner65cae292008-11-19 08:23:25 +00001242 << &Member << BaseExpr->getSourceRange();
Douglas Gregor8acb7272008-12-11 16:49:14 +00001243 }
1244
1245 FieldDecl *MemberDecl = dyn_cast<FieldDecl>(*Lookup.first);
1246 if (!MemberDecl) {
1247 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
1248 "Clang only supports references to members");
1249 return Diag(MemberLoc, DiagID);
1250 }
Eli Friedman76b49832008-02-06 22:48:16 +00001251
1252 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +00001253 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +00001254 QualType MemberType = MemberDecl->getType();
1255 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +00001256 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor8acb7272008-12-11 16:49:14 +00001257 if (MemberDecl->isMutable())
1258 combinedQualifiers &= ~QualType::Const;
Eli Friedman76b49832008-02-06 22:48:16 +00001259 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1260
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001261 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +00001262 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +00001263 }
1264
Chris Lattnere9d71612008-07-21 04:59:05 +00001265 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1266 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001267 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001268 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
1269 FieldDecl *FD = IFTy->getDecl()->lookupFieldDeclForIvar(Context, IV);
1270 return new ObjCIvarRefExpr(IV, FD, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +00001271 OpKind == tok::arrow);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001272 }
Chris Lattner8ba580c2008-11-19 05:08:23 +00001273 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattner271d4c22008-11-24 05:29:24 +00001274 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattner8ba580c2008-11-19 05:08:23 +00001275 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001276 }
1277
Chris Lattnere9d71612008-07-21 04:59:05 +00001278 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1279 // pointer to a (potentially qualified) interface type.
1280 const PointerType *PTy;
1281 const ObjCInterfaceType *IFTy;
1282 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1283 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1284 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001285
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001286 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001287 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1288 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1289
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001290 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001291 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1292 E = IFTy->qual_end(); I != E; ++I)
1293 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1294 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001295
1296 // If that failed, look for an "implicit" property by seeing if the nullary
1297 // selector is implemented.
1298
1299 // FIXME: The logic for looking up nullary and unary selectors should be
1300 // shared with the code in ActOnInstanceMessage.
1301
1302 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1303 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1304
1305 // If this reference is in an @implementation, check for 'private' methods.
1306 if (!Getter)
1307 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1308 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1309 if (ObjCImplementationDecl *ImpDecl =
1310 ObjCImplementations[ClassDecl->getIdentifier()])
1311 Getter = ImpDecl->getInstanceMethod(Sel);
1312
Steve Naroff04151f32008-10-22 19:16:27 +00001313 // Look through local category implementations associated with the class.
1314 if (!Getter) {
1315 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1316 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1317 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1318 }
1319 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001320 if (Getter) {
1321 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001322 // will look for the matching setter, in case it is needed.
1323 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1324 &Member);
1325 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1326 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1327 if (!Setter) {
1328 // If this reference is in an @implementation, also check for 'private'
1329 // methods.
1330 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1331 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1332 if (ObjCImplementationDecl *ImpDecl =
1333 ObjCImplementations[ClassDecl->getIdentifier()])
1334 Setter = ImpDecl->getInstanceMethod(SetterSel);
1335 }
1336 // Look through local category implementations associated with the class.
1337 if (!Setter) {
1338 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1339 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1340 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1341 }
1342 }
1343
1344 // FIXME: we must check that the setter has property type.
1345 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00001346 MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001347 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001348 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001349 // Handle properties on qualified "id" protocols.
1350 const ObjCQualifiedIdType *QIdTy;
1351 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1352 // Check protocols on qualified interfaces.
1353 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001354 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001355 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1356 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001357 // Also must look for a getter name which uses property syntax.
1358 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1359 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1360 return new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(), OMD,
1361 OpLoc, MemberLoc, NULL, 0);
1362 }
1363 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001364 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001365 // Handle 'field access' to vectors, such as 'V.xx'.
1366 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1367 // Component access limited to variables (reject vec4.rg.g).
1368 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1369 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001370 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1371 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001372 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1373 if (ret.isNull())
1374 return true;
1375 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1376 }
1377
Chris Lattner8ba580c2008-11-19 05:08:23 +00001378 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001379 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001380}
1381
Steve Naroff87d58b42007-09-16 03:34:24 +00001382/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001383/// This provides the location of the left/right parens and a list of comma
1384/// locations.
1385Action::ExprResult Sema::
Douglas Gregora133e262008-12-06 00:22:45 +00001386ActOnCallExpr(Scope *S, ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001387 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001388 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1389 Expr *Fn = static_cast<Expr *>(fn);
1390 Expr **Args = reinterpret_cast<Expr**>(args);
1391 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001392 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001393 OverloadedFunctionDecl *Ovl = NULL;
1394
Douglas Gregora133e262008-12-06 00:22:45 +00001395 // Determine whether this is a dependent call inside a C++ template,
1396 // in which case we won't do any semantic analysis now.
1397 bool Dependent = false;
1398 if (Fn->isTypeDependent()) {
1399 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1400 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1401 Dependent = true;
1402 else {
1403 // Resolve the CXXDependentNameExpr to an actual identifier;
1404 // it wasn't really a dependent name after all.
1405 ExprResult Resolved
1406 = ActOnDeclarationNameExpr(S, FnName->getLocation(), FnName->getName(),
1407 /*HasTrailingLParen=*/true,
1408 /*SS=*/0,
1409 /*ForceResolution=*/true);
1410 if (Resolved.isInvalid)
1411 return true;
1412 else {
1413 delete Fn;
1414 Fn = (Expr *)Resolved.Val;
1415 }
1416 }
1417 } else
1418 Dependent = true;
1419 } else
1420 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1421
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001422 // FIXME: Will need to cache the results of name lookup (including
1423 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001424 if (Dependent)
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001425 return new CallExpr(Fn, Args, NumArgs, Context.DependentTy, RParenLoc);
1426
Douglas Gregord2baafd2008-10-21 16:13:35 +00001427 // If we're directly calling a function or a set of overloaded
1428 // functions, get the appropriate declaration.
1429 {
1430 DeclRefExpr *DRExpr = NULL;
1431 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1432 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1433 else
1434 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1435
1436 if (DRExpr) {
1437 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1438 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1439 }
1440 }
1441
Douglas Gregord2baafd2008-10-21 16:13:35 +00001442 if (Ovl) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001443 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1444 RParenLoc);
1445 if (!FDecl)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001446 return true;
1447
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001448 // Update Fn to refer to the actual function selected.
1449 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1450 Fn->getSourceRange().getBegin());
1451 Fn->Destroy(Context);
1452 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001453 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001454
Douglas Gregor10f3c502008-11-19 21:05:33 +00001455 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Douglas Gregora133e262008-12-06 00:22:45 +00001456 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregor10f3c502008-11-19 21:05:33 +00001457 CommaLocs, RParenLoc);
1458
Chris Lattner3e254fb2008-04-08 04:40:51 +00001459 // Promote the function operand.
1460 UsualUnaryConversions(Fn);
1461
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001462 // Make the call expr early, before semantic checks. This guarantees cleanup
1463 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001464 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001465 Context.BoolTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001466
Steve Naroffd6163f32008-09-05 22:11:13 +00001467 const FunctionType *FuncT;
1468 if (!Fn->getType()->isBlockPointerType()) {
1469 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1470 // have type pointer to function".
1471 const PointerType *PT = Fn->getType()->getAsPointerType();
1472 if (PT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001473 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001474 << Fn->getType() << Fn->getSourceRange();
Steve Naroffd6163f32008-09-05 22:11:13 +00001475 FuncT = PT->getPointeeType()->getAsFunctionType();
1476 } else { // This is a block call.
1477 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1478 getAsFunctionType();
1479 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001480 if (FuncT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001481 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001482 << Fn->getType() << Fn->getSourceRange();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001483
1484 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001485 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001486
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001487 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001488 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1489 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001490 unsigned NumArgsInProto = Proto->getNumArgs();
1491 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001492
Chris Lattner3e254fb2008-04-08 04:40:51 +00001493 // If too few arguments are available (and we don't have default
1494 // arguments for the remaining parameters), don't make the call.
1495 if (NumArgs < NumArgsInProto) {
Chris Lattner66beaba2008-11-21 18:44:24 +00001496 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1497 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1498 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1499 // Use default arguments for missing arguments
1500 NumArgsToCheck = NumArgsInProto;
1501 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001502 }
1503
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001504 // If too many are passed and not variadic, error on the extras and drop
1505 // them.
1506 if (NumArgs > NumArgsInProto) {
1507 if (!Proto->isVariadic()) {
Chris Lattner66beaba2008-11-21 18:44:24 +00001508 Diag(Args[NumArgsInProto]->getLocStart(),
1509 diag::err_typecheck_call_too_many_args)
1510 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
Chris Lattner8ba580c2008-11-19 05:08:23 +00001511 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1512 Args[NumArgs-1]->getLocEnd());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001513 // This deletes the extra arguments.
1514 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001515 }
1516 NumArgsToCheck = NumArgsInProto;
1517 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001518
Chris Lattner4b009652007-07-25 00:24:17 +00001519 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001520 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001521 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001522
1523 Expr *Arg;
1524 if (i < NumArgs)
1525 Arg = Args[i];
1526 else
1527 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001528 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001529
Douglas Gregor81c29152008-10-29 00:13:59 +00001530 // Pass the argument.
1531 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner005ed752008-01-04 18:04:52 +00001532 return true;
Douglas Gregor81c29152008-10-29 00:13:59 +00001533
1534 TheCall->setArg(i, Arg);
Chris Lattner4b009652007-07-25 00:24:17 +00001535 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001536
1537 // If this is a variadic call, handle args passed through "...".
1538 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001539 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001540 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1541 Expr *Arg = Args[i];
1542 DefaultArgumentPromotion(Arg);
1543 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001544 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001545 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001546 } else {
1547 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1548
Steve Naroffdb65e052007-08-28 23:30:39 +00001549 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001550 for (unsigned i = 0; i != NumArgs; i++) {
1551 Expr *Arg = Args[i];
1552 DefaultArgumentPromotion(Arg);
1553 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001554 }
Chris Lattner4b009652007-07-25 00:24:17 +00001555 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001556
Chris Lattner2e64c072007-08-10 20:18:51 +00001557 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001558 if (FDecl)
1559 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001560
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001561 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001562}
1563
1564Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001565ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001566 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001567 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001568 QualType literalType = QualType::getFromOpaquePtr(Ty);
1569 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001570 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001571 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001572
Eli Friedman8c2173d2008-05-20 05:22:08 +00001573 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001574 if (literalType->isVariableArrayType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001575 return Diag(LParenLoc, diag::err_variable_object_no_init)
1576 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001577 } else if (literalType->isIncompleteType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001578 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +00001579 << literalType
Chris Lattner8ba580c2008-11-19 05:08:23 +00001580 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001581 }
1582
Douglas Gregor6428e762008-11-05 15:29:30 +00001583 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Chris Lattner271d4c22008-11-24 05:29:24 +00001584 DeclarationName()))
Steve Naroff92590f92008-01-09 20:58:06 +00001585 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001586
Chris Lattnere5cb5862008-12-04 23:50:19 +00001587 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001588 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001589 if (CheckForConstantInitializer(literalExpr, literalType))
1590 return true;
1591 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001592 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1593 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001594}
1595
1596Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001597ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001598 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001599 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001600 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001601
Steve Naroff0acc9c92007-09-15 18:49:24 +00001602 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001603 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001604
Chris Lattner71ca8c82008-10-26 23:43:26 +00001605 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1606 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001607 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1608 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001609}
1610
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001611/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001612bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001613 UsualUnaryConversions(castExpr);
1614
1615 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1616 // type needs to be scalar.
1617 if (castType->isVoidType()) {
1618 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001619 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1620 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001621 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1622 // GCC struct/union extension: allow cast to self.
1623 if (Context.getCanonicalType(castType) !=
1624 Context.getCanonicalType(castExpr->getType()) ||
1625 (!castType->isStructureType() && !castType->isUnionType())) {
1626 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001627 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001628 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001629 }
1630
1631 // accept this, but emit an ext-warn.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001632 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001633 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001634 } else if (!castExpr->getType()->isScalarType() &&
1635 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001636 return Diag(castExpr->getLocStart(),
1637 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001638 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001639 } else if (castExpr->getType()->isVectorType()) {
1640 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1641 return true;
1642 } else if (castType->isVectorType()) {
1643 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1644 return true;
1645 }
1646 return false;
1647}
1648
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001649bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001650 assert(VectorTy->isVectorType() && "Not a vector type!");
1651
1652 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001653 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001654 return Diag(R.getBegin(),
1655 Ty->isVectorType() ?
1656 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00001657 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001658 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001659 } else
1660 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001661 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001662 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001663
1664 return false;
1665}
1666
Chris Lattner4b009652007-07-25 00:24:17 +00001667Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001668ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001669 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001670 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001671
1672 Expr *castExpr = static_cast<Expr*>(Op);
1673 QualType castType = QualType::getFromOpaquePtr(Ty);
1674
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001675 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1676 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00001677 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001678}
1679
Chris Lattner98a425c2007-11-26 01:40:58 +00001680/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1681/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001682inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1683 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1684 UsualUnaryConversions(cond);
1685 UsualUnaryConversions(lex);
1686 UsualUnaryConversions(rex);
1687 QualType condT = cond->getType();
1688 QualType lexT = lex->getType();
1689 QualType rexT = rex->getType();
1690
1691 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001692 if (!cond->isTypeDependent()) {
1693 if (!condT->isScalarType()) { // C99 6.5.15p2
1694 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
1695 return QualType();
1696 }
Chris Lattner4b009652007-07-25 00:24:17 +00001697 }
Chris Lattner992ae932008-01-06 22:42:25 +00001698
1699 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001700 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
1701 return Context.DependentTy;
1702
Chris Lattner992ae932008-01-06 22:42:25 +00001703 // If both operands have arithmetic type, do the usual arithmetic conversions
1704 // to find a common type: C99 6.5.15p3,5.
1705 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001706 UsualArithmeticConversions(lex, rex);
1707 return lex->getType();
1708 }
Chris Lattner992ae932008-01-06 22:42:25 +00001709
1710 // If both operands are the same structure or union type, the result is that
1711 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001712 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001713 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001714 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001715 // "If both the operands have structure or union type, the result has
1716 // that type." This implies that CV qualifiers are dropped.
1717 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001718 }
Chris Lattner992ae932008-01-06 22:42:25 +00001719
1720 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001721 // The following || allows only one side to be void (a GCC-ism).
1722 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001723 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001724 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
1725 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00001726 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001727 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
1728 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00001729 ImpCastExprToType(lex, Context.VoidTy);
1730 ImpCastExprToType(rex, Context.VoidTy);
1731 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001732 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001733 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1734 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001735 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1736 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001737 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001738 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001739 return lexT;
1740 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001741 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1742 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001743 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001744 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001745 return rexT;
1746 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001747 // Handle the case where both operands are pointers before we handle null
1748 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001749 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1750 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1751 // get the "pointed to" types
1752 QualType lhptee = LHSPT->getPointeeType();
1753 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001754
Chris Lattner71225142007-07-31 21:27:01 +00001755 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1756 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001757 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001758 // Figure out necessary qualifiers (C99 6.5.15p6)
1759 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001760 QualType destType = Context.getPointerType(destPointee);
1761 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1762 ImpCastExprToType(rex, destType); // promote to void*
1763 return destType;
1764 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001765 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001766 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001767 QualType destType = Context.getPointerType(destPointee);
1768 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1769 ImpCastExprToType(rex, destType); // promote to void*
1770 return destType;
1771 }
Chris Lattner4b009652007-07-25 00:24:17 +00001772
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001773 QualType compositeType = lexT;
1774
1775 // If either type is an Objective-C object type then check
1776 // compatibility according to Objective-C.
1777 if (Context.isObjCObjectPointerType(lexT) ||
1778 Context.isObjCObjectPointerType(rexT)) {
1779 // If both operands are interfaces and either operand can be
1780 // assigned to the other, use that type as the composite
1781 // type. This allows
1782 // xxx ? (A*) a : (B*) b
1783 // where B is a subclass of A.
1784 //
1785 // Additionally, as for assignment, if either type is 'id'
1786 // allow silent coercion. Finally, if the types are
1787 // incompatible then make sure to use 'id' as the composite
1788 // type so the result is acceptable for sending messages to.
1789
1790 // FIXME: This code should not be localized to here. Also this
1791 // should use a compatible check instead of abusing the
1792 // canAssignObjCInterfaces code.
1793 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1794 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1795 if (LHSIface && RHSIface &&
1796 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1797 compositeType = lexT;
1798 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00001799 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001800 compositeType = rexT;
1801 } else if (Context.isObjCIdType(lhptee) ||
1802 Context.isObjCIdType(rhptee)) {
1803 // FIXME: This code looks wrong, because isObjCIdType checks
1804 // the struct but getObjCIdType returns the pointer to
1805 // struct. This is horrible and should be fixed.
1806 compositeType = Context.getObjCIdType();
1807 } else {
1808 QualType incompatTy = Context.getObjCIdType();
1809 ImpCastExprToType(lex, incompatTy);
1810 ImpCastExprToType(rex, incompatTy);
1811 return incompatTy;
1812 }
1813 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1814 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00001815 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001816 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001817 // In this situation, we assume void* type. No especially good
1818 // reason, but this is what gcc does, and we do have to pick
1819 // to get a consistent AST.
1820 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001821 ImpCastExprToType(lex, incompatTy);
1822 ImpCastExprToType(rex, incompatTy);
1823 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001824 }
1825 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001826 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1827 // differently qualified versions of compatible types, the result type is
1828 // a pointer to an appropriately qualified version of the *composite*
1829 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001830 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001831 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001832 ImpCastExprToType(lex, compositeType);
1833 ImpCastExprToType(rex, compositeType);
1834 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001835 }
Chris Lattner4b009652007-07-25 00:24:17 +00001836 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001837 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1838 // evaluates to "struct objc_object *" (and is handled above when comparing
1839 // id with statically typed objects).
1840 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1841 // GCC allows qualified id and any Objective-C type to devolve to
1842 // id. Currently localizing to here until clear this should be
1843 // part of ObjCQualifiedIdTypesAreCompatible.
1844 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1845 (lexT->isObjCQualifiedIdType() &&
1846 Context.isObjCObjectPointerType(rexT)) ||
1847 (rexT->isObjCQualifiedIdType() &&
1848 Context.isObjCObjectPointerType(lexT))) {
1849 // FIXME: This is not the correct composite type. This only
1850 // happens to work because id can more or less be used anywhere,
1851 // however this may change the type of method sends.
1852 // FIXME: gcc adds some type-checking of the arguments and emits
1853 // (confusing) incompatible comparison warnings in some
1854 // cases. Investigate.
1855 QualType compositeType = Context.getObjCIdType();
1856 ImpCastExprToType(lex, compositeType);
1857 ImpCastExprToType(rex, compositeType);
1858 return compositeType;
1859 }
1860 }
1861
Steve Naroff3eac7692008-09-10 19:17:48 +00001862 // Selection between block pointer types is ok as long as they are the same.
1863 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1864 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1865 return lexT;
1866
Chris Lattner992ae932008-01-06 22:42:25 +00001867 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00001868 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001869 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001870 return QualType();
1871}
1872
Steve Naroff87d58b42007-09-16 03:34:24 +00001873/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001874/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001875Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001876 SourceLocation ColonLoc,
1877 ExprTy *Cond, ExprTy *LHS,
1878 ExprTy *RHS) {
1879 Expr *CondExpr = (Expr *) Cond;
1880 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001881
1882 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1883 // was the condition.
1884 bool isLHSNull = LHSExpr == 0;
1885 if (isLHSNull)
1886 LHSExpr = CondExpr;
1887
Chris Lattner4b009652007-07-25 00:24:17 +00001888 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1889 RHSExpr, QuestionLoc);
1890 if (result.isNull())
1891 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001892 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1893 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001894}
1895
Chris Lattner4b009652007-07-25 00:24:17 +00001896
1897// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1898// being closely modeled after the C99 spec:-). The odd characteristic of this
1899// routine is it effectively iqnores the qualifiers on the top level pointee.
1900// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1901// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001902Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001903Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1904 QualType lhptee, rhptee;
1905
1906 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001907 lhptee = lhsType->getAsPointerType()->getPointeeType();
1908 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001909
1910 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001911 lhptee = Context.getCanonicalType(lhptee);
1912 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001913
Chris Lattner005ed752008-01-04 18:04:52 +00001914 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001915
1916 // C99 6.5.16.1p1: This following citation is common to constraints
1917 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1918 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001919 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001920 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001921 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001922
1923 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1924 // incomplete type and the other is a pointer to a qualified or unqualified
1925 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001926 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001927 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001928 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001929
1930 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001931 assert(rhptee->isFunctionType());
1932 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001933 }
1934
1935 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001936 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001937 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001938
1939 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001940 assert(lhptee->isFunctionType());
1941 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001942 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001943
1944 // Check for ObjC interfaces
1945 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1946 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1947 if (LHSIface && RHSIface &&
1948 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1949 return ConvTy;
1950
1951 // ID acts sort of like void* for ObjC interfaces
1952 if (LHSIface && Context.isObjCIdType(rhptee))
1953 return ConvTy;
1954 if (RHSIface && Context.isObjCIdType(lhptee))
1955 return ConvTy;
1956
Chris Lattner4b009652007-07-25 00:24:17 +00001957 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1958 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001959 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1960 rhptee.getUnqualifiedType()))
1961 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001962 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001963}
1964
Steve Naroff3454b6c2008-09-04 15:10:53 +00001965/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1966/// block pointer types are compatible or whether a block and normal pointer
1967/// are compatible. It is more restrict than comparing two function pointer
1968// types.
1969Sema::AssignConvertType
1970Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1971 QualType rhsType) {
1972 QualType lhptee, rhptee;
1973
1974 // get the "pointed to" type (ignoring qualifiers at the top level)
1975 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1976 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1977
1978 // make sure we operate on the canonical type
1979 lhptee = Context.getCanonicalType(lhptee);
1980 rhptee = Context.getCanonicalType(rhptee);
1981
1982 AssignConvertType ConvTy = Compatible;
1983
1984 // For blocks we enforce that qualifiers are identical.
1985 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1986 ConvTy = CompatiblePointerDiscardsQualifiers;
1987
1988 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1989 return IncompatibleBlockPointer;
1990 return ConvTy;
1991}
1992
Chris Lattner4b009652007-07-25 00:24:17 +00001993/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1994/// has code to accommodate several GCC extensions when type checking
1995/// pointers. Here are some objectionable examples that GCC considers warnings:
1996///
1997/// int a, *pint;
1998/// short *pshort;
1999/// struct foo *pfoo;
2000///
2001/// pint = pshort; // warning: assignment from incompatible pointer type
2002/// a = pint; // warning: assignment makes integer from pointer without a cast
2003/// pint = a; // warning: assignment makes pointer from integer without a cast
2004/// pint = pfoo; // warning: assignment from incompatible pointer type
2005///
2006/// As a result, the code for dealing with pointers is more complex than the
2007/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002008///
Chris Lattner005ed752008-01-04 18:04:52 +00002009Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002010Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002011 // Get canonical types. We're not formatting these types, just comparing
2012 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002013 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2014 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002015
2016 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002017 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002018
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002019 // If the left-hand side is a reference type, then we are in a
2020 // (rare!) case where we've allowed the use of references in C,
2021 // e.g., as a parameter type in a built-in function. In this case,
2022 // just make sure that the type referenced is compatible with the
2023 // right-hand side type. The caller is responsible for adjusting
2024 // lhsType so that the resulting expression does not have reference
2025 // type.
2026 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2027 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002028 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002029 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002030 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002031
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002032 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2033 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002034 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002035 // Relax integer conversions like we do for pointers below.
2036 if (rhsType->isIntegerType())
2037 return IntToPointer;
2038 if (lhsType->isIntegerType())
2039 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002040 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002041 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002042
Nate Begemanc5f0f652008-07-14 18:02:46 +00002043 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002044 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002045 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2046 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002047 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002048
Nate Begemanc5f0f652008-07-14 18:02:46 +00002049 // If we are allowing lax vector conversions, and LHS and RHS are both
2050 // vectors, the total size only needs to be the same. This is a bitcast;
2051 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002052 if (getLangOptions().LaxVectorConversions &&
2053 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002054 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2055 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002056 }
2057 return Incompatible;
2058 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002059
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002060 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002061 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002062
Chris Lattner390564e2008-04-07 06:49:41 +00002063 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002064 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002065 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002066
Chris Lattner390564e2008-04-07 06:49:41 +00002067 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002068 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002069
Steve Naroffa982c712008-09-29 18:10:17 +00002070 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002071 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002072 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002073
2074 // Treat block pointers as objects.
2075 if (getLangOptions().ObjC1 &&
2076 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2077 return Compatible;
2078 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002079 return Incompatible;
2080 }
2081
2082 if (isa<BlockPointerType>(lhsType)) {
2083 if (rhsType->isIntegerType())
2084 return IntToPointer;
2085
Steve Naroffa982c712008-09-29 18:10:17 +00002086 // Treat block pointers as objects.
2087 if (getLangOptions().ObjC1 &&
2088 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2089 return Compatible;
2090
Steve Naroff3454b6c2008-09-04 15:10:53 +00002091 if (rhsType->isBlockPointerType())
2092 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2093
2094 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2095 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002096 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002097 }
Chris Lattner1853da22008-01-04 23:18:45 +00002098 return Incompatible;
2099 }
2100
Chris Lattner390564e2008-04-07 06:49:41 +00002101 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002102 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002103 if (lhsType == Context.BoolTy)
2104 return Compatible;
2105
2106 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002107 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002108
Chris Lattner390564e2008-04-07 06:49:41 +00002109 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002110 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002111
2112 if (isa<BlockPointerType>(lhsType) &&
2113 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002114 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002115 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002116 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002117
Chris Lattner1853da22008-01-04 23:18:45 +00002118 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002119 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002120 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002121 }
2122 return Incompatible;
2123}
2124
Chris Lattner005ed752008-01-04 18:04:52 +00002125Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002126Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002127 if (getLangOptions().CPlusPlus) {
2128 if (!lhsType->isRecordType()) {
2129 // C++ 5.17p3: If the left operand is not of class type, the
2130 // expression is implicitly converted (C++ 4) to the
2131 // cv-unqualified type of the left operand.
Douglas Gregorbb461502008-10-24 04:54:22 +00002132 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002133 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002134 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002135 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002136 }
2137
2138 // FIXME: Currently, we fall through and treat C++ classes like C
2139 // structures.
2140 }
2141
Steve Naroffcdee22d2007-11-27 17:58:44 +00002142 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2143 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002144 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2145 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002146 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002147 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002148 return Compatible;
2149 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002150
2151 // We don't allow conversion of non-null-pointer constants to integers.
2152 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2153 return IntToBlockPointer;
2154
Chris Lattner5f505bf2007-10-16 02:55:40 +00002155 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002156 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002157 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002158 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002159 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002160 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002161 if (!lhsType->isReferenceType())
2162 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002163
Chris Lattner005ed752008-01-04 18:04:52 +00002164 Sema::AssignConvertType result =
2165 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002166
2167 // C99 6.5.16.1p2: The value of the right operand is converted to the
2168 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002169 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2170 // so that we can use references in built-in functions even in C.
2171 // The getNonReferenceType() call makes sure that the resulting expression
2172 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002173 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002174 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002175 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002176}
2177
Chris Lattner005ed752008-01-04 18:04:52 +00002178Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002179Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2180 return CheckAssignmentConstraints(lhsType, rhsType);
2181}
2182
Chris Lattner1eafdea2008-11-18 01:30:42 +00002183QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002184 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002185 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002186 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002187 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002188}
2189
Chris Lattner1eafdea2008-11-18 01:30:42 +00002190inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002191 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002192 // For conversion purposes, we ignore any qualifiers.
2193 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002194 QualType lhsType =
2195 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2196 QualType rhsType =
2197 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002198
Nate Begemanc5f0f652008-07-14 18:02:46 +00002199 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002200 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002201 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002202
Nate Begemanc5f0f652008-07-14 18:02:46 +00002203 // Handle the case of a vector & extvector type of the same size and element
2204 // type. It would be nice if we only had one vector type someday.
2205 if (getLangOptions().LaxVectorConversions)
2206 if (const VectorType *LV = lhsType->getAsVectorType())
2207 if (const VectorType *RV = rhsType->getAsVectorType())
2208 if (LV->getElementType() == RV->getElementType() &&
2209 LV->getNumElements() == RV->getNumElements())
2210 return lhsType->isExtVectorType() ? lhsType : rhsType;
2211
2212 // If the lhs is an extended vector and the rhs is a scalar of the same type
2213 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002214 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002215 QualType eltType = V->getElementType();
2216
2217 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2218 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2219 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002220 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002221 return lhsType;
2222 }
2223 }
2224
Nate Begemanc5f0f652008-07-14 18:02:46 +00002225 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002226 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002227 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002228 QualType eltType = V->getElementType();
2229
2230 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2231 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2232 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002233 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002234 return rhsType;
2235 }
2236 }
2237
Chris Lattner4b009652007-07-25 00:24:17 +00002238 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002239 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002240 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002241 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002242 return QualType();
2243}
2244
2245inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002246 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002247{
2248 QualType lhsType = lex->getType(), rhsType = rex->getType();
2249
2250 if (lhsType->isVectorType() || rhsType->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002251 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002252
Steve Naroff8f708362007-08-24 19:07:16 +00002253 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002254
Chris Lattner4b009652007-07-25 00:24:17 +00002255 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002256 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002257 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002258}
2259
2260inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002261 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002262{
2263 QualType lhsType = lex->getType(), rhsType = rex->getType();
2264
Steve Naroff8f708362007-08-24 19:07:16 +00002265 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002266
Chris Lattner4b009652007-07-25 00:24:17 +00002267 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002268 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002269 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002270}
2271
2272inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002273 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002274{
2275 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002276 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002277
Steve Naroff8f708362007-08-24 19:07:16 +00002278 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002279
Chris Lattner4b009652007-07-25 00:24:17 +00002280 // handle the common case first (both operands are arithmetic).
2281 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002282 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002283
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002284 // Put any potential pointer into PExp
2285 Expr* PExp = lex, *IExp = rex;
2286 if (IExp->getType()->isPointerType())
2287 std::swap(PExp, IExp);
2288
2289 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2290 if (IExp->getType()->isIntegerType()) {
2291 // Check for arithmetic on pointers to incomplete types
2292 if (!PTy->getPointeeType()->isObjectType()) {
2293 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002294 Diag(Loc, diag::ext_gnu_void_ptr)
2295 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002296 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002297 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002298 << lex->getType() << lex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002299 return QualType();
2300 }
2301 }
2302 return PExp->getType();
2303 }
2304 }
2305
Chris Lattner1eafdea2008-11-18 01:30:42 +00002306 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002307}
2308
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002309// C99 6.5.6
2310QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002311 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002312 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002313 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002314
Steve Naroff8f708362007-08-24 19:07:16 +00002315 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002316
Chris Lattnerf6da2912007-12-09 21:53:25 +00002317 // Enforce type constraints: C99 6.5.6p3.
2318
2319 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002320 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002321 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002322
2323 // Either ptr - int or ptr - ptr.
2324 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002325 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002326
Chris Lattnerf6da2912007-12-09 21:53:25 +00002327 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002328 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002329 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002330 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002331 Diag(Loc, diag::ext_gnu_void_ptr)
2332 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002333 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002334 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002335 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002336 return QualType();
2337 }
2338 }
2339
2340 // The result type of a pointer-int computation is the pointer type.
2341 if (rex->getType()->isIntegerType())
2342 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002343
Chris Lattnerf6da2912007-12-09 21:53:25 +00002344 // Handle pointer-pointer subtractions.
2345 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002346 QualType rpointee = RHSPTy->getPointeeType();
2347
Chris Lattnerf6da2912007-12-09 21:53:25 +00002348 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002349 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002350 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002351 if (rpointee->isVoidType()) {
2352 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002353 Diag(Loc, diag::ext_gnu_void_ptr)
2354 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002355 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002356 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002357 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002358 return QualType();
2359 }
2360 }
2361
2362 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002363 if (!Context.typesAreCompatible(
2364 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2365 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002366 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002367 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002368 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002369 return QualType();
2370 }
2371
2372 return Context.getPointerDiffType();
2373 }
2374 }
2375
Chris Lattner1eafdea2008-11-18 01:30:42 +00002376 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002377}
2378
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002379// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002380QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002381 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002382 // C99 6.5.7p2: Each of the operands shall have integer type.
2383 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002384 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002385
Chris Lattner2c8bff72007-12-12 05:47:28 +00002386 // Shifts don't perform usual arithmetic conversions, they just do integer
2387 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002388 if (!isCompAssign)
2389 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002390 UsualUnaryConversions(rex);
2391
2392 // "The type of the result is that of the promoted left operand."
2393 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002394}
2395
Eli Friedman0d9549b2008-08-22 00:56:42 +00002396static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2397 ASTContext& Context) {
2398 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2399 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2400 // ID acts sort of like void* for ObjC interfaces
2401 if (LHSIface && Context.isObjCIdType(RHS))
2402 return true;
2403 if (RHSIface && Context.isObjCIdType(LHS))
2404 return true;
2405 if (!LHSIface || !RHSIface)
2406 return false;
2407 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2408 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2409}
2410
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002411// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002412QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002413 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002414 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002415 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002416
Chris Lattner254f3bc2007-08-26 01:18:55 +00002417 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002418 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2419 UsualArithmeticConversions(lex, rex);
2420 else {
2421 UsualUnaryConversions(lex);
2422 UsualUnaryConversions(rex);
2423 }
Chris Lattner4b009652007-07-25 00:24:17 +00002424 QualType lType = lex->getType();
2425 QualType rType = rex->getType();
2426
Ted Kremenek486509e2007-10-29 17:13:39 +00002427 // For non-floating point types, check for self-comparisons of the form
2428 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2429 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002430 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002431 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2432 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002433 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002434 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002435 }
2436
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002437 // The result of comparisons is 'bool' in C++, 'int' in C.
2438 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2439
Chris Lattner254f3bc2007-08-26 01:18:55 +00002440 if (isRelational) {
2441 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002442 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002443 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002444 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002445 if (lType->isFloatingType()) {
2446 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002447 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002448 }
2449
Chris Lattner254f3bc2007-08-26 01:18:55 +00002450 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002451 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002452 }
Chris Lattner4b009652007-07-25 00:24:17 +00002453
Chris Lattner22be8422007-08-26 01:10:14 +00002454 bool LHSIsNull = lex->isNullPointerConstant(Context);
2455 bool RHSIsNull = rex->isNullPointerConstant(Context);
2456
Chris Lattner254f3bc2007-08-26 01:18:55 +00002457 // All of the following pointer related warnings are GCC extensions, except
2458 // when handling null pointer constants. One day, we can consider making them
2459 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002460 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002461 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002462 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002463 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002464 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002465
Steve Naroff3b435622007-11-13 14:57:38 +00002466 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002467 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2468 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002469 RCanPointeeTy.getUnqualifiedType()) &&
2470 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002471 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002472 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002473 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002474 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002475 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002476 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002477 // Handle block pointer types.
2478 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2479 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2480 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2481
2482 if (!LHSIsNull && !RHSIsNull &&
2483 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002484 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002485 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002486 }
2487 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002488 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002489 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002490 // Allow block pointers to be compared with null pointer constants.
2491 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2492 (lType->isPointerType() && rType->isBlockPointerType())) {
2493 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002494 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002495 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002496 }
2497 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002498 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002499 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002500
Steve Naroff936c4362008-06-03 14:04:54 +00002501 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002502 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002503 const PointerType *LPT = lType->getAsPointerType();
2504 const PointerType *RPT = rType->getAsPointerType();
2505 bool LPtrToVoid = LPT ?
2506 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2507 bool RPtrToVoid = RPT ?
2508 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2509
2510 if (!LPtrToVoid && !RPtrToVoid &&
2511 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002512 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002513 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002514 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002515 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002516 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002517 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002518 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002519 }
Steve Naroff936c4362008-06-03 14:04:54 +00002520 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2521 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002522 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002523 } else {
2524 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002525 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002526 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002527 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002528 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002529 }
Steve Naroff936c4362008-06-03 14:04:54 +00002530 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002531 }
Steve Naroff936c4362008-06-03 14:04:54 +00002532 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2533 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002534 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002535 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002536 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002537 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002538 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002539 }
Steve Naroff936c4362008-06-03 14:04:54 +00002540 if (lType->isIntegerType() &&
2541 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002542 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002543 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002544 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002545 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002546 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002547 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002548 // Handle block pointers.
2549 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2550 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002551 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002552 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002553 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002554 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002555 }
2556 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2557 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002558 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002559 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002560 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002561 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002562 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002563 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002564}
2565
Nate Begemanc5f0f652008-07-14 18:02:46 +00002566/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2567/// operates on extended vector types. Instead of producing an IntTy result,
2568/// like a scalar comparison, a vector comparison produces a vector of integer
2569/// types.
2570QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002571 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002572 bool isRelational) {
2573 // Check to make sure we're operating on vectors of the same type and width,
2574 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002575 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002576 if (vType.isNull())
2577 return vType;
2578
2579 QualType lType = lex->getType();
2580 QualType rType = rex->getType();
2581
2582 // For non-floating point types, check for self-comparisons of the form
2583 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2584 // often indicate logic errors in the program.
2585 if (!lType->isFloatingType()) {
2586 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2587 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2588 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002589 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002590 }
2591
2592 // Check for comparisons of floating point operands using != and ==.
2593 if (!isRelational && lType->isFloatingType()) {
2594 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002595 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002596 }
2597
2598 // Return the type for the comparison, which is the same as vector type for
2599 // integer vectors, or an integer type of identical size and number of
2600 // elements for floating point vectors.
2601 if (lType->isIntegerType())
2602 return lType;
2603
2604 const VectorType *VTy = lType->getAsVectorType();
2605
2606 // FIXME: need to deal with non-32b int / non-64b long long
2607 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2608 if (TypeSize == 32) {
2609 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2610 }
2611 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2612 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2613}
2614
Chris Lattner4b009652007-07-25 00:24:17 +00002615inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002616 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002617{
2618 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002619 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002620
Steve Naroff8f708362007-08-24 19:07:16 +00002621 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002622
2623 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002624 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002625 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002626}
2627
2628inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00002629 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00002630{
2631 UsualUnaryConversions(lex);
2632 UsualUnaryConversions(rex);
2633
Eli Friedmanbea3f842008-05-13 20:16:47 +00002634 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002635 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002636 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002637}
2638
Chris Lattner4c2642c2008-11-18 01:22:49 +00002639/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2640/// emit an error and return true. If so, return false.
2641static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2642 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2643 if (IsLV == Expr::MLV_Valid)
2644 return false;
2645
2646 unsigned Diag = 0;
2647 bool NeedType = false;
2648 switch (IsLV) { // C99 6.5.16p2
2649 default: assert(0 && "Unknown result from isModifiableLvalue!");
2650 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00002651 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002652 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2653 NeedType = true;
2654 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002655 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002656 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2657 NeedType = true;
2658 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00002659 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002660 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2661 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002662 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002663 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2664 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002665 case Expr::MLV_IncompleteType:
2666 case Expr::MLV_IncompleteVoidType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002667 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2668 NeedType = true;
2669 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002670 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002671 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2672 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00002673 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002674 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2675 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00002676 case Expr::MLV_ReadonlyProperty:
2677 Diag = diag::error_readonly_property_assignment;
2678 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00002679 case Expr::MLV_NoSetterProperty:
2680 Diag = diag::error_nosetter_property_assignment;
2681 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002682 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002683
Chris Lattner4c2642c2008-11-18 01:22:49 +00002684 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002685 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002686 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00002687 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002688 return true;
2689}
2690
2691
2692
2693// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00002694QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
2695 SourceLocation Loc,
2696 QualType CompoundType) {
2697 // Verify that LHS is a modifiable lvalue, and emit error if not.
2698 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00002699 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00002700
2701 QualType LHSType = LHS->getType();
2702 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00002703
Chris Lattner005ed752008-01-04 18:04:52 +00002704 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002705 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00002706 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002707 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner34c85082008-08-21 18:04:13 +00002708
2709 // If the RHS is a unary plus or minus, check to see if they = and + are
2710 // right next to each other. If so, the user may have typo'd "x =+ 4"
2711 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002712 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00002713 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2714 RHSCheck = ICE->getSubExpr();
2715 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2716 if ((UO->getOpcode() == UnaryOperator::Plus ||
2717 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00002718 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00002719 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002720 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00002721 Diag(Loc, diag::warn_not_compound_assign)
2722 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
2723 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00002724 }
2725 } else {
2726 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00002727 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00002728 }
Chris Lattner005ed752008-01-04 18:04:52 +00002729
Chris Lattner1eafdea2008-11-18 01:30:42 +00002730 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
2731 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00002732 return QualType();
2733
Chris Lattner4b009652007-07-25 00:24:17 +00002734 // C99 6.5.16p3: The type of an assignment expression is the type of the
2735 // left operand unless the left operand has qualified type, in which case
2736 // it is the unqualified version of the type of the left operand.
2737 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2738 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002739 // C++ 5.17p1: the type of the assignment expression is that of its left
2740 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002741 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002742}
2743
Chris Lattner1eafdea2008-11-18 01:30:42 +00002744// C99 6.5.17
2745QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
2746 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00002747
2748 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002749 DefaultFunctionArrayConversion(RHS);
2750 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002751}
2752
2753/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2754/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Chris Lattnere65182c2008-11-21 07:05:48 +00002755QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc) {
2756 QualType ResType = Op->getType();
2757 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002758
Steve Naroffd30e1932007-08-24 17:20:07 +00002759 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattnere65182c2008-11-21 07:05:48 +00002760 if (ResType->isRealType()) {
2761 // OK!
2762 } else if (const PointerType *PT = ResType->getAsPointerType()) {
2763 // C99 6.5.2.4p2, 6.5.6p2
2764 if (PT->getPointeeType()->isObjectType()) {
2765 // Pointer to object is ok!
2766 } else if (PT->getPointeeType()->isVoidType()) {
2767 // Pointer to void is extension.
2768 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
2769 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +00002770 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002771 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002772 return QualType();
2773 }
Chris Lattnere65182c2008-11-21 07:05:48 +00002774 } else if (ResType->isComplexType()) {
2775 // C99 does not support ++/-- on complex types, we allow as an extension.
2776 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002777 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002778 } else {
2779 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002780 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002781 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002782 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002783 // At this point, we know we have a real, complex or pointer type.
2784 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00002785 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00002786 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00002787 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00002788}
2789
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002790/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002791/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002792/// where the declaration is needed for type checking. We only need to
2793/// handle cases when the expression references a function designator
2794/// or is an lvalue. Here are some examples:
2795/// - &(x) => x
2796/// - &*****f => f for f a function designator.
2797/// - &s.xx => s
2798/// - &s.zz[1].yy -> s, if zz is an array
2799/// - *(x + 1) -> x, if x is an array
2800/// - &"123"[2] -> 0
2801/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002802static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002803 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002804 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002805 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002806 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002807 // Fields cannot be declared with a 'register' storage class.
2808 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002809 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002810 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002811 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002812 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002813 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002814
Douglas Gregord2baafd2008-10-21 16:13:35 +00002815 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002816 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002817 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002818 return 0;
2819 else
2820 return VD;
2821 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002822 case Stmt::UnaryOperatorClass: {
2823 UnaryOperator *UO = cast<UnaryOperator>(E);
2824
2825 switch(UO->getOpcode()) {
2826 case UnaryOperator::Deref: {
2827 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002828 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2829 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2830 if (!VD || VD->getType()->isPointerType())
2831 return 0;
2832 return VD;
2833 }
2834 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002835 }
2836 case UnaryOperator::Real:
2837 case UnaryOperator::Imag:
2838 case UnaryOperator::Extension:
2839 return getPrimaryDecl(UO->getSubExpr());
2840 default:
2841 return 0;
2842 }
2843 }
2844 case Stmt::BinaryOperatorClass: {
2845 BinaryOperator *BO = cast<BinaryOperator>(E);
2846
2847 // Handle cases involving pointer arithmetic. The result of an
2848 // Assign or AddAssign is not an lvalue so they can be ignored.
2849
2850 // (x + n) or (n + x) => x
2851 if (BO->getOpcode() == BinaryOperator::Add) {
2852 if (BO->getLHS()->getType()->isPointerType()) {
2853 return getPrimaryDecl(BO->getLHS());
2854 } else if (BO->getRHS()->getType()->isPointerType()) {
2855 return getPrimaryDecl(BO->getRHS());
2856 }
2857 }
2858
2859 return 0;
2860 }
Chris Lattner4b009652007-07-25 00:24:17 +00002861 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002862 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002863 case Stmt::ImplicitCastExprClass:
2864 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002865 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002866 default:
2867 return 0;
2868 }
2869}
2870
2871/// CheckAddressOfOperand - The operand of & must be either a function
2872/// designator or an lvalue designating an object. If it is an lvalue, the
2873/// object cannot be declared with storage class register or be a bit field.
2874/// Note: The usual conversions are *not* applied to the operand of the &
2875/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00002876/// In C++, the operand might be an overloaded function name, in which case
2877/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00002878QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002879 if (getLangOptions().C99) {
2880 // Implement C99-only parts of addressof rules.
2881 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2882 if (uOp->getOpcode() == UnaryOperator::Deref)
2883 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2884 // (assuming the deref expression is valid).
2885 return uOp->getSubExpr()->getType();
2886 }
2887 // Technically, there should be a check for array subscript
2888 // expressions here, but the result of one is always an lvalue anyway.
2889 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002890 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002891 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopesdf239522008-12-16 22:58:26 +00002892 printf("oleee\n");
Chris Lattner4b009652007-07-25 00:24:17 +00002893 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002894 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2895 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00002896 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
2897 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002898 return QualType();
2899 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002900 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2901 if (MemExpr->getMemberDecl()->isBitField()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002902 Diag(OpLoc, diag::err_typecheck_address_of)
2903 << "bit-field" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00002904 return QualType();
2905 }
2906 // Check for Apple extension for accessing vector components.
2907 } else if (isa<ArraySubscriptExpr>(op) &&
2908 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002909 Diag(OpLoc, diag::err_typecheck_address_of)
2910 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00002911 return QualType();
2912 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002913 // We have an lvalue with a decl. Make sure the decl is not declared
2914 // with the register storage-class specifier.
2915 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2916 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002917 Diag(OpLoc, diag::err_typecheck_address_of)
2918 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002919 return QualType();
2920 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00002921 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00002922 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00002923 } else if (isa<FieldDecl>(dcl)) {
2924 // Okay: we can take the address of a field.
Nuno Lopesdf239522008-12-16 22:58:26 +00002925 } else if (isa<FunctionDecl>(dcl)) {
2926 // Okay: we can take the address of a function.
Douglas Gregor5b82d612008-12-10 21:26:49 +00002927 }
Nuno Lopesdf239522008-12-16 22:58:26 +00002928 else
Chris Lattner4b009652007-07-25 00:24:17 +00002929 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002930 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002931
Chris Lattner4b009652007-07-25 00:24:17 +00002932 // If the operand has type "type", the result has type "pointer to type".
2933 return Context.getPointerType(op->getType());
2934}
2935
Chris Lattnerda5c0872008-11-23 09:13:29 +00002936QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
2937 UsualUnaryConversions(Op);
2938 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002939
Chris Lattnerda5c0872008-11-23 09:13:29 +00002940 // Note that per both C89 and C99, this is always legal, even if ptype is an
2941 // incomplete type or void. It would be possible to warn about dereferencing
2942 // a void pointer, but it's completely well-defined, and such a warning is
2943 // unlikely to catch any mistakes.
2944 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00002945 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00002946
Chris Lattner77d52da2008-11-20 06:06:08 +00002947 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002948 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002949 return QualType();
2950}
2951
2952static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2953 tok::TokenKind Kind) {
2954 BinaryOperator::Opcode Opc;
2955 switch (Kind) {
2956 default: assert(0 && "Unknown binop!");
2957 case tok::star: Opc = BinaryOperator::Mul; break;
2958 case tok::slash: Opc = BinaryOperator::Div; break;
2959 case tok::percent: Opc = BinaryOperator::Rem; break;
2960 case tok::plus: Opc = BinaryOperator::Add; break;
2961 case tok::minus: Opc = BinaryOperator::Sub; break;
2962 case tok::lessless: Opc = BinaryOperator::Shl; break;
2963 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2964 case tok::lessequal: Opc = BinaryOperator::LE; break;
2965 case tok::less: Opc = BinaryOperator::LT; break;
2966 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2967 case tok::greater: Opc = BinaryOperator::GT; break;
2968 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2969 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2970 case tok::amp: Opc = BinaryOperator::And; break;
2971 case tok::caret: Opc = BinaryOperator::Xor; break;
2972 case tok::pipe: Opc = BinaryOperator::Or; break;
2973 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2974 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2975 case tok::equal: Opc = BinaryOperator::Assign; break;
2976 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2977 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2978 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2979 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2980 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2981 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2982 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2983 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2984 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2985 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2986 case tok::comma: Opc = BinaryOperator::Comma; break;
2987 }
2988 return Opc;
2989}
2990
2991static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2992 tok::TokenKind Kind) {
2993 UnaryOperator::Opcode Opc;
2994 switch (Kind) {
2995 default: assert(0 && "Unknown unary op!");
2996 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2997 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2998 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2999 case tok::star: Opc = UnaryOperator::Deref; break;
3000 case tok::plus: Opc = UnaryOperator::Plus; break;
3001 case tok::minus: Opc = UnaryOperator::Minus; break;
3002 case tok::tilde: Opc = UnaryOperator::Not; break;
3003 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003004 case tok::kw___real: Opc = UnaryOperator::Real; break;
3005 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3006 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3007 }
3008 return Opc;
3009}
3010
Douglas Gregord7f915e2008-11-06 23:29:22 +00003011/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3012/// operator @p Opc at location @c TokLoc. This routine only supports
3013/// built-in operations; ActOnBinOp handles overloaded operators.
3014Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3015 unsigned Op,
3016 Expr *lhs, Expr *rhs) {
3017 QualType ResultTy; // Result type of the binary operator.
3018 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3019 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3020
3021 switch (Opc) {
3022 default:
3023 assert(0 && "Unknown binary expr!");
3024 case BinaryOperator::Assign:
3025 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3026 break;
3027 case BinaryOperator::Mul:
3028 case BinaryOperator::Div:
3029 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3030 break;
3031 case BinaryOperator::Rem:
3032 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3033 break;
3034 case BinaryOperator::Add:
3035 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3036 break;
3037 case BinaryOperator::Sub:
3038 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3039 break;
3040 case BinaryOperator::Shl:
3041 case BinaryOperator::Shr:
3042 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3043 break;
3044 case BinaryOperator::LE:
3045 case BinaryOperator::LT:
3046 case BinaryOperator::GE:
3047 case BinaryOperator::GT:
3048 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3049 break;
3050 case BinaryOperator::EQ:
3051 case BinaryOperator::NE:
3052 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3053 break;
3054 case BinaryOperator::And:
3055 case BinaryOperator::Xor:
3056 case BinaryOperator::Or:
3057 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3058 break;
3059 case BinaryOperator::LAnd:
3060 case BinaryOperator::LOr:
3061 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3062 break;
3063 case BinaryOperator::MulAssign:
3064 case BinaryOperator::DivAssign:
3065 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3066 if (!CompTy.isNull())
3067 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3068 break;
3069 case BinaryOperator::RemAssign:
3070 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3071 if (!CompTy.isNull())
3072 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3073 break;
3074 case BinaryOperator::AddAssign:
3075 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3076 if (!CompTy.isNull())
3077 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3078 break;
3079 case BinaryOperator::SubAssign:
3080 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3081 if (!CompTy.isNull())
3082 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3083 break;
3084 case BinaryOperator::ShlAssign:
3085 case BinaryOperator::ShrAssign:
3086 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3087 if (!CompTy.isNull())
3088 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3089 break;
3090 case BinaryOperator::AndAssign:
3091 case BinaryOperator::XorAssign:
3092 case BinaryOperator::OrAssign:
3093 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3094 if (!CompTy.isNull())
3095 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3096 break;
3097 case BinaryOperator::Comma:
3098 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3099 break;
3100 }
3101 if (ResultTy.isNull())
3102 return true;
3103 if (CompTy.isNull())
3104 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
3105 else
3106 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
3107}
3108
Chris Lattner4b009652007-07-25 00:24:17 +00003109// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003110Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3111 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00003112 ExprTy *LHS, ExprTy *RHS) {
3113 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3114 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
3115
Steve Naroff87d58b42007-09-16 03:34:24 +00003116 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3117 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003118
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003119 // If either expression is type-dependent, just build the AST.
3120 // FIXME: We'll need to perform some caching of the result of name
3121 // lookup for operator+.
3122 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3123 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3124 return new CompoundAssignOperator(lhs, rhs, Opc, Context.DependentTy,
3125 Context.DependentTy, TokLoc);
3126 else
3127 return new BinaryOperator(lhs, rhs, Opc, Context.DependentTy, TokLoc);
3128 }
3129
Douglas Gregord7f915e2008-11-06 23:29:22 +00003130 if (getLangOptions().CPlusPlus &&
3131 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3132 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003133 // If this is one of the assignment operators, we only perform
3134 // overload resolution if the left-hand side is a class or
3135 // enumeration type (C++ [expr.ass]p3).
3136 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3137 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3138 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3139 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003140
3141 // Determine which overloaded operator we're dealing with.
3142 static const OverloadedOperatorKind OverOps[] = {
3143 OO_Star, OO_Slash, OO_Percent,
3144 OO_Plus, OO_Minus,
3145 OO_LessLess, OO_GreaterGreater,
3146 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3147 OO_EqualEqual, OO_ExclaimEqual,
3148 OO_Amp,
3149 OO_Caret,
3150 OO_Pipe,
3151 OO_AmpAmp,
3152 OO_PipePipe,
3153 OO_Equal, OO_StarEqual,
3154 OO_SlashEqual, OO_PercentEqual,
3155 OO_PlusEqual, OO_MinusEqual,
3156 OO_LessLessEqual, OO_GreaterGreaterEqual,
3157 OO_AmpEqual, OO_CaretEqual,
3158 OO_PipeEqual,
3159 OO_Comma
3160 };
3161 OverloadedOperatorKind OverOp = OverOps[Opc];
3162
Douglas Gregor5ed15042008-11-18 23:14:02 +00003163 // Add the appropriate overloaded operators (C++ [over.match.oper])
3164 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003165 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003166 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003167 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003168
3169 // Perform overload resolution.
3170 OverloadCandidateSet::iterator Best;
3171 switch (BestViableFunction(CandidateSet, Best)) {
3172 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003173 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003174 FunctionDecl *FnDecl = Best->Function;
3175
Douglas Gregor70d26122008-11-12 17:17:38 +00003176 if (FnDecl) {
3177 // We matched an overloaded operator. Build a call to that
3178 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003179
Douglas Gregor70d26122008-11-12 17:17:38 +00003180 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003181 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3182 if (PerformObjectArgumentInitialization(lhs, Method) ||
3183 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3184 "passing"))
3185 return true;
3186 } else {
3187 // Convert the arguments.
3188 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3189 "passing") ||
3190 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3191 "passing"))
3192 return true;
3193 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003194
Douglas Gregor70d26122008-11-12 17:17:38 +00003195 // Determine the result type
3196 QualType ResultTy
3197 = FnDecl->getType()->getAsFunctionType()->getResultType();
3198 ResultTy = ResultTy.getNonReferenceType();
3199
3200 // Build the actual expression node.
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003201 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3202 SourceLocation());
3203 UsualUnaryConversions(FnExpr);
3204
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003205 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregor70d26122008-11-12 17:17:38 +00003206 } else {
3207 // We matched a built-in operator. Convert the arguments, then
3208 // break out so that we will build the appropriate built-in
3209 // operator node.
3210 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
3211 "passing") ||
3212 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
3213 "passing"))
3214 return true;
3215
3216 break;
3217 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003218 }
3219
3220 case OR_No_Viable_Function:
3221 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003222 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003223 break;
3224
3225 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003226 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3227 << BinaryOperator::getOpcodeStr(Opc)
3228 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003229 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3230 return true;
3231 }
3232
Douglas Gregor70d26122008-11-12 17:17:38 +00003233 // Either we found no viable overloaded operator or we matched a
3234 // built-in operator. In either case, fall through to trying to
3235 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003236 }
Chris Lattner4b009652007-07-25 00:24:17 +00003237
Douglas Gregord7f915e2008-11-06 23:29:22 +00003238 // Build a built-in binary operation.
3239 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003240}
3241
3242// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003243Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3244 tok::TokenKind Op, ExprTy *input) {
Chris Lattner4b009652007-07-25 00:24:17 +00003245 Expr *Input = (Expr*)input;
3246 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003247
3248 if (getLangOptions().CPlusPlus &&
3249 (Input->getType()->isRecordType()
3250 || Input->getType()->isEnumeralType())) {
3251 // Determine which overloaded operator we're dealing with.
3252 static const OverloadedOperatorKind OverOps[] = {
3253 OO_None, OO_None,
3254 OO_PlusPlus, OO_MinusMinus,
3255 OO_Amp, OO_Star,
3256 OO_Plus, OO_Minus,
3257 OO_Tilde, OO_Exclaim,
3258 OO_None, OO_None,
3259 OO_None,
3260 OO_None
3261 };
3262 OverloadedOperatorKind OverOp = OverOps[Opc];
3263
3264 // Add the appropriate overloaded operators (C++ [over.match.oper])
3265 // to the candidate set.
3266 OverloadCandidateSet CandidateSet;
3267 if (OverOp != OO_None)
3268 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3269
3270 // Perform overload resolution.
3271 OverloadCandidateSet::iterator Best;
3272 switch (BestViableFunction(CandidateSet, Best)) {
3273 case OR_Success: {
3274 // We found a built-in operator or an overloaded operator.
3275 FunctionDecl *FnDecl = Best->Function;
3276
3277 if (FnDecl) {
3278 // We matched an overloaded operator. Build a call to that
3279 // operator.
3280
3281 // Convert the arguments.
3282 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3283 if (PerformObjectArgumentInitialization(Input, Method))
3284 return true;
3285 } else {
3286 // Convert the arguments.
3287 if (PerformCopyInitialization(Input,
3288 FnDecl->getParamDecl(0)->getType(),
3289 "passing"))
3290 return true;
3291 }
3292
3293 // Determine the result type
3294 QualType ResultTy
3295 = FnDecl->getType()->getAsFunctionType()->getResultType();
3296 ResultTy = ResultTy.getNonReferenceType();
3297
3298 // Build the actual expression node.
3299 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3300 SourceLocation());
3301 UsualUnaryConversions(FnExpr);
3302
3303 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3304 } else {
3305 // We matched a built-in operator. Convert the arguments, then
3306 // break out so that we will build the appropriate built-in
3307 // operator node.
3308 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0],
3309 "passing"))
3310 return true;
3311
3312 break;
3313 }
3314 }
3315
3316 case OR_No_Viable_Function:
3317 // No viable function; fall through to handling this as a
3318 // built-in operator, which will produce an error message for us.
3319 break;
3320
3321 case OR_Ambiguous:
3322 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3323 << UnaryOperator::getOpcodeStr(Opc)
3324 << Input->getSourceRange();
3325 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3326 return true;
3327 }
3328
3329 // Either we found no viable overloaded operator or we matched a
3330 // built-in operator. In either case, fall through to trying to
3331 // build a built-in operation.
3332 }
3333
Chris Lattner4b009652007-07-25 00:24:17 +00003334 QualType resultType;
3335 switch (Opc) {
3336 default:
3337 assert(0 && "Unimplemented unary expr!");
3338 case UnaryOperator::PreInc:
3339 case UnaryOperator::PreDec:
3340 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
3341 break;
3342 case UnaryOperator::AddrOf:
3343 resultType = CheckAddressOfOperand(Input, OpLoc);
3344 break;
3345 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003346 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003347 resultType = CheckIndirectionOperand(Input, OpLoc);
3348 break;
3349 case UnaryOperator::Plus:
3350 case UnaryOperator::Minus:
3351 UsualUnaryConversions(Input);
3352 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003353 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3354 break;
3355 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3356 resultType->isEnumeralType())
3357 break;
3358 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3359 Opc == UnaryOperator::Plus &&
3360 resultType->isPointerType())
3361 break;
3362
Chris Lattner77d52da2008-11-20 06:06:08 +00003363 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003364 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003365 case UnaryOperator::Not: // bitwise complement
3366 UsualUnaryConversions(Input);
3367 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003368 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3369 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3370 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003371 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003372 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003373 else if (!resultType->isIntegerType())
Chris Lattner77d52da2008-11-20 06:06:08 +00003374 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003375 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003376 break;
3377 case UnaryOperator::LNot: // logical negation
3378 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3379 DefaultFunctionArrayConversion(Input);
3380 resultType = Input->getType();
3381 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattner77d52da2008-11-20 06:06:08 +00003382 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003383 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003384 // LNot always has type int. C99 6.5.3.3p5.
3385 resultType = Context.IntTy;
3386 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003387 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003388 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003389 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003390 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003391 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003392 resultType = Input->getType();
3393 break;
3394 }
3395 if (resultType.isNull())
3396 return true;
3397 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3398}
3399
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003400/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3401Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003402 SourceLocation LabLoc,
3403 IdentifierInfo *LabelII) {
3404 // Look up the record for this label identifier.
3405 LabelStmt *&LabelDecl = LabelMap[LabelII];
3406
Daniel Dunbar879788d2008-08-04 16:51:22 +00003407 // If we haven't seen this label yet, create a forward reference. It
3408 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003409 if (LabelDecl == 0)
3410 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3411
3412 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003413 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3414 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003415}
3416
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003417Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003418 SourceLocation RPLoc) { // "({..})"
3419 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3420 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3421 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3422
3423 // FIXME: there are a variety of strange constraints to enforce here, for
3424 // example, it is not possible to goto into a stmt expression apparently.
3425 // More semantic analysis is needed.
3426
3427 // FIXME: the last statement in the compount stmt has its value used. We
3428 // should not warn about it being unused.
3429
3430 // If there are sub stmts in the compound stmt, take the type of the last one
3431 // as the type of the stmtexpr.
3432 QualType Ty = Context.VoidTy;
3433
Chris Lattner200964f2008-07-26 19:51:01 +00003434 if (!Compound->body_empty()) {
3435 Stmt *LastStmt = Compound->body_back();
3436 // If LastStmt is a label, skip down through into the body.
3437 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3438 LastStmt = Label->getSubStmt();
3439
3440 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003441 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003442 }
Chris Lattner4b009652007-07-25 00:24:17 +00003443
3444 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3445}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003446
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003447Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003448 SourceLocation TypeLoc,
3449 TypeTy *argty,
3450 OffsetOfComponent *CompPtr,
3451 unsigned NumComponents,
3452 SourceLocation RPLoc) {
3453 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3454 assert(!ArgTy.isNull() && "Missing type argument!");
3455
3456 // We must have at least one component that refers to the type, and the first
3457 // one is known to be a field designator. Verify that the ArgTy represents
3458 // a struct/union/class.
3459 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003460 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003461
3462 // Otherwise, create a compound literal expression as the base, and
3463 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003464 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003465
Chris Lattnerb37522e2007-08-31 21:49:13 +00003466 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3467 // GCC extension, diagnose them.
3468 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003469 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3470 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003471
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003472 for (unsigned i = 0; i != NumComponents; ++i) {
3473 const OffsetOfComponent &OC = CompPtr[i];
3474 if (OC.isBrackets) {
3475 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003476 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003477 if (!AT) {
3478 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003479 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003480 }
3481
Chris Lattner2af6a802007-08-30 17:59:59 +00003482 // FIXME: C++: Verify that operator[] isn't overloaded.
3483
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003484 // C99 6.5.2.1p1
3485 Expr *Idx = static_cast<Expr*>(OC.U.E);
3486 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003487 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3488 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003489
3490 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3491 continue;
3492 }
3493
3494 const RecordType *RC = Res->getType()->getAsRecordType();
3495 if (!RC) {
3496 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003497 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003498 }
3499
3500 // Get the decl corresponding to this.
3501 RecordDecl *RD = RC->getDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00003502 FieldDecl *MemberDecl = 0;
3503 DeclContext::lookup_result Lookup = RD->lookup(Context, OC.U.IdentInfo);
3504 if (Lookup.first != Lookup.second)
3505 MemberDecl = dyn_cast<FieldDecl>(*Lookup.first);
3506
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003507 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003508 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3509 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003510
3511 // FIXME: C++: Verify that MemberDecl isn't a static field.
3512 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003513 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3514 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003515 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3516 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003517 }
3518
3519 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3520 BuiltinLoc);
3521}
3522
3523
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003524Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003525 TypeTy *arg1, TypeTy *arg2,
3526 SourceLocation RPLoc) {
3527 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3528 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3529
3530 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3531
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003532 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003533}
3534
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003535Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003536 ExprTy *expr1, ExprTy *expr2,
3537 SourceLocation RPLoc) {
3538 Expr *CondExpr = static_cast<Expr*>(cond);
3539 Expr *LHSExpr = static_cast<Expr*>(expr1);
3540 Expr *RHSExpr = static_cast<Expr*>(expr2);
3541
3542 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3543
3544 // The conditional expression is required to be a constant expression.
3545 llvm::APSInt condEval(32);
3546 SourceLocation ExpLoc;
3547 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003548 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3549 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00003550
3551 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3552 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3553 RHSExpr->getType();
3554 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3555}
3556
Steve Naroff52a81c02008-09-03 18:15:37 +00003557//===----------------------------------------------------------------------===//
3558// Clang Extensions.
3559//===----------------------------------------------------------------------===//
3560
3561/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003562void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003563 // Analyze block parameters.
3564 BlockSemaInfo *BSI = new BlockSemaInfo();
3565
3566 // Add BSI to CurBlock.
3567 BSI->PrevBlockInfo = CurBlock;
3568 CurBlock = BSI;
3569
3570 BSI->ReturnType = 0;
3571 BSI->TheScope = BlockScope;
3572
Steve Naroff52059382008-10-10 01:28:17 +00003573 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003574 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00003575}
3576
3577void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003578 // Analyze arguments to block.
3579 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3580 "Not a function declarator!");
3581 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3582
Steve Naroff52059382008-10-10 01:28:17 +00003583 CurBlock->hasPrototype = FTI.hasPrototype;
3584 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003585
3586 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3587 // no arguments, not a function that takes a single void argument.
3588 if (FTI.hasPrototype &&
3589 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3590 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3591 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3592 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003593 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003594 } else if (FTI.hasPrototype) {
3595 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003596 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3597 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003598 }
Steve Naroff52059382008-10-10 01:28:17 +00003599 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3600
3601 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3602 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3603 // If this has an identifier, add it to the scope stack.
3604 if ((*AI)->getIdentifier())
3605 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003606}
3607
3608/// ActOnBlockError - If there is an error parsing a block, this callback
3609/// is invoked to pop the information about the block from the action impl.
3610void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3611 // Ensure that CurBlock is deleted.
3612 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3613
3614 // Pop off CurBlock, handle nested blocks.
3615 CurBlock = CurBlock->PrevBlockInfo;
3616
3617 // FIXME: Delete the ParmVarDecl objects as well???
3618
3619}
3620
3621/// ActOnBlockStmtExpr - This is called when the body of a block statement
3622/// literal was successfully completed. ^(int x){...}
3623Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3624 Scope *CurScope) {
3625 // Ensure that CurBlock is deleted.
3626 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3627 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3628
Steve Naroff52059382008-10-10 01:28:17 +00003629 PopDeclContext();
3630
Steve Naroff52a81c02008-09-03 18:15:37 +00003631 // Pop off CurBlock, handle nested blocks.
3632 CurBlock = CurBlock->PrevBlockInfo;
3633
3634 QualType RetTy = Context.VoidTy;
3635 if (BSI->ReturnType)
3636 RetTy = QualType(BSI->ReturnType, 0);
3637
3638 llvm::SmallVector<QualType, 8> ArgTypes;
3639 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3640 ArgTypes.push_back(BSI->Params[i]->getType());
3641
3642 QualType BlockTy;
3643 if (!BSI->hasPrototype)
3644 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3645 else
3646 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003647 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003648
3649 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003650
Steve Naroff95029d92008-10-08 18:44:00 +00003651 BSI->TheDecl->setBody(Body.take());
3652 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003653}
3654
Nate Begemanbd881ef2008-01-30 20:50:20 +00003655/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003656/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003657/// The number of arguments has already been validated to match the number of
3658/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003659static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3660 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003661 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003662 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003663 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3664 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003665
3666 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003667 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003668 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003669 return true;
3670}
3671
3672Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3673 SourceLocation *CommaLocs,
3674 SourceLocation BuiltinLoc,
3675 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003676 // __builtin_overload requires at least 2 arguments
3677 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003678 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3679 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003680
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003681 // The first argument is required to be a constant expression. It tells us
3682 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003683 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003684 Expr *NParamsExpr = Args[0];
3685 llvm::APSInt constEval(32);
3686 SourceLocation ExpLoc;
3687 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003688 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3689 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003690
3691 // Verify that the number of parameters is > 0
3692 unsigned NumParams = constEval.getZExtValue();
3693 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003694 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3695 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003696 // Verify that we have at least 1 + NumParams arguments to the builtin.
3697 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003698 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3699 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003700
3701 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003702 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003703 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003704 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3705 // UsualUnaryConversions will convert the function DeclRefExpr into a
3706 // pointer to function.
3707 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003708 const FunctionTypeProto *FnType = 0;
3709 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3710 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003711
3712 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3713 // parameters, and the number of parameters must match the value passed to
3714 // the builtin.
3715 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003716 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
3717 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003718
3719 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003720 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003721 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003722 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003723 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003724 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
3725 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00003726 // Remember our match, and continue processing the remaining arguments
3727 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003728 OE = new OverloadExpr(Args, NumArgs, i,
3729 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003730 BuiltinLoc, RParenLoc);
3731 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003732 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003733 // Return the newly created OverloadExpr node, if we succeded in matching
3734 // exactly one of the candidate functions.
3735 if (OE)
3736 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003737
3738 // If we didn't find a matching function Expr in the __builtin_overload list
3739 // the return an error.
3740 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003741 for (unsigned i = 0; i != NumParams; ++i) {
3742 if (i != 0) typeNames += ", ";
3743 typeNames += Args[i+1]->getType().getAsString();
3744 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003745
Chris Lattner77d52da2008-11-20 06:06:08 +00003746 return Diag(BuiltinLoc, diag::err_overload_no_match)
3747 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003748}
3749
Anders Carlsson36760332007-10-15 20:28:48 +00003750Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3751 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003752 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003753 Expr *E = static_cast<Expr*>(expr);
3754 QualType T = QualType::getFromOpaquePtr(type);
3755
3756 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003757
3758 // Get the va_list type
3759 QualType VaListType = Context.getBuiltinVaListType();
3760 // Deal with implicit array decay; for example, on x86-64,
3761 // va_list is an array, but it's supposed to decay to
3762 // a pointer for va_arg.
3763 if (VaListType->isArrayType())
3764 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003765 // Make sure the input expression also decays appropriately.
3766 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003767
3768 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003769 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00003770 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003771 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00003772
3773 // FIXME: Warn if a non-POD type is passed in.
3774
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003775 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003776}
3777
Douglas Gregorad4b3792008-11-29 04:51:27 +00003778Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
3779 // The type of __null will be int or long, depending on the size of
3780 // pointers on the target.
3781 QualType Ty;
3782 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
3783 Ty = Context.IntTy;
3784 else
3785 Ty = Context.LongTy;
3786
3787 return new GNUNullExpr(Ty, TokenLoc);
3788}
3789
Chris Lattner005ed752008-01-04 18:04:52 +00003790bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3791 SourceLocation Loc,
3792 QualType DstType, QualType SrcType,
3793 Expr *SrcExpr, const char *Flavor) {
3794 // Decode the result (notice that AST's are still created for extensions).
3795 bool isInvalid = false;
3796 unsigned DiagKind;
3797 switch (ConvTy) {
3798 default: assert(0 && "Unknown conversion type");
3799 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003800 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003801 DiagKind = diag::ext_typecheck_convert_pointer_int;
3802 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003803 case IntToPointer:
3804 DiagKind = diag::ext_typecheck_convert_int_pointer;
3805 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003806 case IncompatiblePointer:
3807 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3808 break;
3809 case FunctionVoidPointer:
3810 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3811 break;
3812 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003813 // If the qualifiers lost were because we were applying the
3814 // (deprecated) C++ conversion from a string literal to a char*
3815 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3816 // Ideally, this check would be performed in
3817 // CheckPointerTypesForAssignment. However, that would require a
3818 // bit of refactoring (so that the second argument is an
3819 // expression, rather than a type), which should be done as part
3820 // of a larger effort to fix CheckPointerTypesForAssignment for
3821 // C++ semantics.
3822 if (getLangOptions().CPlusPlus &&
3823 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3824 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003825 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3826 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003827 case IntToBlockPointer:
3828 DiagKind = diag::err_int_to_block_pointer;
3829 break;
3830 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003831 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003832 break;
Steve Naroff19608432008-10-14 22:18:38 +00003833 case IncompatibleObjCQualifiedId:
3834 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3835 // it can give a more specific diagnostic.
3836 DiagKind = diag::warn_incompatible_qualified_id;
3837 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003838 case Incompatible:
3839 DiagKind = diag::err_typecheck_convert_incompatible;
3840 isInvalid = true;
3841 break;
3842 }
3843
Chris Lattner271d4c22008-11-24 05:29:24 +00003844 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
3845 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00003846 return isInvalid;
3847}
Anders Carlssond5201b92008-11-30 19:50:32 +00003848
3849bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
3850{
3851 Expr::EvalResult EvalResult;
3852
3853 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
3854 EvalResult.HasSideEffects) {
3855 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
3856
3857 if (EvalResult.Diag) {
3858 // We only show the note if it's not the usual "invalid subexpression"
3859 // or if it's actually in a subexpression.
3860 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
3861 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
3862 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3863 }
3864
3865 return true;
3866 }
3867
3868 if (EvalResult.Diag) {
3869 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
3870 E->getSourceRange();
3871
3872 // Print the reason it's not a constant.
3873 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
3874 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3875 }
3876
3877 if (Result)
3878 *Result = EvalResult.Val.getInt();
3879 return false;
3880}