blob: b2542542417723451b0dcf6f6f56312d80696bd6 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Chris Lattner299b8842008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattner299b8842008-07-25 21:10:04 +000033/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
34void Sema::DefaultFunctionArrayConversion(Expr *&E) {
35 QualType Ty = E->getType();
36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
37
Chris Lattner299b8842008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000040 else if (Ty->isArrayType()) {
41 // In C90 mode, arrays only promote to pointers if the array expression is
42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
43 // type 'array of type' is converted to an expression that has type 'pointer
44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
45 // that has type 'array of type' ...". The relevant change is "an lvalue"
46 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000047 //
48 // C++ 4.2p1:
49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
50 // T" can be converted to an rvalue of type "pointer to T".
51 //
52 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
53 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattner299b8842008-07-25 21:10:04 +000056}
57
58/// UsualUnaryConversions - Performs various conversions that are common to most
59/// operators (C99 6.3). The conversions of array and function types are
60/// sometimes surpressed. For example, the array->pointer conversion doesn't
61/// apply if the array is an argument to the sizeof or address (&) operators.
62/// In these instances, this routine should *not* be called.
63Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
64 QualType Ty = Expr->getType();
65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
66
Chris Lattner299b8842008-07-25 21:10:04 +000067 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
68 ImpCastExprToType(Expr, Context.IntTy);
69 else
70 DefaultFunctionArrayConversion(Expr);
71
72 return Expr;
73}
74
Chris Lattner9305c3d2008-07-25 22:25:12 +000075/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
76/// do not have a prototype. Arguments that have type float are promoted to
77/// double. All other argument types are converted by UsualUnaryConversions().
78void Sema::DefaultArgumentPromotion(Expr *&Expr) {
79 QualType Ty = Expr->getType();
80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
81
82 // If this is a 'float' (CVR qualified or typedef) promote to double.
83 if (const BuiltinType *BT = Ty->getAsBuiltinType())
84 if (BT->getKind() == BuiltinType::Float)
85 return ImpCastExprToType(Expr, Context.DoubleTy);
86
87 UsualUnaryConversions(Expr);
88}
89
Chris Lattner299b8842008-07-25 21:10:04 +000090/// UsualArithmeticConversions - Performs various conversions that are common to
91/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
92/// routine returns the first non-arithmetic type found. The client is
93/// responsible for emitting appropriate error diagnostics.
94/// FIXME: verify the conversion rules for "complex int" are consistent with
95/// GCC.
96QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
97 bool isCompAssign) {
98 if (!isCompAssign) {
99 UsualUnaryConversions(lhsExpr);
100 UsualUnaryConversions(rhsExpr);
101 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000102
Chris Lattner299b8842008-07-25 21:10:04 +0000103 // For conversion purposes, we ignore any qualifiers.
104 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000105 QualType lhs =
106 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
107 QualType rhs =
108 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000109
110 // If both types are identical, no conversion is needed.
111 if (lhs == rhs)
112 return lhs;
113
114 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
115 // The caller can deal with this (e.g. pointer + int).
116 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
117 return lhs;
118
119 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
120 if (!isCompAssign) {
121 ImpCastExprToType(lhsExpr, destType);
122 ImpCastExprToType(rhsExpr, destType);
123 }
124 return destType;
125}
126
127QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
128 // Perform the usual unary conversions. We do this early so that
129 // integral promotions to "int" can allow us to exit early, in the
130 // lhs == rhs check. Also, for conversion purposes, we ignore any
131 // qualifiers. For example, "const float" and "float" are
132 // equivalent.
Douglas Gregor3d4492e2008-11-13 20:12:29 +0000133 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
134 else lhs = lhs.getUnqualifiedType();
135 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
136 else rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000137
Chris Lattner299b8842008-07-25 21:10:04 +0000138 // If both types are identical, no conversion is needed.
139 if (lhs == rhs)
140 return lhs;
141
142 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
143 // The caller can deal with this (e.g. pointer + int).
144 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
145 return lhs;
146
147 // At this point, we have two different arithmetic types.
148
149 // Handle complex types first (C99 6.3.1.8p1).
150 if (lhs->isComplexType() || rhs->isComplexType()) {
151 // if we have an integer operand, the result is the complex type.
152 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
153 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000154 return lhs;
155 }
156 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
157 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000158 return rhs;
159 }
160 // This handles complex/complex, complex/float, or float/complex.
161 // When both operands are complex, the shorter operand is converted to the
162 // type of the longer, and that is the type of the result. This corresponds
163 // to what is done when combining two real floating-point operands.
164 // The fun begins when size promotion occur across type domains.
165 // From H&S 6.3.4: When one operand is complex and the other is a real
166 // floating-point type, the less precise type is converted, within it's
167 // real or complex domain, to the precision of the other type. For example,
168 // when combining a "long double" with a "double _Complex", the
169 // "double _Complex" is promoted to "long double _Complex".
170 int result = Context.getFloatingTypeOrder(lhs, rhs);
171
172 if (result > 0) { // The left side is bigger, convert rhs.
173 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000174 } else if (result < 0) { // The right side is bigger, convert lhs.
175 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000176 }
177 // At this point, lhs and rhs have the same rank/size. Now, make sure the
178 // domains match. This is a requirement for our implementation, C99
179 // does not require this promotion.
180 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
181 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000182 return rhs;
183 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000184 return lhs;
185 }
186 }
187 return lhs; // The domain/size match exactly.
188 }
189 // Now handle "real" floating types (i.e. float, double, long double).
190 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
191 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000192 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000193 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000194 return lhs;
195 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000196 if (rhs->isComplexIntegerType()) {
197 // convert rhs to the complex floating point type.
198 return Context.getComplexType(lhs);
199 }
200 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000201 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000202 return rhs;
203 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000204 if (lhs->isComplexIntegerType()) {
205 // convert lhs to the complex floating point type.
206 return Context.getComplexType(rhs);
207 }
Chris Lattner299b8842008-07-25 21:10:04 +0000208 // We have two real floating types, float/complex combos were handled above.
209 // Convert the smaller operand to the bigger result.
210 int result = Context.getFloatingTypeOrder(lhs, rhs);
211
212 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000213 return lhs;
214 }
215 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000216 return rhs;
217 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000218 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000219 }
220 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
221 // Handle GCC complex int extension.
222 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
223 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
224
225 if (lhsComplexInt && rhsComplexInt) {
226 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
227 rhsComplexInt->getElementType()) >= 0) {
228 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000229 return lhs;
230 }
Chris Lattner299b8842008-07-25 21:10:04 +0000231 return rhs;
232 } else if (lhsComplexInt && rhs->isIntegerType()) {
233 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000234 return lhs;
235 } else if (rhsComplexInt && lhs->isIntegerType()) {
236 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000237 return rhs;
238 }
239 }
240 // Finally, we have two differing integer types.
241 // The rules for this case are in C99 6.3.1.8
242 int compare = Context.getIntegerTypeOrder(lhs, rhs);
243 bool lhsSigned = lhs->isSignedIntegerType(),
244 rhsSigned = rhs->isSignedIntegerType();
245 QualType destType;
246 if (lhsSigned == rhsSigned) {
247 // Same signedness; use the higher-ranked type
248 destType = compare >= 0 ? lhs : rhs;
249 } else if (compare != (lhsSigned ? 1 : -1)) {
250 // The unsigned type has greater than or equal rank to the
251 // signed type, so use the unsigned type
252 destType = lhsSigned ? rhs : lhs;
253 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
254 // The two types are different widths; if we are here, that
255 // means the signed type is larger than the unsigned type, so
256 // use the signed type.
257 destType = lhsSigned ? lhs : rhs;
258 } else {
259 // The signed type is higher-ranked than the unsigned type,
260 // but isn't actually any bigger (like unsigned int and long
261 // on most 32-bit systems). Use the unsigned type corresponding
262 // to the signed type.
263 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
264 }
Chris Lattner299b8842008-07-25 21:10:04 +0000265 return destType;
266}
267
268//===----------------------------------------------------------------------===//
269// Semantic Analysis for various Expression Types
270//===----------------------------------------------------------------------===//
271
272
Steve Naroff87d58b42007-09-16 03:34:24 +0000273/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000274/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
275/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
276/// multiple tokens. However, the common case is that StringToks points to one
277/// string.
278///
279Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000280Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000281 assert(NumStringToks && "Must have at least one string!");
282
283 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
284 if (Literal.hadError)
285 return ExprResult(true);
286
287 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
288 for (unsigned i = 0; i != NumStringToks; ++i)
289 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000290
291 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000292 if (Literal.Pascal && Literal.GetStringLength() > 256)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000293 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
294 << SourceRange(StringToks[0].getLocation(),
295 StringToks[NumStringToks-1].getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000296
Chris Lattnera6dcce32008-02-11 00:02:17 +0000297 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000298 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000299 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000300
301 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
302 if (getLangOptions().CPlusPlus)
303 StrTy.addConst();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000304
305 // Get an array type for the string, according to C99 6.4.5. This includes
306 // the nul terminator character as well as the string length for pascal
307 // strings.
308 StrTy = Context.getConstantArrayType(StrTy,
309 llvm::APInt(32, Literal.GetStringLength()+1),
310 ArrayType::Normal, 0);
311
Chris Lattner4b009652007-07-25 00:24:17 +0000312 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
313 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000314 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000315 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000316 StringToks[NumStringToks-1].getLocation());
317}
318
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000319/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
320/// CurBlock to VD should cause it to be snapshotted (as we do for auto
321/// variables defined outside the block) or false if this is not needed (e.g.
322/// for values inside the block or for globals).
323///
324/// FIXME: This will create BlockDeclRefExprs for global variables,
325/// function references, etc which is suboptimal :) and breaks
326/// things like "integer constant expression" tests.
327static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
328 ValueDecl *VD) {
329 // If the value is defined inside the block, we couldn't snapshot it even if
330 // we wanted to.
331 if (CurBlock->TheDecl == VD->getDeclContext())
332 return false;
333
334 // If this is an enum constant or function, it is constant, don't snapshot.
335 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
336 return false;
337
338 // If this is a reference to an extern, static, or global variable, no need to
339 // snapshot it.
340 // FIXME: What about 'const' variables in C++?
341 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
342 return Var->hasLocalStorage();
343
344 return true;
345}
346
347
348
Steve Naroff0acc9c92007-09-15 18:49:24 +0000349/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000350/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000351/// identifier is used in a function call context.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000352/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the
353/// class or namespace that the identifier must be a member of.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000354Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000355 IdentifierInfo &II,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000356 bool HasTrailingLParen,
357 const CXXScopeSpec *SS) {
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000358 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
359}
360
361/// ActOnDeclarationNameExpr - The parser has read some kind of name
362/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
363/// performs lookup on that name and returns an expression that refers
364/// to that name. This routine isn't directly called from the parser,
365/// because the parser doesn't know about DeclarationName. Rather,
366/// this routine is called by ActOnIdentifierExpr,
367/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
368/// which form the DeclarationName from the corresponding syntactic
369/// forms.
370///
371/// HasTrailingLParen indicates whether this identifier is used in a
372/// function call context. LookupCtx is only used for a C++
373/// qualified-id (foo::bar) to indicate the class or namespace that
374/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000375///
376/// If ForceResolution is true, then we will attempt to resolve the
377/// name even if it looks like a dependent name. This option is off by
378/// default.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000379Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
380 DeclarationName Name,
381 bool HasTrailingLParen,
Douglas Gregora133e262008-12-06 00:22:45 +0000382 const CXXScopeSpec *SS,
383 bool ForceResolution) {
384 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
385 HasTrailingLParen && !SS && !ForceResolution) {
386 // We've seen something of the form
387 // identifier(
388 // and we are in a template, so it is likely that 's' is a
389 // dependent name. However, we won't know until we've parsed all
390 // of the call arguments. So, build a CXXDependentNameExpr node
391 // to represent this name. Then, if it turns out that none of the
392 // arguments are type-dependent, we'll force the resolution of the
393 // dependent name at that point.
394 return new CXXDependentNameExpr(Name.getAsIdentifierInfo(),
395 Context.DependentTy, Loc);
396 }
397
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000398 // Could be enum-constant, value decl, instance variable, etc.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000399 Decl *D;
400 if (SS && !SS->isEmpty()) {
401 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
402 if (DC == 0)
403 return true;
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000404 D = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000405 } else
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000406 D = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Douglas Gregora133e262008-12-06 00:22:45 +0000407
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000408 // If this reference is in an Objective-C method, then ivar lookup happens as
409 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000410 IdentifierInfo *II = Name.getAsIdentifierInfo();
411 if (II && getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000412 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000413 // There are two cases to handle here. 1) scoped lookup could have failed,
414 // in which case we should look for an ivar. 2) scoped lookup could have
415 // found a decl, but that decl is outside the current method (i.e. a global
416 // variable). In these two cases, we do a lookup for an ivar with this
417 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000418 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000419 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000420 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000421 // FIXME: This should use a new expr for a direct reference, don't turn
422 // this into Self->ivar, just return a BareIVarExpr or something.
423 IdentifierInfo &II = Context.Idents.get("self");
424 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
425 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
426 static_cast<Expr*>(SelfExpr.Val), true, true);
427 }
428 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000429 // Needed to implement property "super.method" notation.
Chris Lattner87fada82008-11-20 05:35:30 +0000430 if (SD == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000431 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000432 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000433 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000434 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000435 }
Chris Lattner4b009652007-07-25 00:24:17 +0000436 if (D == 0) {
437 // Otherwise, this could be an implicitly declared function reference (legal
438 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000439 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000440 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000441 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000442 else {
443 // If this name wasn't predeclared and if this is not a function call,
444 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000445 if (SS && !SS->isEmpty())
Chris Lattner77d52da2008-11-20 06:06:08 +0000446 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattnerb1753422008-11-23 21:45:46 +0000447 << Name << SS->getRange();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000448 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
449 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000450 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000451 else
Chris Lattnerb1753422008-11-23 21:45:46 +0000452 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000453 }
454 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000455
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000456 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
457 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
458 if (MD->isStatic())
459 // "invalid use of member 'x' in static member function"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000460 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattner271d4c22008-11-24 05:29:24 +0000461 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000462 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
463 // "invalid use of nonstatic data member 'x'"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000464 return Diag(Loc, diag::err_invalid_non_static_member_use)
Chris Lattner271d4c22008-11-24 05:29:24 +0000465 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000466
467 if (FD->isInvalidDecl())
468 return true;
469
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +0000470 // FIXME: Handle 'mutable'.
471 return new DeclRefExpr(FD,
472 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000473 }
474
Chris Lattner271d4c22008-11-24 05:29:24 +0000475 return Diag(Loc, diag::err_invalid_non_static_member_use)
476 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000477 }
Chris Lattner4b009652007-07-25 00:24:17 +0000478 if (isa<TypedefDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000479 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremenek42730c52008-01-07 19:49:32 +0000480 if (isa<ObjCInterfaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000481 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000482 if (isa<NamespaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000483 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000484
Steve Naroffd6163f32008-09-05 22:11:13 +0000485 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000486 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
487 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
488
Steve Naroffd6163f32008-09-05 22:11:13 +0000489 ValueDecl *VD = cast<ValueDecl>(D);
490
491 // check if referencing an identifier with __attribute__((deprecated)).
492 if (VD->getAttr<DeprecatedAttr>())
Chris Lattner271d4c22008-11-24 05:29:24 +0000493 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Douglas Gregor48840c72008-12-10 23:01:14 +0000494
495 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
496 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
497 Scope *CheckS = S;
498 while (CheckS) {
499 if (CheckS->isWithinElse() &&
500 CheckS->getControlParent()->isDeclScope(Var)) {
501 if (Var->getType()->isBooleanType())
502 Diag(Loc, diag::warn_value_always_false) << Var->getDeclName();
503 else
504 Diag(Loc, diag::warn_value_always_zero) << Var->getDeclName();
505 break;
506 }
507
508 // Move up one more control parent to check again.
509 CheckS = CheckS->getControlParent();
510 if (CheckS)
511 CheckS = CheckS->getParent();
512 }
513 }
514 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000515
516 // Only create DeclRefExpr's for valid Decl's.
517 if (VD->isInvalidDecl())
518 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000519
520 // If the identifier reference is inside a block, and it refers to a value
521 // that is outside the block, create a BlockDeclRefExpr instead of a
522 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
523 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000524 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000525 // We do not do this for things like enum constants, global variables, etc,
526 // as they do not get snapshotted.
527 //
528 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000529 // The BlocksAttr indicates the variable is bound by-reference.
530 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000531 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
532 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000533
534 // Variable will be bound by-copy, make it const within the closure.
535 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000536 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
537 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000538 }
539 // If this reference is not in a block or if the referenced variable is
540 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000541
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000542 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000543 bool ValueDependent = false;
544 if (getLangOptions().CPlusPlus) {
545 // C++ [temp.dep.expr]p3:
546 // An id-expression is type-dependent if it contains:
547 // - an identifier that was declared with a dependent type,
548 if (VD->getType()->isDependentType())
549 TypeDependent = true;
550 // - FIXME: a template-id that is dependent,
551 // - a conversion-function-id that specifies a dependent type,
552 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
553 Name.getCXXNameType()->isDependentType())
554 TypeDependent = true;
555 // - a nested-name-specifier that contains a class-name that
556 // names a dependent type.
557 else if (SS && !SS->isEmpty()) {
558 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
559 DC; DC = DC->getParent()) {
560 // FIXME: could stop early at namespace scope.
561 if (DC->isCXXRecord()) {
562 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
563 if (Context.getTypeDeclType(Record)->isDependentType()) {
564 TypeDependent = true;
565 break;
566 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000567 }
568 }
569 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000570
Douglas Gregora5d84612008-12-10 20:57:37 +0000571 // C++ [temp.dep.constexpr]p2:
572 //
573 // An identifier is value-dependent if it is:
574 // - a name declared with a dependent type,
575 if (TypeDependent)
576 ValueDependent = true;
577 // - the name of a non-type template parameter,
578 else if (isa<NonTypeTemplateParmDecl>(VD))
579 ValueDependent = true;
580 // - a constant with integral or enumeration type and is
581 // initialized with an expression that is value-dependent
582 // (FIXME!).
583 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000584
585 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
586 TypeDependent, ValueDependent);
Chris Lattner4b009652007-07-25 00:24:17 +0000587}
588
Chris Lattner69909292008-08-10 01:53:14 +0000589Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000590 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000591 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000592
593 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000594 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000595 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
596 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
597 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000598 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000599
600 // Verify that this is in a function context.
Chris Lattnere5cb5862008-12-04 23:50:19 +0000601 if (getCurFunctionOrMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000602 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000603
Chris Lattner7e637512008-01-12 08:14:25 +0000604 // Pre-defined identifiers are of type char[x], where x is the length of the
605 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000606 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000607 if (FunctionDecl *FD = getCurFunctionDecl())
608 Length = FD->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000609 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000610 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000611
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000612 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000613 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000614 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000615 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000616}
617
Steve Naroff87d58b42007-09-16 03:34:24 +0000618Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000619 llvm::SmallString<16> CharBuffer;
620 CharBuffer.resize(Tok.getLength());
621 const char *ThisTokBegin = &CharBuffer[0];
622 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
623
624 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
625 Tok.getLocation(), PP);
626 if (Literal.hadError())
627 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000628
629 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
630
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000631 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
632 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000633}
634
Steve Naroff87d58b42007-09-16 03:34:24 +0000635Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000636 // fast path for a single digit (which is quite common). A single digit
637 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
638 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000639 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000640
Chris Lattner8cd0e932008-03-05 18:54:05 +0000641 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000642 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000643 Context.IntTy,
644 Tok.getLocation()));
645 }
646 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000647 // Add padding so that NumericLiteralParser can overread by one character.
648 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000649 const char *ThisTokBegin = &IntegerBuffer[0];
650
651 // Get the spelling of the token, which eliminates trigraphs, etc.
652 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000653
Chris Lattner4b009652007-07-25 00:24:17 +0000654 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
655 Tok.getLocation(), PP);
656 if (Literal.hadError)
657 return ExprResult(true);
658
Chris Lattner1de66eb2007-08-26 03:42:43 +0000659 Expr *Res;
660
661 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000662 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000663 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000664 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000665 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000666 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000667 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000668 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000669
670 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
671
Ted Kremenekddedbe22007-11-29 00:56:49 +0000672 // isExact will be set by GetFloatValue().
673 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000674 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000675 Ty, Tok.getLocation());
676
Chris Lattner1de66eb2007-08-26 03:42:43 +0000677 } else if (!Literal.isIntegerLiteral()) {
678 return ExprResult(true);
679 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000680 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000681
Neil Booth7421e9c2007-08-29 22:00:19 +0000682 // long long is a C99 feature.
683 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000684 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000685 Diag(Tok.getLocation(), diag::ext_longlong);
686
Chris Lattner4b009652007-07-25 00:24:17 +0000687 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000688 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000689
690 if (Literal.GetIntegerValue(ResultVal)) {
691 // If this value didn't fit into uintmax_t, warn and force to ull.
692 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000693 Ty = Context.UnsignedLongLongTy;
694 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000695 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000696 } else {
697 // If this value fits into a ULL, try to figure out what else it fits into
698 // according to the rules of C99 6.4.4.1p5.
699
700 // Octal, Hexadecimal, and integers with a U suffix are allowed to
701 // be an unsigned int.
702 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
703
704 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000705 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000706 if (!Literal.isLong && !Literal.isLongLong) {
707 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000708 unsigned IntSize = Context.Target.getIntWidth();
709
Chris Lattner4b009652007-07-25 00:24:17 +0000710 // Does it fit in a unsigned int?
711 if (ResultVal.isIntN(IntSize)) {
712 // Does it fit in a signed int?
713 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000714 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000715 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000716 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000717 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000718 }
Chris Lattner4b009652007-07-25 00:24:17 +0000719 }
720
721 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000722 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000723 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000724
725 // Does it fit in a unsigned long?
726 if (ResultVal.isIntN(LongSize)) {
727 // Does it fit in a signed long?
728 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000729 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000730 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000731 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000732 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000733 }
Chris Lattner4b009652007-07-25 00:24:17 +0000734 }
735
736 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000737 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000738 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000739
740 // Does it fit in a unsigned long long?
741 if (ResultVal.isIntN(LongLongSize)) {
742 // Does it fit in a signed long long?
743 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000744 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000745 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000746 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000747 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000748 }
749 }
750
751 // If we still couldn't decide a type, we probably have something that
752 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000753 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000754 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000755 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000756 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000757 }
Chris Lattnere4068872008-05-09 05:59:00 +0000758
759 if (ResultVal.getBitWidth() != Width)
760 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000761 }
762
Chris Lattner48d7f382008-04-02 04:24:33 +0000763 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000764 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000765
766 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
767 if (Literal.isImaginary)
768 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
769
770 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000771}
772
Steve Naroff87d58b42007-09-16 03:34:24 +0000773Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000774 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000775 Expr *E = (Expr *)Val;
776 assert((E != 0) && "ActOnParenExpr() missing expr");
777 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000778}
779
780/// The UsualUnaryConversions() function is *not* called by this routine.
781/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000782bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
783 SourceLocation OpLoc,
784 const SourceRange &ExprRange,
785 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000786 // C99 6.5.3.4p1:
787 if (isa<FunctionType>(exprType) && isSizeof)
788 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000789 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +0000790 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000791 Diag(OpLoc, diag::ext_sizeof_void_type)
792 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
793 else if (exprType->isIncompleteType())
794 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
795 diag::err_alignof_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000796 << exprType << ExprRange;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000797
798 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000799}
800
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000801/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
802/// the same for @c alignof and @c __alignof
803/// Note that the ArgRange is invalid if isType is false.
804Action::ExprResult
805Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
806 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +0000807 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000808 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000809
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000810 QualType ArgTy;
811 SourceRange Range;
812 if (isType) {
813 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
814 Range = ArgRange;
815 } else {
816 // Get the end location.
817 Expr *ArgEx = (Expr *)TyOrEx;
818 Range = ArgEx->getSourceRange();
819 ArgTy = ArgEx->getType();
820 }
821
822 // Verify that the operand is valid.
823 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +0000824 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000825
826 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
827 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
828 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +0000829}
830
Chris Lattner5110ad52007-08-24 21:41:10 +0000831QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000832 DefaultFunctionArrayConversion(V);
833
Chris Lattnera16e42d2007-08-26 05:39:26 +0000834 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000835 if (const ComplexType *CT = V->getType()->getAsComplexType())
836 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000837
838 // Otherwise they pass through real integer and floating point types here.
839 if (V->getType()->isArithmeticType())
840 return V->getType();
841
842 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +0000843 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000844 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000845}
846
847
Chris Lattner4b009652007-07-25 00:24:17 +0000848
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000849Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000850 tok::TokenKind Kind,
851 ExprTy *Input) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000852 Expr *Arg = (Expr *)Input;
853
Chris Lattner4b009652007-07-25 00:24:17 +0000854 UnaryOperator::Opcode Opc;
855 switch (Kind) {
856 default: assert(0 && "Unknown unary op!");
857 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
858 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
859 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000860
861 if (getLangOptions().CPlusPlus &&
862 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
863 // Which overloaded operator?
864 OverloadedOperatorKind OverOp =
865 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
866
867 // C++ [over.inc]p1:
868 //
869 // [...] If the function is a member function with one
870 // parameter (which shall be of type int) or a non-member
871 // function with two parameters (the second of which shall be
872 // of type int), it defines the postfix increment operator ++
873 // for objects of that type. When the postfix increment is
874 // called as a result of using the ++ operator, the int
875 // argument will have value zero.
876 Expr *Args[2] = {
877 Arg,
878 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
879 /*isSigned=*/true),
880 Context.IntTy, SourceLocation())
881 };
882
883 // Build the candidate set for overloading
884 OverloadCandidateSet CandidateSet;
885 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
886
887 // Perform overload resolution.
888 OverloadCandidateSet::iterator Best;
889 switch (BestViableFunction(CandidateSet, Best)) {
890 case OR_Success: {
891 // We found a built-in operator or an overloaded operator.
892 FunctionDecl *FnDecl = Best->Function;
893
894 if (FnDecl) {
895 // We matched an overloaded operator. Build a call to that
896 // operator.
897
898 // Convert the arguments.
899 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
900 if (PerformObjectArgumentInitialization(Arg, Method))
901 return true;
902 } else {
903 // Convert the arguments.
904 if (PerformCopyInitialization(Arg,
905 FnDecl->getParamDecl(0)->getType(),
906 "passing"))
907 return true;
908 }
909
910 // Determine the result type
911 QualType ResultTy
912 = FnDecl->getType()->getAsFunctionType()->getResultType();
913 ResultTy = ResultTy.getNonReferenceType();
914
915 // Build the actual expression node.
916 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
917 SourceLocation());
918 UsualUnaryConversions(FnExpr);
919
920 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
921 } else {
922 // We matched a built-in operator. Convert the arguments, then
923 // break out so that we will build the appropriate built-in
924 // operator node.
925 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
926 "passing"))
927 return true;
928
929 break;
930 }
931 }
932
933 case OR_No_Viable_Function:
934 // No viable function; fall through to handling this as a
935 // built-in operator, which will produce an error message for us.
936 break;
937
938 case OR_Ambiguous:
939 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
940 << UnaryOperator::getOpcodeStr(Opc)
941 << Arg->getSourceRange();
942 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
943 return true;
944 }
945
946 // Either we found no viable overloaded operator or we matched a
947 // built-in operator. In either case, fall through to trying to
948 // build a built-in operation.
949 }
950
951 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000952 if (result.isNull())
953 return true;
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000954 return new UnaryOperator(Arg, Opc, result, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000955}
956
957Action::ExprResult Sema::
Douglas Gregor80723c52008-11-19 17:17:41 +0000958ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000959 ExprTy *Idx, SourceLocation RLoc) {
960 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
961
Douglas Gregor80723c52008-11-19 17:17:41 +0000962 if (getLangOptions().CPlusPlus &&
963 LHSExp->getType()->isRecordType() ||
964 LHSExp->getType()->isEnumeralType() ||
965 RHSExp->getType()->isRecordType() ||
Sebastian Redle5edfce2008-12-03 16:32:40 +0000966 RHSExp->getType()->isEnumeralType()) {
Douglas Gregor80723c52008-11-19 17:17:41 +0000967 // Add the appropriate overloaded operators (C++ [over.match.oper])
968 // to the candidate set.
969 OverloadCandidateSet CandidateSet;
970 Expr *Args[2] = { LHSExp, RHSExp };
971 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
972
973 // Perform overload resolution.
974 OverloadCandidateSet::iterator Best;
975 switch (BestViableFunction(CandidateSet, Best)) {
976 case OR_Success: {
977 // We found a built-in operator or an overloaded operator.
978 FunctionDecl *FnDecl = Best->Function;
979
980 if (FnDecl) {
981 // We matched an overloaded operator. Build a call to that
982 // operator.
983
984 // Convert the arguments.
985 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
986 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
987 PerformCopyInitialization(RHSExp,
988 FnDecl->getParamDecl(0)->getType(),
989 "passing"))
990 return true;
991 } else {
992 // Convert the arguments.
993 if (PerformCopyInitialization(LHSExp,
994 FnDecl->getParamDecl(0)->getType(),
995 "passing") ||
996 PerformCopyInitialization(RHSExp,
997 FnDecl->getParamDecl(1)->getType(),
998 "passing"))
999 return true;
1000 }
1001
1002 // Determine the result type
1003 QualType ResultTy
1004 = FnDecl->getType()->getAsFunctionType()->getResultType();
1005 ResultTy = ResultTy.getNonReferenceType();
1006
1007 // Build the actual expression node.
1008 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1009 SourceLocation());
1010 UsualUnaryConversions(FnExpr);
1011
1012 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
1013 } else {
1014 // We matched a built-in operator. Convert the arguments, then
1015 // break out so that we will build the appropriate built-in
1016 // operator node.
1017 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1018 "passing") ||
1019 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1020 "passing"))
1021 return true;
1022
1023 break;
1024 }
1025 }
1026
1027 case OR_No_Viable_Function:
1028 // No viable function; fall through to handling this as a
1029 // built-in operator, which will produce an error message for us.
1030 break;
1031
1032 case OR_Ambiguous:
1033 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1034 << "[]"
1035 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1036 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1037 return true;
1038 }
1039
1040 // Either we found no viable overloaded operator or we matched a
1041 // built-in operator. In either case, fall through to trying to
1042 // build a built-in operation.
1043 }
1044
Chris Lattner4b009652007-07-25 00:24:17 +00001045 // Perform default conversions.
1046 DefaultFunctionArrayConversion(LHSExp);
1047 DefaultFunctionArrayConversion(RHSExp);
1048
1049 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1050
1051 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001052 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001053 // in the subscript position. As a result, we need to derive the array base
1054 // and index from the expression types.
1055 Expr *BaseExpr, *IndexExpr;
1056 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001057 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001058 BaseExpr = LHSExp;
1059 IndexExpr = RHSExp;
1060 // FIXME: need to deal with const...
1061 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001062 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001063 // Handle the uncommon case of "123[Ptr]".
1064 BaseExpr = RHSExp;
1065 IndexExpr = LHSExp;
1066 // FIXME: need to deal with const...
1067 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001068 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1069 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001070 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +00001071
1072 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +00001073 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1074 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001075 return Diag(LLoc, diag::err_ext_vector_component_access)
1076 << SourceRange(LLoc, RLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001077 // FIXME: need to deal with const...
1078 ResultType = VTy->getElementType();
1079 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001080 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
1081 << RHSExp->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001082 }
1083 // C99 6.5.2.1p1
1084 if (!IndexExpr->getType()->isIntegerType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001085 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
1086 << IndexExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001087
1088 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1089 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001090 // void (*)(int)) and pointers to incomplete types. Functions are not
1091 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001092 if (!ResultType->isObjectType())
1093 return Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001094 diag::err_typecheck_subscript_not_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001095 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001096
1097 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
1098}
1099
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001100QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001101CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001102 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001103 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001104
1105 // This flag determines whether or not the component is to be treated as a
1106 // special name, or a regular GLSL-style component access.
1107 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001108
1109 // The vector accessor can't exceed the number of elements.
1110 const char *compStr = CompName.getName();
1111 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001112 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001113 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001114 return QualType();
1115 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001116
1117 // Check that we've found one of the special components, or that the component
1118 // names must come from the same set.
1119 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1120 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1121 SpecialComponent = true;
1122 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001123 do
1124 compStr++;
1125 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1126 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1127 do
1128 compStr++;
1129 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1130 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1131 do
1132 compStr++;
1133 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1134 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001135
Nate Begemanc8e51f82008-05-09 06:41:27 +00001136 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001137 // We didn't get to the end of the string. This means the component names
1138 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001139 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1140 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001141 return QualType();
1142 }
1143 // Each component accessor can't exceed the vector type.
1144 compStr = CompName.getName();
1145 while (*compStr) {
1146 if (vecType->isAccessorWithinNumElements(*compStr))
1147 compStr++;
1148 else
1149 break;
1150 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001151 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001152 // We didn't get to the end of the string. This means a component accessor
1153 // exceeds the number of elements in the vector.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001154 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001155 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001156 return QualType();
1157 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001158
1159 // If we have a special component name, verify that the current vector length
1160 // is an even number, since all special component names return exactly half
1161 // the elements.
1162 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001163 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001164 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001165 return QualType();
1166 }
1167
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001168 // The component accessor looks fine - now we need to compute the actual type.
1169 // The vector type is implied by the component accessor. For example,
1170 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001171 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1172 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner65cae292008-11-19 08:23:25 +00001173 : CompName.getLength();
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001174 if (CompSize == 1)
1175 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001176
Nate Begemanaf6ed502008-04-18 23:10:10 +00001177 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001178 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001179 // diagostics look bad. We want extended vector types to appear built-in.
1180 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1181 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1182 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001183 }
1184 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001185}
1186
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001187/// constructSetterName - Return the setter name for the given
1188/// identifier, i.e. "set" + Name where the initial character of Name
1189/// has been capitalized.
1190// FIXME: Merge with same routine in Parser. But where should this
1191// live?
1192static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1193 const IdentifierInfo *Name) {
1194 llvm::SmallString<100> SelectorName;
1195 SelectorName = "set";
1196 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1197 SelectorName[3] = toupper(SelectorName[3]);
1198 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1199}
1200
Chris Lattner4b009652007-07-25 00:24:17 +00001201Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001202ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001203 tok::TokenKind OpKind, SourceLocation MemberLoc,
1204 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001205 Expr *BaseExpr = static_cast<Expr *>(Base);
1206 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001207
1208 // Perform default conversions.
1209 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +00001210
Steve Naroff2cb66382007-07-26 03:11:44 +00001211 QualType BaseType = BaseExpr->getType();
1212 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001213
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001214 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1215 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001216 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001217 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001218 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001219 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
1220 return BuildOverloadedArrowExpr(BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroff2cb66382007-07-26 03:11:44 +00001221 else
Chris Lattner8ba580c2008-11-19 05:08:23 +00001222 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001223 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001224 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001225
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001226 // Handle field access to simple records. This also handles access to fields
1227 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001228 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001229 RecordDecl *RDecl = RTy->getDecl();
1230 if (RTy->isIncompleteType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001231 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattner271d4c22008-11-24 05:29:24 +00001232 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroff2cb66382007-07-26 03:11:44 +00001233 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001234 FieldDecl *MemberDecl = RDecl->getMember(&Member);
1235 if (!MemberDecl)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001236 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner65cae292008-11-19 08:23:25 +00001237 << &Member << BaseExpr->getSourceRange();
Eli Friedman76b49832008-02-06 22:48:16 +00001238
1239 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +00001240 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +00001241 QualType MemberType = MemberDecl->getType();
1242 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +00001243 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +00001244 if (CXXFieldDecl *CXXMember = dyn_cast<CXXFieldDecl>(MemberDecl)) {
1245 if (CXXMember->isMutable())
1246 combinedQualifiers &= ~QualType::Const;
1247 }
Eli Friedman76b49832008-02-06 22:48:16 +00001248 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1249
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001250 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +00001251 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +00001252 }
1253
Chris Lattnere9d71612008-07-21 04:59:05 +00001254 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1255 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001256 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
1257 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001258 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +00001259 OpKind == tok::arrow);
Chris Lattner8ba580c2008-11-19 05:08:23 +00001260 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattner271d4c22008-11-24 05:29:24 +00001261 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattner8ba580c2008-11-19 05:08:23 +00001262 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001263 }
1264
Chris Lattnere9d71612008-07-21 04:59:05 +00001265 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1266 // pointer to a (potentially qualified) interface type.
1267 const PointerType *PTy;
1268 const ObjCInterfaceType *IFTy;
1269 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1270 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1271 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001272
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001273 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001274 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1275 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1276
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001277 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001278 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1279 E = IFTy->qual_end(); I != E; ++I)
1280 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1281 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001282
1283 // If that failed, look for an "implicit" property by seeing if the nullary
1284 // selector is implemented.
1285
1286 // FIXME: The logic for looking up nullary and unary selectors should be
1287 // shared with the code in ActOnInstanceMessage.
1288
1289 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1290 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1291
1292 // If this reference is in an @implementation, check for 'private' methods.
1293 if (!Getter)
1294 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1295 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1296 if (ObjCImplementationDecl *ImpDecl =
1297 ObjCImplementations[ClassDecl->getIdentifier()])
1298 Getter = ImpDecl->getInstanceMethod(Sel);
1299
Steve Naroff04151f32008-10-22 19:16:27 +00001300 // Look through local category implementations associated with the class.
1301 if (!Getter) {
1302 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1303 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1304 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1305 }
1306 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001307 if (Getter) {
1308 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001309 // will look for the matching setter, in case it is needed.
1310 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1311 &Member);
1312 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1313 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1314 if (!Setter) {
1315 // If this reference is in an @implementation, also check for 'private'
1316 // methods.
1317 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1318 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1319 if (ObjCImplementationDecl *ImpDecl =
1320 ObjCImplementations[ClassDecl->getIdentifier()])
1321 Setter = ImpDecl->getInstanceMethod(SetterSel);
1322 }
1323 // Look through local category implementations associated with the class.
1324 if (!Setter) {
1325 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1326 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1327 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1328 }
1329 }
1330
1331 // FIXME: we must check that the setter has property type.
1332 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00001333 MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001334 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001335 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001336 // Handle properties on qualified "id" protocols.
1337 const ObjCQualifiedIdType *QIdTy;
1338 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1339 // Check protocols on qualified interfaces.
1340 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001341 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001342 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1343 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001344 // Also must look for a getter name which uses property syntax.
1345 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1346 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1347 return new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(), OMD,
1348 OpLoc, MemberLoc, NULL, 0);
1349 }
1350 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001351 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001352 // Handle 'field access' to vectors, such as 'V.xx'.
1353 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1354 // Component access limited to variables (reject vec4.rg.g).
1355 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1356 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001357 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1358 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001359 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1360 if (ret.isNull())
1361 return true;
1362 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1363 }
1364
Chris Lattner8ba580c2008-11-19 05:08:23 +00001365 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001366 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001367}
1368
Steve Naroff87d58b42007-09-16 03:34:24 +00001369/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001370/// This provides the location of the left/right parens and a list of comma
1371/// locations.
1372Action::ExprResult Sema::
Douglas Gregora133e262008-12-06 00:22:45 +00001373ActOnCallExpr(Scope *S, ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001374 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001375 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1376 Expr *Fn = static_cast<Expr *>(fn);
1377 Expr **Args = reinterpret_cast<Expr**>(args);
1378 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001379 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001380 OverloadedFunctionDecl *Ovl = NULL;
1381
Douglas Gregora133e262008-12-06 00:22:45 +00001382 // Determine whether this is a dependent call inside a C++ template,
1383 // in which case we won't do any semantic analysis now.
1384 bool Dependent = false;
1385 if (Fn->isTypeDependent()) {
1386 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1387 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1388 Dependent = true;
1389 else {
1390 // Resolve the CXXDependentNameExpr to an actual identifier;
1391 // it wasn't really a dependent name after all.
1392 ExprResult Resolved
1393 = ActOnDeclarationNameExpr(S, FnName->getLocation(), FnName->getName(),
1394 /*HasTrailingLParen=*/true,
1395 /*SS=*/0,
1396 /*ForceResolution=*/true);
1397 if (Resolved.isInvalid)
1398 return true;
1399 else {
1400 delete Fn;
1401 Fn = (Expr *)Resolved.Val;
1402 }
1403 }
1404 } else
1405 Dependent = true;
1406 } else
1407 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1408
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001409 // FIXME: Will need to cache the results of name lookup (including
1410 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001411 if (Dependent)
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001412 return new CallExpr(Fn, Args, NumArgs, Context.DependentTy, RParenLoc);
1413
Douglas Gregord2baafd2008-10-21 16:13:35 +00001414 // If we're directly calling a function or a set of overloaded
1415 // functions, get the appropriate declaration.
1416 {
1417 DeclRefExpr *DRExpr = NULL;
1418 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1419 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1420 else
1421 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1422
1423 if (DRExpr) {
1424 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1425 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1426 }
1427 }
1428
Douglas Gregord2baafd2008-10-21 16:13:35 +00001429 if (Ovl) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001430 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1431 RParenLoc);
1432 if (!FDecl)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001433 return true;
1434
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001435 // Update Fn to refer to the actual function selected.
1436 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1437 Fn->getSourceRange().getBegin());
1438 Fn->Destroy(Context);
1439 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001440 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001441
Douglas Gregor10f3c502008-11-19 21:05:33 +00001442 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Douglas Gregora133e262008-12-06 00:22:45 +00001443 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregor10f3c502008-11-19 21:05:33 +00001444 CommaLocs, RParenLoc);
1445
Chris Lattner3e254fb2008-04-08 04:40:51 +00001446 // Promote the function operand.
1447 UsualUnaryConversions(Fn);
1448
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001449 // Make the call expr early, before semantic checks. This guarantees cleanup
1450 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001451 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001452 Context.BoolTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001453
Steve Naroffd6163f32008-09-05 22:11:13 +00001454 const FunctionType *FuncT;
1455 if (!Fn->getType()->isBlockPointerType()) {
1456 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1457 // have type pointer to function".
1458 const PointerType *PT = Fn->getType()->getAsPointerType();
1459 if (PT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001460 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001461 << Fn->getType() << Fn->getSourceRange();
Steve Naroffd6163f32008-09-05 22:11:13 +00001462 FuncT = PT->getPointeeType()->getAsFunctionType();
1463 } else { // This is a block call.
1464 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1465 getAsFunctionType();
1466 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001467 if (FuncT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001468 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001469 << Fn->getType() << Fn->getSourceRange();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001470
1471 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001472 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001473
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001474 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001475 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1476 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001477 unsigned NumArgsInProto = Proto->getNumArgs();
1478 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001479
Chris Lattner3e254fb2008-04-08 04:40:51 +00001480 // If too few arguments are available (and we don't have default
1481 // arguments for the remaining parameters), don't make the call.
1482 if (NumArgs < NumArgsInProto) {
Chris Lattner66beaba2008-11-21 18:44:24 +00001483 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1484 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1485 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1486 // Use default arguments for missing arguments
1487 NumArgsToCheck = NumArgsInProto;
1488 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001489 }
1490
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001491 // If too many are passed and not variadic, error on the extras and drop
1492 // them.
1493 if (NumArgs > NumArgsInProto) {
1494 if (!Proto->isVariadic()) {
Chris Lattner66beaba2008-11-21 18:44:24 +00001495 Diag(Args[NumArgsInProto]->getLocStart(),
1496 diag::err_typecheck_call_too_many_args)
1497 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
Chris Lattner8ba580c2008-11-19 05:08:23 +00001498 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1499 Args[NumArgs-1]->getLocEnd());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001500 // This deletes the extra arguments.
1501 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001502 }
1503 NumArgsToCheck = NumArgsInProto;
1504 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001505
Chris Lattner4b009652007-07-25 00:24:17 +00001506 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001507 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001508 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001509
1510 Expr *Arg;
1511 if (i < NumArgs)
1512 Arg = Args[i];
1513 else
1514 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001515 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001516
Douglas Gregor81c29152008-10-29 00:13:59 +00001517 // Pass the argument.
1518 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner005ed752008-01-04 18:04:52 +00001519 return true;
Douglas Gregor81c29152008-10-29 00:13:59 +00001520
1521 TheCall->setArg(i, Arg);
Chris Lattner4b009652007-07-25 00:24:17 +00001522 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001523
1524 // If this is a variadic call, handle args passed through "...".
1525 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001526 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001527 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1528 Expr *Arg = Args[i];
1529 DefaultArgumentPromotion(Arg);
1530 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001531 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001532 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001533 } else {
1534 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1535
Steve Naroffdb65e052007-08-28 23:30:39 +00001536 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001537 for (unsigned i = 0; i != NumArgs; i++) {
1538 Expr *Arg = Args[i];
1539 DefaultArgumentPromotion(Arg);
1540 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001541 }
Chris Lattner4b009652007-07-25 00:24:17 +00001542 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001543
Chris Lattner2e64c072007-08-10 20:18:51 +00001544 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001545 if (FDecl)
1546 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001547
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001548 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001549}
1550
1551Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001552ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001553 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001554 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001555 QualType literalType = QualType::getFromOpaquePtr(Ty);
1556 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001557 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001558 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001559
Eli Friedman8c2173d2008-05-20 05:22:08 +00001560 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001561 if (literalType->isVariableArrayType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001562 return Diag(LParenLoc, diag::err_variable_object_no_init)
1563 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001564 } else if (literalType->isIncompleteType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001565 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +00001566 << literalType
Chris Lattner8ba580c2008-11-19 05:08:23 +00001567 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001568 }
1569
Douglas Gregor6428e762008-11-05 15:29:30 +00001570 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Chris Lattner271d4c22008-11-24 05:29:24 +00001571 DeclarationName()))
Steve Naroff92590f92008-01-09 20:58:06 +00001572 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001573
Chris Lattnere5cb5862008-12-04 23:50:19 +00001574 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001575 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001576 if (CheckForConstantInitializer(literalExpr, literalType))
1577 return true;
1578 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001579 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1580 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001581}
1582
1583Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001584ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001585 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001586 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001587 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001588
Steve Naroff0acc9c92007-09-15 18:49:24 +00001589 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001590 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001591
Chris Lattner71ca8c82008-10-26 23:43:26 +00001592 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1593 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001594 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1595 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001596}
1597
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001598/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001599bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001600 UsualUnaryConversions(castExpr);
1601
1602 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1603 // type needs to be scalar.
1604 if (castType->isVoidType()) {
1605 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001606 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1607 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001608 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1609 // GCC struct/union extension: allow cast to self.
1610 if (Context.getCanonicalType(castType) !=
1611 Context.getCanonicalType(castExpr->getType()) ||
1612 (!castType->isStructureType() && !castType->isUnionType())) {
1613 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001614 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001615 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001616 }
1617
1618 // accept this, but emit an ext-warn.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001619 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001620 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001621 } else if (!castExpr->getType()->isScalarType() &&
1622 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001623 return Diag(castExpr->getLocStart(),
1624 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001625 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001626 } else if (castExpr->getType()->isVectorType()) {
1627 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1628 return true;
1629 } else if (castType->isVectorType()) {
1630 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1631 return true;
1632 }
1633 return false;
1634}
1635
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001636bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001637 assert(VectorTy->isVectorType() && "Not a vector type!");
1638
1639 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001640 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001641 return Diag(R.getBegin(),
1642 Ty->isVectorType() ?
1643 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00001644 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001645 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001646 } else
1647 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001648 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001649 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001650
1651 return false;
1652}
1653
Chris Lattner4b009652007-07-25 00:24:17 +00001654Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001655ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001656 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001657 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001658
1659 Expr *castExpr = static_cast<Expr*>(Op);
1660 QualType castType = QualType::getFromOpaquePtr(Ty);
1661
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001662 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1663 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00001664 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001665}
1666
Chris Lattner98a425c2007-11-26 01:40:58 +00001667/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1668/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001669inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1670 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1671 UsualUnaryConversions(cond);
1672 UsualUnaryConversions(lex);
1673 UsualUnaryConversions(rex);
1674 QualType condT = cond->getType();
1675 QualType lexT = lex->getType();
1676 QualType rexT = rex->getType();
1677
1678 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001679 if (!cond->isTypeDependent()) {
1680 if (!condT->isScalarType()) { // C99 6.5.15p2
1681 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
1682 return QualType();
1683 }
Chris Lattner4b009652007-07-25 00:24:17 +00001684 }
Chris Lattner992ae932008-01-06 22:42:25 +00001685
1686 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001687 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
1688 return Context.DependentTy;
1689
Chris Lattner992ae932008-01-06 22:42:25 +00001690 // If both operands have arithmetic type, do the usual arithmetic conversions
1691 // to find a common type: C99 6.5.15p3,5.
1692 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001693 UsualArithmeticConversions(lex, rex);
1694 return lex->getType();
1695 }
Chris Lattner992ae932008-01-06 22:42:25 +00001696
1697 // If both operands are the same structure or union type, the result is that
1698 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001699 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001700 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001701 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001702 // "If both the operands have structure or union type, the result has
1703 // that type." This implies that CV qualifiers are dropped.
1704 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001705 }
Chris Lattner992ae932008-01-06 22:42:25 +00001706
1707 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001708 // The following || allows only one side to be void (a GCC-ism).
1709 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001710 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001711 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
1712 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00001713 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001714 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
1715 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00001716 ImpCastExprToType(lex, Context.VoidTy);
1717 ImpCastExprToType(rex, Context.VoidTy);
1718 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001719 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001720 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1721 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001722 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1723 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001724 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001725 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001726 return lexT;
1727 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001728 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1729 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001730 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001731 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001732 return rexT;
1733 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001734 // Handle the case where both operands are pointers before we handle null
1735 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001736 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1737 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1738 // get the "pointed to" types
1739 QualType lhptee = LHSPT->getPointeeType();
1740 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001741
Chris Lattner71225142007-07-31 21:27:01 +00001742 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1743 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001744 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001745 // Figure out necessary qualifiers (C99 6.5.15p6)
1746 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001747 QualType destType = Context.getPointerType(destPointee);
1748 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1749 ImpCastExprToType(rex, destType); // promote to void*
1750 return destType;
1751 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001752 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001753 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001754 QualType destType = Context.getPointerType(destPointee);
1755 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1756 ImpCastExprToType(rex, destType); // promote to void*
1757 return destType;
1758 }
Chris Lattner4b009652007-07-25 00:24:17 +00001759
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001760 QualType compositeType = lexT;
1761
1762 // If either type is an Objective-C object type then check
1763 // compatibility according to Objective-C.
1764 if (Context.isObjCObjectPointerType(lexT) ||
1765 Context.isObjCObjectPointerType(rexT)) {
1766 // If both operands are interfaces and either operand can be
1767 // assigned to the other, use that type as the composite
1768 // type. This allows
1769 // xxx ? (A*) a : (B*) b
1770 // where B is a subclass of A.
1771 //
1772 // Additionally, as for assignment, if either type is 'id'
1773 // allow silent coercion. Finally, if the types are
1774 // incompatible then make sure to use 'id' as the composite
1775 // type so the result is acceptable for sending messages to.
1776
1777 // FIXME: This code should not be localized to here. Also this
1778 // should use a compatible check instead of abusing the
1779 // canAssignObjCInterfaces code.
1780 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1781 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1782 if (LHSIface && RHSIface &&
1783 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1784 compositeType = lexT;
1785 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00001786 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001787 compositeType = rexT;
1788 } else if (Context.isObjCIdType(lhptee) ||
1789 Context.isObjCIdType(rhptee)) {
1790 // FIXME: This code looks wrong, because isObjCIdType checks
1791 // the struct but getObjCIdType returns the pointer to
1792 // struct. This is horrible and should be fixed.
1793 compositeType = Context.getObjCIdType();
1794 } else {
1795 QualType incompatTy = Context.getObjCIdType();
1796 ImpCastExprToType(lex, incompatTy);
1797 ImpCastExprToType(rex, incompatTy);
1798 return incompatTy;
1799 }
1800 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1801 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00001802 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001803 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001804 // In this situation, we assume void* type. No especially good
1805 // reason, but this is what gcc does, and we do have to pick
1806 // to get a consistent AST.
1807 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001808 ImpCastExprToType(lex, incompatTy);
1809 ImpCastExprToType(rex, incompatTy);
1810 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001811 }
1812 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001813 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1814 // differently qualified versions of compatible types, the result type is
1815 // a pointer to an appropriately qualified version of the *composite*
1816 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001817 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001818 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001819 ImpCastExprToType(lex, compositeType);
1820 ImpCastExprToType(rex, compositeType);
1821 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001822 }
Chris Lattner4b009652007-07-25 00:24:17 +00001823 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001824 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1825 // evaluates to "struct objc_object *" (and is handled above when comparing
1826 // id with statically typed objects).
1827 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1828 // GCC allows qualified id and any Objective-C type to devolve to
1829 // id. Currently localizing to here until clear this should be
1830 // part of ObjCQualifiedIdTypesAreCompatible.
1831 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1832 (lexT->isObjCQualifiedIdType() &&
1833 Context.isObjCObjectPointerType(rexT)) ||
1834 (rexT->isObjCQualifiedIdType() &&
1835 Context.isObjCObjectPointerType(lexT))) {
1836 // FIXME: This is not the correct composite type. This only
1837 // happens to work because id can more or less be used anywhere,
1838 // however this may change the type of method sends.
1839 // FIXME: gcc adds some type-checking of the arguments and emits
1840 // (confusing) incompatible comparison warnings in some
1841 // cases. Investigate.
1842 QualType compositeType = Context.getObjCIdType();
1843 ImpCastExprToType(lex, compositeType);
1844 ImpCastExprToType(rex, compositeType);
1845 return compositeType;
1846 }
1847 }
1848
Steve Naroff3eac7692008-09-10 19:17:48 +00001849 // Selection between block pointer types is ok as long as they are the same.
1850 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1851 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1852 return lexT;
1853
Chris Lattner992ae932008-01-06 22:42:25 +00001854 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00001855 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001856 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001857 return QualType();
1858}
1859
Steve Naroff87d58b42007-09-16 03:34:24 +00001860/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001861/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001862Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001863 SourceLocation ColonLoc,
1864 ExprTy *Cond, ExprTy *LHS,
1865 ExprTy *RHS) {
1866 Expr *CondExpr = (Expr *) Cond;
1867 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001868
1869 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1870 // was the condition.
1871 bool isLHSNull = LHSExpr == 0;
1872 if (isLHSNull)
1873 LHSExpr = CondExpr;
1874
Chris Lattner4b009652007-07-25 00:24:17 +00001875 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1876 RHSExpr, QuestionLoc);
1877 if (result.isNull())
1878 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001879 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1880 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001881}
1882
Chris Lattner4b009652007-07-25 00:24:17 +00001883
1884// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1885// being closely modeled after the C99 spec:-). The odd characteristic of this
1886// routine is it effectively iqnores the qualifiers on the top level pointee.
1887// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1888// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001889Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001890Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1891 QualType lhptee, rhptee;
1892
1893 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001894 lhptee = lhsType->getAsPointerType()->getPointeeType();
1895 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001896
1897 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001898 lhptee = Context.getCanonicalType(lhptee);
1899 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001900
Chris Lattner005ed752008-01-04 18:04:52 +00001901 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001902
1903 // C99 6.5.16.1p1: This following citation is common to constraints
1904 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1905 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001906 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001907 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001908 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001909
1910 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1911 // incomplete type and the other is a pointer to a qualified or unqualified
1912 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001913 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001914 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001915 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001916
1917 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001918 assert(rhptee->isFunctionType());
1919 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001920 }
1921
1922 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001923 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001924 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001925
1926 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001927 assert(lhptee->isFunctionType());
1928 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001929 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001930
1931 // Check for ObjC interfaces
1932 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1933 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1934 if (LHSIface && RHSIface &&
1935 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1936 return ConvTy;
1937
1938 // ID acts sort of like void* for ObjC interfaces
1939 if (LHSIface && Context.isObjCIdType(rhptee))
1940 return ConvTy;
1941 if (RHSIface && Context.isObjCIdType(lhptee))
1942 return ConvTy;
1943
Chris Lattner4b009652007-07-25 00:24:17 +00001944 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1945 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001946 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1947 rhptee.getUnqualifiedType()))
1948 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001949 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001950}
1951
Steve Naroff3454b6c2008-09-04 15:10:53 +00001952/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1953/// block pointer types are compatible or whether a block and normal pointer
1954/// are compatible. It is more restrict than comparing two function pointer
1955// types.
1956Sema::AssignConvertType
1957Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1958 QualType rhsType) {
1959 QualType lhptee, rhptee;
1960
1961 // get the "pointed to" type (ignoring qualifiers at the top level)
1962 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1963 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1964
1965 // make sure we operate on the canonical type
1966 lhptee = Context.getCanonicalType(lhptee);
1967 rhptee = Context.getCanonicalType(rhptee);
1968
1969 AssignConvertType ConvTy = Compatible;
1970
1971 // For blocks we enforce that qualifiers are identical.
1972 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1973 ConvTy = CompatiblePointerDiscardsQualifiers;
1974
1975 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1976 return IncompatibleBlockPointer;
1977 return ConvTy;
1978}
1979
Chris Lattner4b009652007-07-25 00:24:17 +00001980/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1981/// has code to accommodate several GCC extensions when type checking
1982/// pointers. Here are some objectionable examples that GCC considers warnings:
1983///
1984/// int a, *pint;
1985/// short *pshort;
1986/// struct foo *pfoo;
1987///
1988/// pint = pshort; // warning: assignment from incompatible pointer type
1989/// a = pint; // warning: assignment makes integer from pointer without a cast
1990/// pint = a; // warning: assignment makes pointer from integer without a cast
1991/// pint = pfoo; // warning: assignment from incompatible pointer type
1992///
1993/// As a result, the code for dealing with pointers is more complex than the
1994/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001995///
Chris Lattner005ed752008-01-04 18:04:52 +00001996Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001997Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001998 // Get canonical types. We're not formatting these types, just comparing
1999 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002000 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2001 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002002
2003 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002004 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002005
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002006 // If the left-hand side is a reference type, then we are in a
2007 // (rare!) case where we've allowed the use of references in C,
2008 // e.g., as a parameter type in a built-in function. In this case,
2009 // just make sure that the type referenced is compatible with the
2010 // right-hand side type. The caller is responsible for adjusting
2011 // lhsType so that the resulting expression does not have reference
2012 // type.
2013 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2014 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002015 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002016 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002017 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002018
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002019 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2020 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002021 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002022 // Relax integer conversions like we do for pointers below.
2023 if (rhsType->isIntegerType())
2024 return IntToPointer;
2025 if (lhsType->isIntegerType())
2026 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002027 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002028 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002029
Nate Begemanc5f0f652008-07-14 18:02:46 +00002030 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002031 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002032 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2033 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002034 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002035
Nate Begemanc5f0f652008-07-14 18:02:46 +00002036 // If we are allowing lax vector conversions, and LHS and RHS are both
2037 // vectors, the total size only needs to be the same. This is a bitcast;
2038 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002039 if (getLangOptions().LaxVectorConversions &&
2040 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002041 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2042 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002043 }
2044 return Incompatible;
2045 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002046
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002047 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002048 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002049
Chris Lattner390564e2008-04-07 06:49:41 +00002050 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002051 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002052 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002053
Chris Lattner390564e2008-04-07 06:49:41 +00002054 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002055 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002056
Steve Naroffa982c712008-09-29 18:10:17 +00002057 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002058 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002059 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002060
2061 // Treat block pointers as objects.
2062 if (getLangOptions().ObjC1 &&
2063 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2064 return Compatible;
2065 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002066 return Incompatible;
2067 }
2068
2069 if (isa<BlockPointerType>(lhsType)) {
2070 if (rhsType->isIntegerType())
2071 return IntToPointer;
2072
Steve Naroffa982c712008-09-29 18:10:17 +00002073 // Treat block pointers as objects.
2074 if (getLangOptions().ObjC1 &&
2075 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2076 return Compatible;
2077
Steve Naroff3454b6c2008-09-04 15:10:53 +00002078 if (rhsType->isBlockPointerType())
2079 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2080
2081 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2082 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002083 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002084 }
Chris Lattner1853da22008-01-04 23:18:45 +00002085 return Incompatible;
2086 }
2087
Chris Lattner390564e2008-04-07 06:49:41 +00002088 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002089 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002090 if (lhsType == Context.BoolTy)
2091 return Compatible;
2092
2093 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002094 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002095
Chris Lattner390564e2008-04-07 06:49:41 +00002096 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002097 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002098
2099 if (isa<BlockPointerType>(lhsType) &&
2100 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002101 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002102 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002103 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002104
Chris Lattner1853da22008-01-04 23:18:45 +00002105 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002106 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002107 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002108 }
2109 return Incompatible;
2110}
2111
Chris Lattner005ed752008-01-04 18:04:52 +00002112Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002113Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002114 if (getLangOptions().CPlusPlus) {
2115 if (!lhsType->isRecordType()) {
2116 // C++ 5.17p3: If the left operand is not of class type, the
2117 // expression is implicitly converted (C++ 4) to the
2118 // cv-unqualified type of the left operand.
Douglas Gregorbb461502008-10-24 04:54:22 +00002119 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002120 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002121 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002122 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002123 }
2124
2125 // FIXME: Currently, we fall through and treat C++ classes like C
2126 // structures.
2127 }
2128
Steve Naroffcdee22d2007-11-27 17:58:44 +00002129 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2130 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002131 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2132 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002133 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002134 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002135 return Compatible;
2136 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002137
2138 // We don't allow conversion of non-null-pointer constants to integers.
2139 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2140 return IntToBlockPointer;
2141
Chris Lattner5f505bf2007-10-16 02:55:40 +00002142 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002143 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002144 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002145 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002146 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002147 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002148 if (!lhsType->isReferenceType())
2149 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002150
Chris Lattner005ed752008-01-04 18:04:52 +00002151 Sema::AssignConvertType result =
2152 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002153
2154 // C99 6.5.16.1p2: The value of the right operand is converted to the
2155 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002156 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2157 // so that we can use references in built-in functions even in C.
2158 // The getNonReferenceType() call makes sure that the resulting expression
2159 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002160 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002161 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002162 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002163}
2164
Chris Lattner005ed752008-01-04 18:04:52 +00002165Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002166Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2167 return CheckAssignmentConstraints(lhsType, rhsType);
2168}
2169
Chris Lattner1eafdea2008-11-18 01:30:42 +00002170QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002171 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002172 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002173 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002174 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002175}
2176
Chris Lattner1eafdea2008-11-18 01:30:42 +00002177inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002178 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002179 // For conversion purposes, we ignore any qualifiers.
2180 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002181 QualType lhsType =
2182 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2183 QualType rhsType =
2184 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002185
Nate Begemanc5f0f652008-07-14 18:02:46 +00002186 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002187 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002188 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002189
Nate Begemanc5f0f652008-07-14 18:02:46 +00002190 // Handle the case of a vector & extvector type of the same size and element
2191 // type. It would be nice if we only had one vector type someday.
2192 if (getLangOptions().LaxVectorConversions)
2193 if (const VectorType *LV = lhsType->getAsVectorType())
2194 if (const VectorType *RV = rhsType->getAsVectorType())
2195 if (LV->getElementType() == RV->getElementType() &&
2196 LV->getNumElements() == RV->getNumElements())
2197 return lhsType->isExtVectorType() ? lhsType : rhsType;
2198
2199 // If the lhs is an extended vector and the rhs is a scalar of the same type
2200 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002201 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002202 QualType eltType = V->getElementType();
2203
2204 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2205 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2206 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002207 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002208 return lhsType;
2209 }
2210 }
2211
Nate Begemanc5f0f652008-07-14 18:02:46 +00002212 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002213 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002214 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002215 QualType eltType = V->getElementType();
2216
2217 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2218 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2219 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002220 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002221 return rhsType;
2222 }
2223 }
2224
Chris Lattner4b009652007-07-25 00:24:17 +00002225 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002226 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002227 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002228 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002229 return QualType();
2230}
2231
2232inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002233 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002234{
2235 QualType lhsType = lex->getType(), rhsType = rex->getType();
2236
2237 if (lhsType->isVectorType() || rhsType->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002238 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002239
Steve Naroff8f708362007-08-24 19:07:16 +00002240 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002241
Chris Lattner4b009652007-07-25 00:24:17 +00002242 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002243 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002244 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002245}
2246
2247inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002248 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002249{
2250 QualType lhsType = lex->getType(), rhsType = rex->getType();
2251
Steve Naroff8f708362007-08-24 19:07:16 +00002252 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002253
Chris Lattner4b009652007-07-25 00:24:17 +00002254 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002255 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002256 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002257}
2258
2259inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002260 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002261{
2262 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002263 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002264
Steve Naroff8f708362007-08-24 19:07:16 +00002265 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002266
Chris Lattner4b009652007-07-25 00:24:17 +00002267 // handle the common case first (both operands are arithmetic).
2268 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002269 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002270
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002271 // Put any potential pointer into PExp
2272 Expr* PExp = lex, *IExp = rex;
2273 if (IExp->getType()->isPointerType())
2274 std::swap(PExp, IExp);
2275
2276 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2277 if (IExp->getType()->isIntegerType()) {
2278 // Check for arithmetic on pointers to incomplete types
2279 if (!PTy->getPointeeType()->isObjectType()) {
2280 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002281 Diag(Loc, diag::ext_gnu_void_ptr)
2282 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002283 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002284 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002285 << lex->getType() << lex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002286 return QualType();
2287 }
2288 }
2289 return PExp->getType();
2290 }
2291 }
2292
Chris Lattner1eafdea2008-11-18 01:30:42 +00002293 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002294}
2295
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002296// C99 6.5.6
2297QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002298 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002299 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002300 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002301
Steve Naroff8f708362007-08-24 19:07:16 +00002302 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002303
Chris Lattnerf6da2912007-12-09 21:53:25 +00002304 // Enforce type constraints: C99 6.5.6p3.
2305
2306 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002307 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002308 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002309
2310 // Either ptr - int or ptr - ptr.
2311 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002312 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002313
Chris Lattnerf6da2912007-12-09 21:53:25 +00002314 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002315 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002316 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002317 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002318 Diag(Loc, diag::ext_gnu_void_ptr)
2319 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002320 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002321 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002322 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002323 return QualType();
2324 }
2325 }
2326
2327 // The result type of a pointer-int computation is the pointer type.
2328 if (rex->getType()->isIntegerType())
2329 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002330
Chris Lattnerf6da2912007-12-09 21:53:25 +00002331 // Handle pointer-pointer subtractions.
2332 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002333 QualType rpointee = RHSPTy->getPointeeType();
2334
Chris Lattnerf6da2912007-12-09 21:53:25 +00002335 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002336 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002337 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002338 if (rpointee->isVoidType()) {
2339 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002340 Diag(Loc, diag::ext_gnu_void_ptr)
2341 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002342 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002343 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002344 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002345 return QualType();
2346 }
2347 }
2348
2349 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002350 if (!Context.typesAreCompatible(
2351 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2352 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002353 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002354 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002355 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002356 return QualType();
2357 }
2358
2359 return Context.getPointerDiffType();
2360 }
2361 }
2362
Chris Lattner1eafdea2008-11-18 01:30:42 +00002363 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002364}
2365
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002366// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002367QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002368 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002369 // C99 6.5.7p2: Each of the operands shall have integer type.
2370 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002371 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002372
Chris Lattner2c8bff72007-12-12 05:47:28 +00002373 // Shifts don't perform usual arithmetic conversions, they just do integer
2374 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002375 if (!isCompAssign)
2376 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002377 UsualUnaryConversions(rex);
2378
2379 // "The type of the result is that of the promoted left operand."
2380 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002381}
2382
Eli Friedman0d9549b2008-08-22 00:56:42 +00002383static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2384 ASTContext& Context) {
2385 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2386 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2387 // ID acts sort of like void* for ObjC interfaces
2388 if (LHSIface && Context.isObjCIdType(RHS))
2389 return true;
2390 if (RHSIface && Context.isObjCIdType(LHS))
2391 return true;
2392 if (!LHSIface || !RHSIface)
2393 return false;
2394 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2395 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2396}
2397
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002398// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002399QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002400 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002401 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002402 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002403
Chris Lattner254f3bc2007-08-26 01:18:55 +00002404 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002405 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2406 UsualArithmeticConversions(lex, rex);
2407 else {
2408 UsualUnaryConversions(lex);
2409 UsualUnaryConversions(rex);
2410 }
Chris Lattner4b009652007-07-25 00:24:17 +00002411 QualType lType = lex->getType();
2412 QualType rType = rex->getType();
2413
Ted Kremenek486509e2007-10-29 17:13:39 +00002414 // For non-floating point types, check for self-comparisons of the form
2415 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2416 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002417 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002418 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2419 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002420 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002421 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002422 }
2423
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002424 // The result of comparisons is 'bool' in C++, 'int' in C.
2425 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2426
Chris Lattner254f3bc2007-08-26 01:18:55 +00002427 if (isRelational) {
2428 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002429 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002430 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002431 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002432 if (lType->isFloatingType()) {
2433 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002434 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002435 }
2436
Chris Lattner254f3bc2007-08-26 01:18:55 +00002437 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002438 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002439 }
Chris Lattner4b009652007-07-25 00:24:17 +00002440
Chris Lattner22be8422007-08-26 01:10:14 +00002441 bool LHSIsNull = lex->isNullPointerConstant(Context);
2442 bool RHSIsNull = rex->isNullPointerConstant(Context);
2443
Chris Lattner254f3bc2007-08-26 01:18:55 +00002444 // All of the following pointer related warnings are GCC extensions, except
2445 // when handling null pointer constants. One day, we can consider making them
2446 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002447 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002448 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002449 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002450 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002451 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002452
Steve Naroff3b435622007-11-13 14:57:38 +00002453 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002454 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2455 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002456 RCanPointeeTy.getUnqualifiedType()) &&
2457 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002458 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002459 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002460 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002461 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002462 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002463 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002464 // Handle block pointer types.
2465 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2466 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2467 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2468
2469 if (!LHSIsNull && !RHSIsNull &&
2470 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002471 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002472 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002473 }
2474 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002475 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002476 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002477 // Allow block pointers to be compared with null pointer constants.
2478 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2479 (lType->isPointerType() && rType->isBlockPointerType())) {
2480 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002481 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002482 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002483 }
2484 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002485 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002486 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002487
Steve Naroff936c4362008-06-03 14:04:54 +00002488 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002489 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002490 const PointerType *LPT = lType->getAsPointerType();
2491 const PointerType *RPT = rType->getAsPointerType();
2492 bool LPtrToVoid = LPT ?
2493 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2494 bool RPtrToVoid = RPT ?
2495 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2496
2497 if (!LPtrToVoid && !RPtrToVoid &&
2498 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002499 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002500 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002501 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002502 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002503 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002504 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002505 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002506 }
Steve Naroff936c4362008-06-03 14:04:54 +00002507 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2508 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002509 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002510 } else {
2511 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002512 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002513 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002514 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002515 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002516 }
Steve Naroff936c4362008-06-03 14:04:54 +00002517 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002518 }
Steve Naroff936c4362008-06-03 14:04:54 +00002519 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2520 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002521 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002522 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002523 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002524 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002525 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002526 }
Steve Naroff936c4362008-06-03 14:04:54 +00002527 if (lType->isIntegerType() &&
2528 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002529 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002530 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002531 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002532 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002533 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002534 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002535 // Handle block pointers.
2536 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2537 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002538 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002539 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002540 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002541 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002542 }
2543 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2544 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002545 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002546 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002547 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002548 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002549 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002550 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002551}
2552
Nate Begemanc5f0f652008-07-14 18:02:46 +00002553/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2554/// operates on extended vector types. Instead of producing an IntTy result,
2555/// like a scalar comparison, a vector comparison produces a vector of integer
2556/// types.
2557QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002558 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002559 bool isRelational) {
2560 // Check to make sure we're operating on vectors of the same type and width,
2561 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002562 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002563 if (vType.isNull())
2564 return vType;
2565
2566 QualType lType = lex->getType();
2567 QualType rType = rex->getType();
2568
2569 // For non-floating point types, check for self-comparisons of the form
2570 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2571 // often indicate logic errors in the program.
2572 if (!lType->isFloatingType()) {
2573 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2574 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2575 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002576 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002577 }
2578
2579 // Check for comparisons of floating point operands using != and ==.
2580 if (!isRelational && lType->isFloatingType()) {
2581 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002582 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002583 }
2584
2585 // Return the type for the comparison, which is the same as vector type for
2586 // integer vectors, or an integer type of identical size and number of
2587 // elements for floating point vectors.
2588 if (lType->isIntegerType())
2589 return lType;
2590
2591 const VectorType *VTy = lType->getAsVectorType();
2592
2593 // FIXME: need to deal with non-32b int / non-64b long long
2594 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2595 if (TypeSize == 32) {
2596 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2597 }
2598 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2599 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2600}
2601
Chris Lattner4b009652007-07-25 00:24:17 +00002602inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002603 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002604{
2605 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002606 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002607
Steve Naroff8f708362007-08-24 19:07:16 +00002608 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002609
2610 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002611 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002612 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002613}
2614
2615inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00002616 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00002617{
2618 UsualUnaryConversions(lex);
2619 UsualUnaryConversions(rex);
2620
Eli Friedmanbea3f842008-05-13 20:16:47 +00002621 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002622 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002623 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002624}
2625
Chris Lattner4c2642c2008-11-18 01:22:49 +00002626/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2627/// emit an error and return true. If so, return false.
2628static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2629 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2630 if (IsLV == Expr::MLV_Valid)
2631 return false;
2632
2633 unsigned Diag = 0;
2634 bool NeedType = false;
2635 switch (IsLV) { // C99 6.5.16p2
2636 default: assert(0 && "Unknown result from isModifiableLvalue!");
2637 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00002638 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002639 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2640 NeedType = true;
2641 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002642 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002643 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2644 NeedType = true;
2645 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00002646 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002647 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2648 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002649 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002650 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2651 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002652 case Expr::MLV_IncompleteType:
2653 case Expr::MLV_IncompleteVoidType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002654 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2655 NeedType = true;
2656 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002657 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002658 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2659 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00002660 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002661 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2662 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00002663 case Expr::MLV_ReadonlyProperty:
2664 Diag = diag::error_readonly_property_assignment;
2665 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00002666 case Expr::MLV_NoSetterProperty:
2667 Diag = diag::error_nosetter_property_assignment;
2668 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002669 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002670
Chris Lattner4c2642c2008-11-18 01:22:49 +00002671 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002672 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002673 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00002674 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002675 return true;
2676}
2677
2678
2679
2680// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00002681QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
2682 SourceLocation Loc,
2683 QualType CompoundType) {
2684 // Verify that LHS is a modifiable lvalue, and emit error if not.
2685 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00002686 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00002687
2688 QualType LHSType = LHS->getType();
2689 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00002690
Chris Lattner005ed752008-01-04 18:04:52 +00002691 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002692 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00002693 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002694 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner34c85082008-08-21 18:04:13 +00002695
2696 // If the RHS is a unary plus or minus, check to see if they = and + are
2697 // right next to each other. If so, the user may have typo'd "x =+ 4"
2698 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002699 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00002700 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2701 RHSCheck = ICE->getSubExpr();
2702 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2703 if ((UO->getOpcode() == UnaryOperator::Plus ||
2704 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00002705 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00002706 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002707 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00002708 Diag(Loc, diag::warn_not_compound_assign)
2709 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
2710 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00002711 }
2712 } else {
2713 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00002714 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00002715 }
Chris Lattner005ed752008-01-04 18:04:52 +00002716
Chris Lattner1eafdea2008-11-18 01:30:42 +00002717 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
2718 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00002719 return QualType();
2720
Chris Lattner4b009652007-07-25 00:24:17 +00002721 // C99 6.5.16p3: The type of an assignment expression is the type of the
2722 // left operand unless the left operand has qualified type, in which case
2723 // it is the unqualified version of the type of the left operand.
2724 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2725 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002726 // C++ 5.17p1: the type of the assignment expression is that of its left
2727 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002728 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002729}
2730
Chris Lattner1eafdea2008-11-18 01:30:42 +00002731// C99 6.5.17
2732QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
2733 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00002734
2735 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002736 DefaultFunctionArrayConversion(RHS);
2737 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002738}
2739
2740/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2741/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Chris Lattnere65182c2008-11-21 07:05:48 +00002742QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc) {
2743 QualType ResType = Op->getType();
2744 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002745
Steve Naroffd30e1932007-08-24 17:20:07 +00002746 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattnere65182c2008-11-21 07:05:48 +00002747 if (ResType->isRealType()) {
2748 // OK!
2749 } else if (const PointerType *PT = ResType->getAsPointerType()) {
2750 // C99 6.5.2.4p2, 6.5.6p2
2751 if (PT->getPointeeType()->isObjectType()) {
2752 // Pointer to object is ok!
2753 } else if (PT->getPointeeType()->isVoidType()) {
2754 // Pointer to void is extension.
2755 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
2756 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +00002757 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002758 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002759 return QualType();
2760 }
Chris Lattnere65182c2008-11-21 07:05:48 +00002761 } else if (ResType->isComplexType()) {
2762 // C99 does not support ++/-- on complex types, we allow as an extension.
2763 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002764 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002765 } else {
2766 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002767 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002768 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002769 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002770 // At this point, we know we have a real, complex or pointer type.
2771 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00002772 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00002773 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00002774 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00002775}
2776
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002777/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002778/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002779/// where the declaration is needed for type checking. We only need to
2780/// handle cases when the expression references a function designator
2781/// or is an lvalue. Here are some examples:
2782/// - &(x) => x
2783/// - &*****f => f for f a function designator.
2784/// - &s.xx => s
2785/// - &s.zz[1].yy -> s, if zz is an array
2786/// - *(x + 1) -> x, if x is an array
2787/// - &"123"[2] -> 0
2788/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002789static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002790 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002791 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002792 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002793 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002794 // Fields cannot be declared with a 'register' storage class.
2795 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002796 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002797 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002798 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002799 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002800 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002801
Douglas Gregord2baafd2008-10-21 16:13:35 +00002802 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002803 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002804 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002805 return 0;
2806 else
2807 return VD;
2808 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002809 case Stmt::UnaryOperatorClass: {
2810 UnaryOperator *UO = cast<UnaryOperator>(E);
2811
2812 switch(UO->getOpcode()) {
2813 case UnaryOperator::Deref: {
2814 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002815 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2816 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2817 if (!VD || VD->getType()->isPointerType())
2818 return 0;
2819 return VD;
2820 }
2821 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002822 }
2823 case UnaryOperator::Real:
2824 case UnaryOperator::Imag:
2825 case UnaryOperator::Extension:
2826 return getPrimaryDecl(UO->getSubExpr());
2827 default:
2828 return 0;
2829 }
2830 }
2831 case Stmt::BinaryOperatorClass: {
2832 BinaryOperator *BO = cast<BinaryOperator>(E);
2833
2834 // Handle cases involving pointer arithmetic. The result of an
2835 // Assign or AddAssign is not an lvalue so they can be ignored.
2836
2837 // (x + n) or (n + x) => x
2838 if (BO->getOpcode() == BinaryOperator::Add) {
2839 if (BO->getLHS()->getType()->isPointerType()) {
2840 return getPrimaryDecl(BO->getLHS());
2841 } else if (BO->getRHS()->getType()->isPointerType()) {
2842 return getPrimaryDecl(BO->getRHS());
2843 }
2844 }
2845
2846 return 0;
2847 }
Chris Lattner4b009652007-07-25 00:24:17 +00002848 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002849 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002850 case Stmt::ImplicitCastExprClass:
2851 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002852 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002853 default:
2854 return 0;
2855 }
2856}
2857
2858/// CheckAddressOfOperand - The operand of & must be either a function
2859/// designator or an lvalue designating an object. If it is an lvalue, the
2860/// object cannot be declared with storage class register or be a bit field.
2861/// Note: The usual conversions are *not* applied to the operand of the &
2862/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00002863/// In C++, the operand might be an overloaded function name, in which case
2864/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00002865QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002866 if (getLangOptions().C99) {
2867 // Implement C99-only parts of addressof rules.
2868 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2869 if (uOp->getOpcode() == UnaryOperator::Deref)
2870 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2871 // (assuming the deref expression is valid).
2872 return uOp->getSubExpr()->getType();
2873 }
2874 // Technically, there should be a check for array subscript
2875 // expressions here, but the result of one is always an lvalue anyway.
2876 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002877 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002878 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002879
2880 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002881 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2882 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00002883 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
2884 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002885 return QualType();
2886 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002887 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2888 if (MemExpr->getMemberDecl()->isBitField()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002889 Diag(OpLoc, diag::err_typecheck_address_of)
2890 << "bit-field" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00002891 return QualType();
2892 }
2893 // Check for Apple extension for accessing vector components.
2894 } else if (isa<ArraySubscriptExpr>(op) &&
2895 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002896 Diag(OpLoc, diag::err_typecheck_address_of)
2897 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00002898 return QualType();
2899 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002900 // We have an lvalue with a decl. Make sure the decl is not declared
2901 // with the register storage-class specifier.
2902 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2903 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002904 Diag(OpLoc, diag::err_typecheck_address_of)
2905 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002906 return QualType();
2907 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00002908 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00002909 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00002910 } else if (isa<FieldDecl>(dcl)) {
2911 // Okay: we can take the address of a field.
2912 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00002913 else
Chris Lattner4b009652007-07-25 00:24:17 +00002914 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002915 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002916
Chris Lattner4b009652007-07-25 00:24:17 +00002917 // If the operand has type "type", the result has type "pointer to type".
2918 return Context.getPointerType(op->getType());
2919}
2920
Chris Lattnerda5c0872008-11-23 09:13:29 +00002921QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
2922 UsualUnaryConversions(Op);
2923 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002924
Chris Lattnerda5c0872008-11-23 09:13:29 +00002925 // Note that per both C89 and C99, this is always legal, even if ptype is an
2926 // incomplete type or void. It would be possible to warn about dereferencing
2927 // a void pointer, but it's completely well-defined, and such a warning is
2928 // unlikely to catch any mistakes.
2929 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00002930 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00002931
Chris Lattner77d52da2008-11-20 06:06:08 +00002932 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002933 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002934 return QualType();
2935}
2936
2937static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2938 tok::TokenKind Kind) {
2939 BinaryOperator::Opcode Opc;
2940 switch (Kind) {
2941 default: assert(0 && "Unknown binop!");
2942 case tok::star: Opc = BinaryOperator::Mul; break;
2943 case tok::slash: Opc = BinaryOperator::Div; break;
2944 case tok::percent: Opc = BinaryOperator::Rem; break;
2945 case tok::plus: Opc = BinaryOperator::Add; break;
2946 case tok::minus: Opc = BinaryOperator::Sub; break;
2947 case tok::lessless: Opc = BinaryOperator::Shl; break;
2948 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2949 case tok::lessequal: Opc = BinaryOperator::LE; break;
2950 case tok::less: Opc = BinaryOperator::LT; break;
2951 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2952 case tok::greater: Opc = BinaryOperator::GT; break;
2953 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2954 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2955 case tok::amp: Opc = BinaryOperator::And; break;
2956 case tok::caret: Opc = BinaryOperator::Xor; break;
2957 case tok::pipe: Opc = BinaryOperator::Or; break;
2958 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2959 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2960 case tok::equal: Opc = BinaryOperator::Assign; break;
2961 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2962 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2963 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2964 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2965 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2966 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2967 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2968 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2969 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2970 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2971 case tok::comma: Opc = BinaryOperator::Comma; break;
2972 }
2973 return Opc;
2974}
2975
2976static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2977 tok::TokenKind Kind) {
2978 UnaryOperator::Opcode Opc;
2979 switch (Kind) {
2980 default: assert(0 && "Unknown unary op!");
2981 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2982 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2983 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2984 case tok::star: Opc = UnaryOperator::Deref; break;
2985 case tok::plus: Opc = UnaryOperator::Plus; break;
2986 case tok::minus: Opc = UnaryOperator::Minus; break;
2987 case tok::tilde: Opc = UnaryOperator::Not; break;
2988 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002989 case tok::kw___real: Opc = UnaryOperator::Real; break;
2990 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2991 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2992 }
2993 return Opc;
2994}
2995
Douglas Gregord7f915e2008-11-06 23:29:22 +00002996/// CreateBuiltinBinOp - Creates a new built-in binary operation with
2997/// operator @p Opc at location @c TokLoc. This routine only supports
2998/// built-in operations; ActOnBinOp handles overloaded operators.
2999Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3000 unsigned Op,
3001 Expr *lhs, Expr *rhs) {
3002 QualType ResultTy; // Result type of the binary operator.
3003 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3004 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3005
3006 switch (Opc) {
3007 default:
3008 assert(0 && "Unknown binary expr!");
3009 case BinaryOperator::Assign:
3010 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3011 break;
3012 case BinaryOperator::Mul:
3013 case BinaryOperator::Div:
3014 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3015 break;
3016 case BinaryOperator::Rem:
3017 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3018 break;
3019 case BinaryOperator::Add:
3020 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3021 break;
3022 case BinaryOperator::Sub:
3023 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3024 break;
3025 case BinaryOperator::Shl:
3026 case BinaryOperator::Shr:
3027 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3028 break;
3029 case BinaryOperator::LE:
3030 case BinaryOperator::LT:
3031 case BinaryOperator::GE:
3032 case BinaryOperator::GT:
3033 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3034 break;
3035 case BinaryOperator::EQ:
3036 case BinaryOperator::NE:
3037 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3038 break;
3039 case BinaryOperator::And:
3040 case BinaryOperator::Xor:
3041 case BinaryOperator::Or:
3042 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3043 break;
3044 case BinaryOperator::LAnd:
3045 case BinaryOperator::LOr:
3046 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3047 break;
3048 case BinaryOperator::MulAssign:
3049 case BinaryOperator::DivAssign:
3050 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3051 if (!CompTy.isNull())
3052 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3053 break;
3054 case BinaryOperator::RemAssign:
3055 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3056 if (!CompTy.isNull())
3057 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3058 break;
3059 case BinaryOperator::AddAssign:
3060 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3061 if (!CompTy.isNull())
3062 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3063 break;
3064 case BinaryOperator::SubAssign:
3065 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3066 if (!CompTy.isNull())
3067 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3068 break;
3069 case BinaryOperator::ShlAssign:
3070 case BinaryOperator::ShrAssign:
3071 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3072 if (!CompTy.isNull())
3073 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3074 break;
3075 case BinaryOperator::AndAssign:
3076 case BinaryOperator::XorAssign:
3077 case BinaryOperator::OrAssign:
3078 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3079 if (!CompTy.isNull())
3080 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3081 break;
3082 case BinaryOperator::Comma:
3083 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3084 break;
3085 }
3086 if (ResultTy.isNull())
3087 return true;
3088 if (CompTy.isNull())
3089 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
3090 else
3091 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
3092}
3093
Chris Lattner4b009652007-07-25 00:24:17 +00003094// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003095Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3096 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00003097 ExprTy *LHS, ExprTy *RHS) {
3098 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3099 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
3100
Steve Naroff87d58b42007-09-16 03:34:24 +00003101 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3102 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003103
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003104 // If either expression is type-dependent, just build the AST.
3105 // FIXME: We'll need to perform some caching of the result of name
3106 // lookup for operator+.
3107 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3108 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3109 return new CompoundAssignOperator(lhs, rhs, Opc, Context.DependentTy,
3110 Context.DependentTy, TokLoc);
3111 else
3112 return new BinaryOperator(lhs, rhs, Opc, Context.DependentTy, TokLoc);
3113 }
3114
Douglas Gregord7f915e2008-11-06 23:29:22 +00003115 if (getLangOptions().CPlusPlus &&
3116 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3117 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003118 // If this is one of the assignment operators, we only perform
3119 // overload resolution if the left-hand side is a class or
3120 // enumeration type (C++ [expr.ass]p3).
3121 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3122 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3123 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3124 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003125
3126 // Determine which overloaded operator we're dealing with.
3127 static const OverloadedOperatorKind OverOps[] = {
3128 OO_Star, OO_Slash, OO_Percent,
3129 OO_Plus, OO_Minus,
3130 OO_LessLess, OO_GreaterGreater,
3131 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3132 OO_EqualEqual, OO_ExclaimEqual,
3133 OO_Amp,
3134 OO_Caret,
3135 OO_Pipe,
3136 OO_AmpAmp,
3137 OO_PipePipe,
3138 OO_Equal, OO_StarEqual,
3139 OO_SlashEqual, OO_PercentEqual,
3140 OO_PlusEqual, OO_MinusEqual,
3141 OO_LessLessEqual, OO_GreaterGreaterEqual,
3142 OO_AmpEqual, OO_CaretEqual,
3143 OO_PipeEqual,
3144 OO_Comma
3145 };
3146 OverloadedOperatorKind OverOp = OverOps[Opc];
3147
Douglas Gregor5ed15042008-11-18 23:14:02 +00003148 // Add the appropriate overloaded operators (C++ [over.match.oper])
3149 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003150 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003151 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003152 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003153
3154 // Perform overload resolution.
3155 OverloadCandidateSet::iterator Best;
3156 switch (BestViableFunction(CandidateSet, Best)) {
3157 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003158 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003159 FunctionDecl *FnDecl = Best->Function;
3160
Douglas Gregor70d26122008-11-12 17:17:38 +00003161 if (FnDecl) {
3162 // We matched an overloaded operator. Build a call to that
3163 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003164
Douglas Gregor70d26122008-11-12 17:17:38 +00003165 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003166 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3167 if (PerformObjectArgumentInitialization(lhs, Method) ||
3168 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3169 "passing"))
3170 return true;
3171 } else {
3172 // Convert the arguments.
3173 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3174 "passing") ||
3175 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3176 "passing"))
3177 return true;
3178 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003179
Douglas Gregor70d26122008-11-12 17:17:38 +00003180 // Determine the result type
3181 QualType ResultTy
3182 = FnDecl->getType()->getAsFunctionType()->getResultType();
3183 ResultTy = ResultTy.getNonReferenceType();
3184
3185 // Build the actual expression node.
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003186 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3187 SourceLocation());
3188 UsualUnaryConversions(FnExpr);
3189
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003190 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregor70d26122008-11-12 17:17:38 +00003191 } else {
3192 // We matched a built-in operator. Convert the arguments, then
3193 // break out so that we will build the appropriate built-in
3194 // operator node.
3195 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
3196 "passing") ||
3197 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
3198 "passing"))
3199 return true;
3200
3201 break;
3202 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003203 }
3204
3205 case OR_No_Viable_Function:
3206 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003207 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003208 break;
3209
3210 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003211 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3212 << BinaryOperator::getOpcodeStr(Opc)
3213 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003214 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3215 return true;
3216 }
3217
Douglas Gregor70d26122008-11-12 17:17:38 +00003218 // Either we found no viable overloaded operator or we matched a
3219 // built-in operator. In either case, fall through to trying to
3220 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003221 }
Chris Lattner4b009652007-07-25 00:24:17 +00003222
Douglas Gregord7f915e2008-11-06 23:29:22 +00003223 // Build a built-in binary operation.
3224 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003225}
3226
3227// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003228Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3229 tok::TokenKind Op, ExprTy *input) {
Chris Lattner4b009652007-07-25 00:24:17 +00003230 Expr *Input = (Expr*)input;
3231 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003232
3233 if (getLangOptions().CPlusPlus &&
3234 (Input->getType()->isRecordType()
3235 || Input->getType()->isEnumeralType())) {
3236 // Determine which overloaded operator we're dealing with.
3237 static const OverloadedOperatorKind OverOps[] = {
3238 OO_None, OO_None,
3239 OO_PlusPlus, OO_MinusMinus,
3240 OO_Amp, OO_Star,
3241 OO_Plus, OO_Minus,
3242 OO_Tilde, OO_Exclaim,
3243 OO_None, OO_None,
3244 OO_None,
3245 OO_None
3246 };
3247 OverloadedOperatorKind OverOp = OverOps[Opc];
3248
3249 // Add the appropriate overloaded operators (C++ [over.match.oper])
3250 // to the candidate set.
3251 OverloadCandidateSet CandidateSet;
3252 if (OverOp != OO_None)
3253 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3254
3255 // Perform overload resolution.
3256 OverloadCandidateSet::iterator Best;
3257 switch (BestViableFunction(CandidateSet, Best)) {
3258 case OR_Success: {
3259 // We found a built-in operator or an overloaded operator.
3260 FunctionDecl *FnDecl = Best->Function;
3261
3262 if (FnDecl) {
3263 // We matched an overloaded operator. Build a call to that
3264 // operator.
3265
3266 // Convert the arguments.
3267 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3268 if (PerformObjectArgumentInitialization(Input, Method))
3269 return true;
3270 } else {
3271 // Convert the arguments.
3272 if (PerformCopyInitialization(Input,
3273 FnDecl->getParamDecl(0)->getType(),
3274 "passing"))
3275 return true;
3276 }
3277
3278 // Determine the result type
3279 QualType ResultTy
3280 = FnDecl->getType()->getAsFunctionType()->getResultType();
3281 ResultTy = ResultTy.getNonReferenceType();
3282
3283 // Build the actual expression node.
3284 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3285 SourceLocation());
3286 UsualUnaryConversions(FnExpr);
3287
3288 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3289 } else {
3290 // We matched a built-in operator. Convert the arguments, then
3291 // break out so that we will build the appropriate built-in
3292 // operator node.
3293 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0],
3294 "passing"))
3295 return true;
3296
3297 break;
3298 }
3299 }
3300
3301 case OR_No_Viable_Function:
3302 // No viable function; fall through to handling this as a
3303 // built-in operator, which will produce an error message for us.
3304 break;
3305
3306 case OR_Ambiguous:
3307 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3308 << UnaryOperator::getOpcodeStr(Opc)
3309 << Input->getSourceRange();
3310 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3311 return true;
3312 }
3313
3314 // Either we found no viable overloaded operator or we matched a
3315 // built-in operator. In either case, fall through to trying to
3316 // build a built-in operation.
3317 }
3318
Chris Lattner4b009652007-07-25 00:24:17 +00003319 QualType resultType;
3320 switch (Opc) {
3321 default:
3322 assert(0 && "Unimplemented unary expr!");
3323 case UnaryOperator::PreInc:
3324 case UnaryOperator::PreDec:
3325 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
3326 break;
3327 case UnaryOperator::AddrOf:
3328 resultType = CheckAddressOfOperand(Input, OpLoc);
3329 break;
3330 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003331 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003332 resultType = CheckIndirectionOperand(Input, OpLoc);
3333 break;
3334 case UnaryOperator::Plus:
3335 case UnaryOperator::Minus:
3336 UsualUnaryConversions(Input);
3337 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003338 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3339 break;
3340 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3341 resultType->isEnumeralType())
3342 break;
3343 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3344 Opc == UnaryOperator::Plus &&
3345 resultType->isPointerType())
3346 break;
3347
Chris Lattner77d52da2008-11-20 06:06:08 +00003348 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003349 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003350 case UnaryOperator::Not: // bitwise complement
3351 UsualUnaryConversions(Input);
3352 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003353 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3354 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3355 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003356 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003357 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003358 else if (!resultType->isIntegerType())
Chris Lattner77d52da2008-11-20 06:06:08 +00003359 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003360 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003361 break;
3362 case UnaryOperator::LNot: // logical negation
3363 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3364 DefaultFunctionArrayConversion(Input);
3365 resultType = Input->getType();
3366 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattner77d52da2008-11-20 06:06:08 +00003367 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003368 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003369 // LNot always has type int. C99 6.5.3.3p5.
3370 resultType = Context.IntTy;
3371 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003372 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003373 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003374 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003375 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003376 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003377 resultType = Input->getType();
3378 break;
3379 }
3380 if (resultType.isNull())
3381 return true;
3382 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3383}
3384
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003385/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3386Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003387 SourceLocation LabLoc,
3388 IdentifierInfo *LabelII) {
3389 // Look up the record for this label identifier.
3390 LabelStmt *&LabelDecl = LabelMap[LabelII];
3391
Daniel Dunbar879788d2008-08-04 16:51:22 +00003392 // If we haven't seen this label yet, create a forward reference. It
3393 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003394 if (LabelDecl == 0)
3395 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3396
3397 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003398 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3399 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003400}
3401
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003402Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003403 SourceLocation RPLoc) { // "({..})"
3404 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3405 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3406 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3407
3408 // FIXME: there are a variety of strange constraints to enforce here, for
3409 // example, it is not possible to goto into a stmt expression apparently.
3410 // More semantic analysis is needed.
3411
3412 // FIXME: the last statement in the compount stmt has its value used. We
3413 // should not warn about it being unused.
3414
3415 // If there are sub stmts in the compound stmt, take the type of the last one
3416 // as the type of the stmtexpr.
3417 QualType Ty = Context.VoidTy;
3418
Chris Lattner200964f2008-07-26 19:51:01 +00003419 if (!Compound->body_empty()) {
3420 Stmt *LastStmt = Compound->body_back();
3421 // If LastStmt is a label, skip down through into the body.
3422 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3423 LastStmt = Label->getSubStmt();
3424
3425 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003426 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003427 }
Chris Lattner4b009652007-07-25 00:24:17 +00003428
3429 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3430}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003431
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003432Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003433 SourceLocation TypeLoc,
3434 TypeTy *argty,
3435 OffsetOfComponent *CompPtr,
3436 unsigned NumComponents,
3437 SourceLocation RPLoc) {
3438 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3439 assert(!ArgTy.isNull() && "Missing type argument!");
3440
3441 // We must have at least one component that refers to the type, and the first
3442 // one is known to be a field designator. Verify that the ArgTy represents
3443 // a struct/union/class.
3444 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003445 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003446
3447 // Otherwise, create a compound literal expression as the base, and
3448 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003449 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003450
Chris Lattnerb37522e2007-08-31 21:49:13 +00003451 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3452 // GCC extension, diagnose them.
3453 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003454 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3455 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003456
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003457 for (unsigned i = 0; i != NumComponents; ++i) {
3458 const OffsetOfComponent &OC = CompPtr[i];
3459 if (OC.isBrackets) {
3460 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003461 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003462 if (!AT) {
3463 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003464 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003465 }
3466
Chris Lattner2af6a802007-08-30 17:59:59 +00003467 // FIXME: C++: Verify that operator[] isn't overloaded.
3468
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003469 // C99 6.5.2.1p1
3470 Expr *Idx = static_cast<Expr*>(OC.U.E);
3471 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003472 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3473 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003474
3475 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3476 continue;
3477 }
3478
3479 const RecordType *RC = Res->getType()->getAsRecordType();
3480 if (!RC) {
3481 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003482 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003483 }
3484
3485 // Get the decl corresponding to this.
3486 RecordDecl *RD = RC->getDecl();
3487 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
3488 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003489 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3490 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003491
3492 // FIXME: C++: Verify that MemberDecl isn't a static field.
3493 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003494 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3495 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003496 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3497 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003498 }
3499
3500 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3501 BuiltinLoc);
3502}
3503
3504
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003505Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003506 TypeTy *arg1, TypeTy *arg2,
3507 SourceLocation RPLoc) {
3508 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3509 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3510
3511 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3512
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003513 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003514}
3515
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003516Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003517 ExprTy *expr1, ExprTy *expr2,
3518 SourceLocation RPLoc) {
3519 Expr *CondExpr = static_cast<Expr*>(cond);
3520 Expr *LHSExpr = static_cast<Expr*>(expr1);
3521 Expr *RHSExpr = static_cast<Expr*>(expr2);
3522
3523 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3524
3525 // The conditional expression is required to be a constant expression.
3526 llvm::APSInt condEval(32);
3527 SourceLocation ExpLoc;
3528 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003529 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3530 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00003531
3532 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3533 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3534 RHSExpr->getType();
3535 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3536}
3537
Steve Naroff52a81c02008-09-03 18:15:37 +00003538//===----------------------------------------------------------------------===//
3539// Clang Extensions.
3540//===----------------------------------------------------------------------===//
3541
3542/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003543void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003544 // Analyze block parameters.
3545 BlockSemaInfo *BSI = new BlockSemaInfo();
3546
3547 // Add BSI to CurBlock.
3548 BSI->PrevBlockInfo = CurBlock;
3549 CurBlock = BSI;
3550
3551 BSI->ReturnType = 0;
3552 BSI->TheScope = BlockScope;
3553
Steve Naroff52059382008-10-10 01:28:17 +00003554 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
3555 PushDeclContext(BSI->TheDecl);
3556}
3557
3558void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003559 // Analyze arguments to block.
3560 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3561 "Not a function declarator!");
3562 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3563
Steve Naroff52059382008-10-10 01:28:17 +00003564 CurBlock->hasPrototype = FTI.hasPrototype;
3565 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003566
3567 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3568 // no arguments, not a function that takes a single void argument.
3569 if (FTI.hasPrototype &&
3570 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3571 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3572 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3573 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003574 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003575 } else if (FTI.hasPrototype) {
3576 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003577 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3578 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003579 }
Steve Naroff52059382008-10-10 01:28:17 +00003580 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3581
3582 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3583 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3584 // If this has an identifier, add it to the scope stack.
3585 if ((*AI)->getIdentifier())
3586 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003587}
3588
3589/// ActOnBlockError - If there is an error parsing a block, this callback
3590/// is invoked to pop the information about the block from the action impl.
3591void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3592 // Ensure that CurBlock is deleted.
3593 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3594
3595 // Pop off CurBlock, handle nested blocks.
3596 CurBlock = CurBlock->PrevBlockInfo;
3597
3598 // FIXME: Delete the ParmVarDecl objects as well???
3599
3600}
3601
3602/// ActOnBlockStmtExpr - This is called when the body of a block statement
3603/// literal was successfully completed. ^(int x){...}
3604Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3605 Scope *CurScope) {
3606 // Ensure that CurBlock is deleted.
3607 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3608 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3609
Steve Naroff52059382008-10-10 01:28:17 +00003610 PopDeclContext();
3611
Steve Naroff52a81c02008-09-03 18:15:37 +00003612 // Pop off CurBlock, handle nested blocks.
3613 CurBlock = CurBlock->PrevBlockInfo;
3614
3615 QualType RetTy = Context.VoidTy;
3616 if (BSI->ReturnType)
3617 RetTy = QualType(BSI->ReturnType, 0);
3618
3619 llvm::SmallVector<QualType, 8> ArgTypes;
3620 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3621 ArgTypes.push_back(BSI->Params[i]->getType());
3622
3623 QualType BlockTy;
3624 if (!BSI->hasPrototype)
3625 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3626 else
3627 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003628 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003629
3630 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003631
Steve Naroff95029d92008-10-08 18:44:00 +00003632 BSI->TheDecl->setBody(Body.take());
3633 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003634}
3635
Nate Begemanbd881ef2008-01-30 20:50:20 +00003636/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003637/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003638/// The number of arguments has already been validated to match the number of
3639/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003640static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3641 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003642 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003643 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003644 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3645 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003646
3647 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003648 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003649 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003650 return true;
3651}
3652
3653Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3654 SourceLocation *CommaLocs,
3655 SourceLocation BuiltinLoc,
3656 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003657 // __builtin_overload requires at least 2 arguments
3658 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003659 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3660 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003661
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003662 // The first argument is required to be a constant expression. It tells us
3663 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003664 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003665 Expr *NParamsExpr = Args[0];
3666 llvm::APSInt constEval(32);
3667 SourceLocation ExpLoc;
3668 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003669 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3670 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003671
3672 // Verify that the number of parameters is > 0
3673 unsigned NumParams = constEval.getZExtValue();
3674 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003675 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3676 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003677 // Verify that we have at least 1 + NumParams arguments to the builtin.
3678 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003679 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3680 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003681
3682 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003683 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003684 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003685 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3686 // UsualUnaryConversions will convert the function DeclRefExpr into a
3687 // pointer to function.
3688 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003689 const FunctionTypeProto *FnType = 0;
3690 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3691 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003692
3693 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3694 // parameters, and the number of parameters must match the value passed to
3695 // the builtin.
3696 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003697 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
3698 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003699
3700 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003701 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003702 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003703 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003704 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003705 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
3706 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00003707 // Remember our match, and continue processing the remaining arguments
3708 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003709 OE = new OverloadExpr(Args, NumArgs, i,
3710 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003711 BuiltinLoc, RParenLoc);
3712 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003713 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003714 // Return the newly created OverloadExpr node, if we succeded in matching
3715 // exactly one of the candidate functions.
3716 if (OE)
3717 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003718
3719 // If we didn't find a matching function Expr in the __builtin_overload list
3720 // the return an error.
3721 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003722 for (unsigned i = 0; i != NumParams; ++i) {
3723 if (i != 0) typeNames += ", ";
3724 typeNames += Args[i+1]->getType().getAsString();
3725 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003726
Chris Lattner77d52da2008-11-20 06:06:08 +00003727 return Diag(BuiltinLoc, diag::err_overload_no_match)
3728 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003729}
3730
Anders Carlsson36760332007-10-15 20:28:48 +00003731Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3732 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003733 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003734 Expr *E = static_cast<Expr*>(expr);
3735 QualType T = QualType::getFromOpaquePtr(type);
3736
3737 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003738
3739 // Get the va_list type
3740 QualType VaListType = Context.getBuiltinVaListType();
3741 // Deal with implicit array decay; for example, on x86-64,
3742 // va_list is an array, but it's supposed to decay to
3743 // a pointer for va_arg.
3744 if (VaListType->isArrayType())
3745 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003746 // Make sure the input expression also decays appropriately.
3747 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003748
3749 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003750 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00003751 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003752 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00003753
3754 // FIXME: Warn if a non-POD type is passed in.
3755
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003756 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003757}
3758
Douglas Gregorad4b3792008-11-29 04:51:27 +00003759Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
3760 // The type of __null will be int or long, depending on the size of
3761 // pointers on the target.
3762 QualType Ty;
3763 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
3764 Ty = Context.IntTy;
3765 else
3766 Ty = Context.LongTy;
3767
3768 return new GNUNullExpr(Ty, TokenLoc);
3769}
3770
Chris Lattner005ed752008-01-04 18:04:52 +00003771bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3772 SourceLocation Loc,
3773 QualType DstType, QualType SrcType,
3774 Expr *SrcExpr, const char *Flavor) {
3775 // Decode the result (notice that AST's are still created for extensions).
3776 bool isInvalid = false;
3777 unsigned DiagKind;
3778 switch (ConvTy) {
3779 default: assert(0 && "Unknown conversion type");
3780 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003781 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003782 DiagKind = diag::ext_typecheck_convert_pointer_int;
3783 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003784 case IntToPointer:
3785 DiagKind = diag::ext_typecheck_convert_int_pointer;
3786 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003787 case IncompatiblePointer:
3788 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3789 break;
3790 case FunctionVoidPointer:
3791 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3792 break;
3793 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003794 // If the qualifiers lost were because we were applying the
3795 // (deprecated) C++ conversion from a string literal to a char*
3796 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3797 // Ideally, this check would be performed in
3798 // CheckPointerTypesForAssignment. However, that would require a
3799 // bit of refactoring (so that the second argument is an
3800 // expression, rather than a type), which should be done as part
3801 // of a larger effort to fix CheckPointerTypesForAssignment for
3802 // C++ semantics.
3803 if (getLangOptions().CPlusPlus &&
3804 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3805 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003806 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3807 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003808 case IntToBlockPointer:
3809 DiagKind = diag::err_int_to_block_pointer;
3810 break;
3811 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003812 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003813 break;
Steve Naroff19608432008-10-14 22:18:38 +00003814 case IncompatibleObjCQualifiedId:
3815 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3816 // it can give a more specific diagnostic.
3817 DiagKind = diag::warn_incompatible_qualified_id;
3818 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003819 case Incompatible:
3820 DiagKind = diag::err_typecheck_convert_incompatible;
3821 isInvalid = true;
3822 break;
3823 }
3824
Chris Lattner271d4c22008-11-24 05:29:24 +00003825 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
3826 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00003827 return isInvalid;
3828}
Anders Carlssond5201b92008-11-30 19:50:32 +00003829
3830bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
3831{
3832 Expr::EvalResult EvalResult;
3833
3834 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
3835 EvalResult.HasSideEffects) {
3836 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
3837
3838 if (EvalResult.Diag) {
3839 // We only show the note if it's not the usual "invalid subexpression"
3840 // or if it's actually in a subexpression.
3841 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
3842 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
3843 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3844 }
3845
3846 return true;
3847 }
3848
3849 if (EvalResult.Diag) {
3850 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
3851 E->getSourceRange();
3852
3853 // Print the reason it's not a constant.
3854 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
3855 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3856 }
3857
3858 if (Result)
3859 *Result = EvalResult.Val.getInt();
3860 return false;
3861}