blob: 3870f0736ec22df8982a444a0dea74c831cbe7e0 [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.
192 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
193 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000194 return lhs;
195 }
196 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
197 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000198 return rhs;
199 }
200 // We have two real floating types, float/complex combos were handled above.
201 // Convert the smaller operand to the bigger result.
202 int result = Context.getFloatingTypeOrder(lhs, rhs);
203
204 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000205 return lhs;
206 }
207 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000208 return rhs;
209 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000210 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000211 }
212 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
213 // Handle GCC complex int extension.
214 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
215 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
216
217 if (lhsComplexInt && rhsComplexInt) {
218 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
219 rhsComplexInt->getElementType()) >= 0) {
220 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000221 return lhs;
222 }
Chris Lattner299b8842008-07-25 21:10:04 +0000223 return rhs;
224 } else if (lhsComplexInt && rhs->isIntegerType()) {
225 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000226 return lhs;
227 } else if (rhsComplexInt && lhs->isIntegerType()) {
228 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000229 return rhs;
230 }
231 }
232 // Finally, we have two differing integer types.
233 // The rules for this case are in C99 6.3.1.8
234 int compare = Context.getIntegerTypeOrder(lhs, rhs);
235 bool lhsSigned = lhs->isSignedIntegerType(),
236 rhsSigned = rhs->isSignedIntegerType();
237 QualType destType;
238 if (lhsSigned == rhsSigned) {
239 // Same signedness; use the higher-ranked type
240 destType = compare >= 0 ? lhs : rhs;
241 } else if (compare != (lhsSigned ? 1 : -1)) {
242 // The unsigned type has greater than or equal rank to the
243 // signed type, so use the unsigned type
244 destType = lhsSigned ? rhs : lhs;
245 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
246 // The two types are different widths; if we are here, that
247 // means the signed type is larger than the unsigned type, so
248 // use the signed type.
249 destType = lhsSigned ? lhs : rhs;
250 } else {
251 // The signed type is higher-ranked than the unsigned type,
252 // but isn't actually any bigger (like unsigned int and long
253 // on most 32-bit systems). Use the unsigned type corresponding
254 // to the signed type.
255 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
256 }
Chris Lattner299b8842008-07-25 21:10:04 +0000257 return destType;
258}
259
260//===----------------------------------------------------------------------===//
261// Semantic Analysis for various Expression Types
262//===----------------------------------------------------------------------===//
263
264
Steve Naroff87d58b42007-09-16 03:34:24 +0000265/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000266/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
267/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
268/// multiple tokens. However, the common case is that StringToks points to one
269/// string.
270///
271Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000272Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000273 assert(NumStringToks && "Must have at least one string!");
274
275 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
276 if (Literal.hadError)
277 return ExprResult(true);
278
279 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
280 for (unsigned i = 0; i != NumStringToks; ++i)
281 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000282
283 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000284 if (Literal.Pascal && Literal.GetStringLength() > 256)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000285 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
286 << SourceRange(StringToks[0].getLocation(),
287 StringToks[NumStringToks-1].getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000288
Chris Lattnera6dcce32008-02-11 00:02:17 +0000289 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000290 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000291 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000292
293 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
294 if (getLangOptions().CPlusPlus)
295 StrTy.addConst();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000296
297 // Get an array type for the string, according to C99 6.4.5. This includes
298 // the nul terminator character as well as the string length for pascal
299 // strings.
300 StrTy = Context.getConstantArrayType(StrTy,
301 llvm::APInt(32, Literal.GetStringLength()+1),
302 ArrayType::Normal, 0);
303
Chris Lattner4b009652007-07-25 00:24:17 +0000304 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
305 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000306 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000307 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000308 StringToks[NumStringToks-1].getLocation());
309}
310
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000311/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
312/// CurBlock to VD should cause it to be snapshotted (as we do for auto
313/// variables defined outside the block) or false if this is not needed (e.g.
314/// for values inside the block or for globals).
315///
316/// FIXME: This will create BlockDeclRefExprs for global variables,
317/// function references, etc which is suboptimal :) and breaks
318/// things like "integer constant expression" tests.
319static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
320 ValueDecl *VD) {
321 // If the value is defined inside the block, we couldn't snapshot it even if
322 // we wanted to.
323 if (CurBlock->TheDecl == VD->getDeclContext())
324 return false;
325
326 // If this is an enum constant or function, it is constant, don't snapshot.
327 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
328 return false;
329
330 // If this is a reference to an extern, static, or global variable, no need to
331 // snapshot it.
332 // FIXME: What about 'const' variables in C++?
333 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
334 return Var->hasLocalStorage();
335
336 return true;
337}
338
339
340
Steve Naroff0acc9c92007-09-15 18:49:24 +0000341/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000342/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000343/// identifier is used in a function call context.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000344/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the
345/// class or namespace that the identifier must be a member of.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000346Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000347 IdentifierInfo &II,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000348 bool HasTrailingLParen,
349 const CXXScopeSpec *SS) {
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000350 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
351}
352
353/// ActOnDeclarationNameExpr - The parser has read some kind of name
354/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
355/// performs lookup on that name and returns an expression that refers
356/// to that name. This routine isn't directly called from the parser,
357/// because the parser doesn't know about DeclarationName. Rather,
358/// this routine is called by ActOnIdentifierExpr,
359/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
360/// which form the DeclarationName from the corresponding syntactic
361/// forms.
362///
363/// HasTrailingLParen indicates whether this identifier is used in a
364/// function call context. LookupCtx is only used for a C++
365/// qualified-id (foo::bar) to indicate the class or namespace that
366/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000367///
368/// If ForceResolution is true, then we will attempt to resolve the
369/// name even if it looks like a dependent name. This option is off by
370/// default.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000371Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
372 DeclarationName Name,
373 bool HasTrailingLParen,
Douglas Gregora133e262008-12-06 00:22:45 +0000374 const CXXScopeSpec *SS,
375 bool ForceResolution) {
376 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
377 HasTrailingLParen && !SS && !ForceResolution) {
378 // We've seen something of the form
379 // identifier(
380 // and we are in a template, so it is likely that 's' is a
381 // dependent name. However, we won't know until we've parsed all
382 // of the call arguments. So, build a CXXDependentNameExpr node
383 // to represent this name. Then, if it turns out that none of the
384 // arguments are type-dependent, we'll force the resolution of the
385 // dependent name at that point.
386 return new CXXDependentNameExpr(Name.getAsIdentifierInfo(),
387 Context.DependentTy, Loc);
388 }
389
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000390 // Could be enum-constant, value decl, instance variable, etc.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000391 Decl *D;
392 if (SS && !SS->isEmpty()) {
393 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
394 if (DC == 0)
395 return true;
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000396 D = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000397 } else
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000398 D = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Douglas Gregora133e262008-12-06 00:22:45 +0000399
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000400 // If this reference is in an Objective-C method, then ivar lookup happens as
401 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000402 IdentifierInfo *II = Name.getAsIdentifierInfo();
403 if (II && getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000404 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000405 // There are two cases to handle here. 1) scoped lookup could have failed,
406 // in which case we should look for an ivar. 2) scoped lookup could have
407 // found a decl, but that decl is outside the current method (i.e. a global
408 // variable). In these two cases, we do a lookup for an ivar with this
409 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000410 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000411 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000412 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000413 // FIXME: This should use a new expr for a direct reference, don't turn
414 // this into Self->ivar, just return a BareIVarExpr or something.
415 IdentifierInfo &II = Context.Idents.get("self");
416 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
417 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
418 static_cast<Expr*>(SelfExpr.Val), true, true);
419 }
420 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000421 // Needed to implement property "super.method" notation.
Chris Lattner87fada82008-11-20 05:35:30 +0000422 if (SD == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000423 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000424 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000425 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000426 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000427 }
Chris Lattner4b009652007-07-25 00:24:17 +0000428 if (D == 0) {
429 // Otherwise, this could be an implicitly declared function reference (legal
430 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000431 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000432 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000433 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000434 else {
435 // If this name wasn't predeclared and if this is not a function call,
436 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000437 if (SS && !SS->isEmpty())
Chris Lattner77d52da2008-11-20 06:06:08 +0000438 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattnerb1753422008-11-23 21:45:46 +0000439 << Name << SS->getRange();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000440 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
441 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000442 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000443 else
Chris Lattnerb1753422008-11-23 21:45:46 +0000444 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000445 }
446 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000447
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000448 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
449 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
450 if (MD->isStatic())
451 // "invalid use of member 'x' in static member function"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000452 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattner271d4c22008-11-24 05:29:24 +0000453 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000454 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
455 // "invalid use of nonstatic data member 'x'"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000456 return Diag(Loc, diag::err_invalid_non_static_member_use)
Chris Lattner271d4c22008-11-24 05:29:24 +0000457 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000458
459 if (FD->isInvalidDecl())
460 return true;
461
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +0000462 // FIXME: Handle 'mutable'.
463 return new DeclRefExpr(FD,
464 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000465 }
466
Chris Lattner271d4c22008-11-24 05:29:24 +0000467 return Diag(Loc, diag::err_invalid_non_static_member_use)
468 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000469 }
Chris Lattner4b009652007-07-25 00:24:17 +0000470 if (isa<TypedefDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000471 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremenek42730c52008-01-07 19:49:32 +0000472 if (isa<ObjCInterfaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000473 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000474 if (isa<NamespaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000475 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000476
Steve Naroffd6163f32008-09-05 22:11:13 +0000477 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000478 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
479 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
480
Steve Naroffd6163f32008-09-05 22:11:13 +0000481 ValueDecl *VD = cast<ValueDecl>(D);
482
483 // check if referencing an identifier with __attribute__((deprecated)).
484 if (VD->getAttr<DeprecatedAttr>())
Chris Lattner271d4c22008-11-24 05:29:24 +0000485 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Douglas Gregor48840c72008-12-10 23:01:14 +0000486
487 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
488 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
489 Scope *CheckS = S;
490 while (CheckS) {
491 if (CheckS->isWithinElse() &&
492 CheckS->getControlParent()->isDeclScope(Var)) {
493 if (Var->getType()->isBooleanType())
494 Diag(Loc, diag::warn_value_always_false) << Var->getDeclName();
495 else
496 Diag(Loc, diag::warn_value_always_zero) << Var->getDeclName();
497 break;
498 }
499
500 // Move up one more control parent to check again.
501 CheckS = CheckS->getControlParent();
502 if (CheckS)
503 CheckS = CheckS->getParent();
504 }
505 }
506 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000507
508 // Only create DeclRefExpr's for valid Decl's.
509 if (VD->isInvalidDecl())
510 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000511
512 // If the identifier reference is inside a block, and it refers to a value
513 // that is outside the block, create a BlockDeclRefExpr instead of a
514 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
515 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000516 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000517 // We do not do this for things like enum constants, global variables, etc,
518 // as they do not get snapshotted.
519 //
520 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000521 // The BlocksAttr indicates the variable is bound by-reference.
522 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000523 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
524 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000525
526 // Variable will be bound by-copy, make it const within the closure.
527 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000528 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
529 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000530 }
531 // If this reference is not in a block or if the referenced variable is
532 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000533
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000534 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000535 bool ValueDependent = false;
536 if (getLangOptions().CPlusPlus) {
537 // C++ [temp.dep.expr]p3:
538 // An id-expression is type-dependent if it contains:
539 // - an identifier that was declared with a dependent type,
540 if (VD->getType()->isDependentType())
541 TypeDependent = true;
542 // - FIXME: a template-id that is dependent,
543 // - a conversion-function-id that specifies a dependent type,
544 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
545 Name.getCXXNameType()->isDependentType())
546 TypeDependent = true;
547 // - a nested-name-specifier that contains a class-name that
548 // names a dependent type.
549 else if (SS && !SS->isEmpty()) {
550 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
551 DC; DC = DC->getParent()) {
552 // FIXME: could stop early at namespace scope.
553 if (DC->isCXXRecord()) {
554 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
555 if (Context.getTypeDeclType(Record)->isDependentType()) {
556 TypeDependent = true;
557 break;
558 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000559 }
560 }
561 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000562
Douglas Gregora5d84612008-12-10 20:57:37 +0000563 // C++ [temp.dep.constexpr]p2:
564 //
565 // An identifier is value-dependent if it is:
566 // - a name declared with a dependent type,
567 if (TypeDependent)
568 ValueDependent = true;
569 // - the name of a non-type template parameter,
570 else if (isa<NonTypeTemplateParmDecl>(VD))
571 ValueDependent = true;
572 // - a constant with integral or enumeration type and is
573 // initialized with an expression that is value-dependent
574 // (FIXME!).
575 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000576
577 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
578 TypeDependent, ValueDependent);
Chris Lattner4b009652007-07-25 00:24:17 +0000579}
580
Chris Lattner69909292008-08-10 01:53:14 +0000581Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000582 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000583 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000584
585 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000586 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000587 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
588 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
589 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000590 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000591
592 // Verify that this is in a function context.
Chris Lattnere5cb5862008-12-04 23:50:19 +0000593 if (getCurFunctionOrMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000594 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000595
Chris Lattner7e637512008-01-12 08:14:25 +0000596 // Pre-defined identifiers are of type char[x], where x is the length of the
597 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000598 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000599 if (FunctionDecl *FD = getCurFunctionDecl())
600 Length = FD->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000601 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000602 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000603
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000604 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000605 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000606 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000607 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000608}
609
Steve Naroff87d58b42007-09-16 03:34:24 +0000610Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000611 llvm::SmallString<16> CharBuffer;
612 CharBuffer.resize(Tok.getLength());
613 const char *ThisTokBegin = &CharBuffer[0];
614 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
615
616 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
617 Tok.getLocation(), PP);
618 if (Literal.hadError())
619 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000620
621 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
622
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000623 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
624 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000625}
626
Steve Naroff87d58b42007-09-16 03:34:24 +0000627Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000628 // fast path for a single digit (which is quite common). A single digit
629 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
630 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000631 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000632
Chris Lattner8cd0e932008-03-05 18:54:05 +0000633 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000634 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000635 Context.IntTy,
636 Tok.getLocation()));
637 }
638 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000639 // Add padding so that NumericLiteralParser can overread by one character.
640 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000641 const char *ThisTokBegin = &IntegerBuffer[0];
642
643 // Get the spelling of the token, which eliminates trigraphs, etc.
644 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000645
Chris Lattner4b009652007-07-25 00:24:17 +0000646 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
647 Tok.getLocation(), PP);
648 if (Literal.hadError)
649 return ExprResult(true);
650
Chris Lattner1de66eb2007-08-26 03:42:43 +0000651 Expr *Res;
652
653 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000654 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000655 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000656 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000657 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000658 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000659 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000660 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000661
662 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
663
Ted Kremenekddedbe22007-11-29 00:56:49 +0000664 // isExact will be set by GetFloatValue().
665 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000666 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000667 Ty, Tok.getLocation());
668
Chris Lattner1de66eb2007-08-26 03:42:43 +0000669 } else if (!Literal.isIntegerLiteral()) {
670 return ExprResult(true);
671 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000672 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000673
Neil Booth7421e9c2007-08-29 22:00:19 +0000674 // long long is a C99 feature.
675 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000676 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000677 Diag(Tok.getLocation(), diag::ext_longlong);
678
Chris Lattner4b009652007-07-25 00:24:17 +0000679 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000680 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000681
682 if (Literal.GetIntegerValue(ResultVal)) {
683 // If this value didn't fit into uintmax_t, warn and force to ull.
684 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000685 Ty = Context.UnsignedLongLongTy;
686 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000687 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000688 } else {
689 // If this value fits into a ULL, try to figure out what else it fits into
690 // according to the rules of C99 6.4.4.1p5.
691
692 // Octal, Hexadecimal, and integers with a U suffix are allowed to
693 // be an unsigned int.
694 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
695
696 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000697 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000698 if (!Literal.isLong && !Literal.isLongLong) {
699 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000700 unsigned IntSize = Context.Target.getIntWidth();
701
Chris Lattner4b009652007-07-25 00:24:17 +0000702 // Does it fit in a unsigned int?
703 if (ResultVal.isIntN(IntSize)) {
704 // Does it fit in a signed int?
705 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000706 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000707 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000708 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000709 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000710 }
Chris Lattner4b009652007-07-25 00:24:17 +0000711 }
712
713 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000714 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000715 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000716
717 // Does it fit in a unsigned long?
718 if (ResultVal.isIntN(LongSize)) {
719 // Does it fit in a signed long?
720 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000721 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000722 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000723 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000724 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000725 }
Chris Lattner4b009652007-07-25 00:24:17 +0000726 }
727
728 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000729 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000730 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000731
732 // Does it fit in a unsigned long long?
733 if (ResultVal.isIntN(LongLongSize)) {
734 // Does it fit in a signed long long?
735 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000736 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000737 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000738 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000739 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000740 }
741 }
742
743 // If we still couldn't decide a type, we probably have something that
744 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000745 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000746 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000747 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000748 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000749 }
Chris Lattnere4068872008-05-09 05:59:00 +0000750
751 if (ResultVal.getBitWidth() != Width)
752 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000753 }
754
Chris Lattner48d7f382008-04-02 04:24:33 +0000755 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000756 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000757
758 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
759 if (Literal.isImaginary)
760 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
761
762 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000763}
764
Steve Naroff87d58b42007-09-16 03:34:24 +0000765Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000766 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000767 Expr *E = (Expr *)Val;
768 assert((E != 0) && "ActOnParenExpr() missing expr");
769 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000770}
771
772/// The UsualUnaryConversions() function is *not* called by this routine.
773/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000774bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
775 SourceLocation OpLoc,
776 const SourceRange &ExprRange,
777 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000778 // C99 6.5.3.4p1:
779 if (isa<FunctionType>(exprType) && isSizeof)
780 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000781 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +0000782 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000783 Diag(OpLoc, diag::ext_sizeof_void_type)
784 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
785 else if (exprType->isIncompleteType())
786 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
787 diag::err_alignof_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000788 << exprType << ExprRange;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000789
790 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000791}
792
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000793/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
794/// the same for @c alignof and @c __alignof
795/// Note that the ArgRange is invalid if isType is false.
796Action::ExprResult
797Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
798 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +0000799 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000800 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000801
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000802 QualType ArgTy;
803 SourceRange Range;
804 if (isType) {
805 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
806 Range = ArgRange;
807 } else {
808 // Get the end location.
809 Expr *ArgEx = (Expr *)TyOrEx;
810 Range = ArgEx->getSourceRange();
811 ArgTy = ArgEx->getType();
812 }
813
814 // Verify that the operand is valid.
815 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +0000816 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000817
818 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
819 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
820 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +0000821}
822
Chris Lattner5110ad52007-08-24 21:41:10 +0000823QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000824 DefaultFunctionArrayConversion(V);
825
Chris Lattnera16e42d2007-08-26 05:39:26 +0000826 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000827 if (const ComplexType *CT = V->getType()->getAsComplexType())
828 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000829
830 // Otherwise they pass through real integer and floating point types here.
831 if (V->getType()->isArithmeticType())
832 return V->getType();
833
834 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +0000835 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000836 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000837}
838
839
Chris Lattner4b009652007-07-25 00:24:17 +0000840
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000841Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000842 tok::TokenKind Kind,
843 ExprTy *Input) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000844 Expr *Arg = (Expr *)Input;
845
Chris Lattner4b009652007-07-25 00:24:17 +0000846 UnaryOperator::Opcode Opc;
847 switch (Kind) {
848 default: assert(0 && "Unknown unary op!");
849 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
850 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
851 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000852
853 if (getLangOptions().CPlusPlus &&
854 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
855 // Which overloaded operator?
856 OverloadedOperatorKind OverOp =
857 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
858
859 // C++ [over.inc]p1:
860 //
861 // [...] If the function is a member function with one
862 // parameter (which shall be of type int) or a non-member
863 // function with two parameters (the second of which shall be
864 // of type int), it defines the postfix increment operator ++
865 // for objects of that type. When the postfix increment is
866 // called as a result of using the ++ operator, the int
867 // argument will have value zero.
868 Expr *Args[2] = {
869 Arg,
870 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
871 /*isSigned=*/true),
872 Context.IntTy, SourceLocation())
873 };
874
875 // Build the candidate set for overloading
876 OverloadCandidateSet CandidateSet;
877 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
878
879 // Perform overload resolution.
880 OverloadCandidateSet::iterator Best;
881 switch (BestViableFunction(CandidateSet, Best)) {
882 case OR_Success: {
883 // We found a built-in operator or an overloaded operator.
884 FunctionDecl *FnDecl = Best->Function;
885
886 if (FnDecl) {
887 // We matched an overloaded operator. Build a call to that
888 // operator.
889
890 // Convert the arguments.
891 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
892 if (PerformObjectArgumentInitialization(Arg, Method))
893 return true;
894 } else {
895 // Convert the arguments.
896 if (PerformCopyInitialization(Arg,
897 FnDecl->getParamDecl(0)->getType(),
898 "passing"))
899 return true;
900 }
901
902 // Determine the result type
903 QualType ResultTy
904 = FnDecl->getType()->getAsFunctionType()->getResultType();
905 ResultTy = ResultTy.getNonReferenceType();
906
907 // Build the actual expression node.
908 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
909 SourceLocation());
910 UsualUnaryConversions(FnExpr);
911
912 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
913 } else {
914 // We matched a built-in operator. Convert the arguments, then
915 // break out so that we will build the appropriate built-in
916 // operator node.
917 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
918 "passing"))
919 return true;
920
921 break;
922 }
923 }
924
925 case OR_No_Viable_Function:
926 // No viable function; fall through to handling this as a
927 // built-in operator, which will produce an error message for us.
928 break;
929
930 case OR_Ambiguous:
931 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
932 << UnaryOperator::getOpcodeStr(Opc)
933 << Arg->getSourceRange();
934 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
935 return true;
936 }
937
938 // Either we found no viable overloaded operator or we matched a
939 // built-in operator. In either case, fall through to trying to
940 // build a built-in operation.
941 }
942
943 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000944 if (result.isNull())
945 return true;
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000946 return new UnaryOperator(Arg, Opc, result, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000947}
948
949Action::ExprResult Sema::
Douglas Gregor80723c52008-11-19 17:17:41 +0000950ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000951 ExprTy *Idx, SourceLocation RLoc) {
952 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
953
Douglas Gregor80723c52008-11-19 17:17:41 +0000954 if (getLangOptions().CPlusPlus &&
955 LHSExp->getType()->isRecordType() ||
956 LHSExp->getType()->isEnumeralType() ||
957 RHSExp->getType()->isRecordType() ||
Sebastian Redle5edfce2008-12-03 16:32:40 +0000958 RHSExp->getType()->isEnumeralType()) {
Douglas Gregor80723c52008-11-19 17:17:41 +0000959 // Add the appropriate overloaded operators (C++ [over.match.oper])
960 // to the candidate set.
961 OverloadCandidateSet CandidateSet;
962 Expr *Args[2] = { LHSExp, RHSExp };
963 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
964
965 // Perform overload resolution.
966 OverloadCandidateSet::iterator Best;
967 switch (BestViableFunction(CandidateSet, Best)) {
968 case OR_Success: {
969 // We found a built-in operator or an overloaded operator.
970 FunctionDecl *FnDecl = Best->Function;
971
972 if (FnDecl) {
973 // We matched an overloaded operator. Build a call to that
974 // operator.
975
976 // Convert the arguments.
977 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
978 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
979 PerformCopyInitialization(RHSExp,
980 FnDecl->getParamDecl(0)->getType(),
981 "passing"))
982 return true;
983 } else {
984 // Convert the arguments.
985 if (PerformCopyInitialization(LHSExp,
986 FnDecl->getParamDecl(0)->getType(),
987 "passing") ||
988 PerformCopyInitialization(RHSExp,
989 FnDecl->getParamDecl(1)->getType(),
990 "passing"))
991 return true;
992 }
993
994 // Determine the result type
995 QualType ResultTy
996 = FnDecl->getType()->getAsFunctionType()->getResultType();
997 ResultTy = ResultTy.getNonReferenceType();
998
999 // Build the actual expression node.
1000 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1001 SourceLocation());
1002 UsualUnaryConversions(FnExpr);
1003
1004 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
1005 } else {
1006 // We matched a built-in operator. Convert the arguments, then
1007 // break out so that we will build the appropriate built-in
1008 // operator node.
1009 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1010 "passing") ||
1011 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1012 "passing"))
1013 return true;
1014
1015 break;
1016 }
1017 }
1018
1019 case OR_No_Viable_Function:
1020 // No viable function; fall through to handling this as a
1021 // built-in operator, which will produce an error message for us.
1022 break;
1023
1024 case OR_Ambiguous:
1025 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1026 << "[]"
1027 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1028 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1029 return true;
1030 }
1031
1032 // Either we found no viable overloaded operator or we matched a
1033 // built-in operator. In either case, fall through to trying to
1034 // build a built-in operation.
1035 }
1036
Chris Lattner4b009652007-07-25 00:24:17 +00001037 // Perform default conversions.
1038 DefaultFunctionArrayConversion(LHSExp);
1039 DefaultFunctionArrayConversion(RHSExp);
1040
1041 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1042
1043 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001044 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001045 // in the subscript position. As a result, we need to derive the array base
1046 // and index from the expression types.
1047 Expr *BaseExpr, *IndexExpr;
1048 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001049 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001050 BaseExpr = LHSExp;
1051 IndexExpr = RHSExp;
1052 // FIXME: need to deal with const...
1053 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001054 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001055 // Handle the uncommon case of "123[Ptr]".
1056 BaseExpr = RHSExp;
1057 IndexExpr = LHSExp;
1058 // FIXME: need to deal with const...
1059 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001060 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1061 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001062 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +00001063
1064 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +00001065 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1066 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001067 return Diag(LLoc, diag::err_ext_vector_component_access)
1068 << SourceRange(LLoc, RLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001069 // FIXME: need to deal with const...
1070 ResultType = VTy->getElementType();
1071 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001072 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
1073 << RHSExp->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001074 }
1075 // C99 6.5.2.1p1
1076 if (!IndexExpr->getType()->isIntegerType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001077 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
1078 << IndexExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001079
1080 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1081 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001082 // void (*)(int)) and pointers to incomplete types. Functions are not
1083 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001084 if (!ResultType->isObjectType())
1085 return Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001086 diag::err_typecheck_subscript_not_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001087 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001088
1089 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
1090}
1091
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001092QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001093CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001094 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001095 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001096
1097 // This flag determines whether or not the component is to be treated as a
1098 // special name, or a regular GLSL-style component access.
1099 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001100
1101 // The vector accessor can't exceed the number of elements.
1102 const char *compStr = CompName.getName();
1103 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001104 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001105 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001106 return QualType();
1107 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001108
1109 // Check that we've found one of the special components, or that the component
1110 // names must come from the same set.
1111 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1112 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1113 SpecialComponent = true;
1114 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001115 do
1116 compStr++;
1117 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1118 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1119 do
1120 compStr++;
1121 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1122 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1123 do
1124 compStr++;
1125 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1126 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001127
Nate Begemanc8e51f82008-05-09 06:41:27 +00001128 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001129 // We didn't get to the end of the string. This means the component names
1130 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001131 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1132 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001133 return QualType();
1134 }
1135 // Each component accessor can't exceed the vector type.
1136 compStr = CompName.getName();
1137 while (*compStr) {
1138 if (vecType->isAccessorWithinNumElements(*compStr))
1139 compStr++;
1140 else
1141 break;
1142 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001143 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001144 // We didn't get to the end of the string. This means a component accessor
1145 // exceeds the number of elements in the vector.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001146 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001147 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001148 return QualType();
1149 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001150
1151 // If we have a special component name, verify that the current vector length
1152 // is an even number, since all special component names return exactly half
1153 // the elements.
1154 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001155 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001156 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001157 return QualType();
1158 }
1159
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001160 // The component accessor looks fine - now we need to compute the actual type.
1161 // The vector type is implied by the component accessor. For example,
1162 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001163 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1164 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner65cae292008-11-19 08:23:25 +00001165 : CompName.getLength();
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001166 if (CompSize == 1)
1167 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001168
Nate Begemanaf6ed502008-04-18 23:10:10 +00001169 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001170 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001171 // diagostics look bad. We want extended vector types to appear built-in.
1172 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1173 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1174 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001175 }
1176 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001177}
1178
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001179/// constructSetterName - Return the setter name for the given
1180/// identifier, i.e. "set" + Name where the initial character of Name
1181/// has been capitalized.
1182// FIXME: Merge with same routine in Parser. But where should this
1183// live?
1184static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1185 const IdentifierInfo *Name) {
1186 llvm::SmallString<100> SelectorName;
1187 SelectorName = "set";
1188 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1189 SelectorName[3] = toupper(SelectorName[3]);
1190 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1191}
1192
Chris Lattner4b009652007-07-25 00:24:17 +00001193Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001194ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001195 tok::TokenKind OpKind, SourceLocation MemberLoc,
1196 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001197 Expr *BaseExpr = static_cast<Expr *>(Base);
1198 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001199
1200 // Perform default conversions.
1201 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +00001202
Steve Naroff2cb66382007-07-26 03:11:44 +00001203 QualType BaseType = BaseExpr->getType();
1204 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001205
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001206 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1207 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001208 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001209 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001210 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001211 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
1212 return BuildOverloadedArrowExpr(BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroff2cb66382007-07-26 03:11:44 +00001213 else
Chris Lattner8ba580c2008-11-19 05:08:23 +00001214 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001215 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001216 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001217
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001218 // Handle field access to simple records. This also handles access to fields
1219 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001220 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001221 RecordDecl *RDecl = RTy->getDecl();
1222 if (RTy->isIncompleteType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001223 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattner271d4c22008-11-24 05:29:24 +00001224 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroff2cb66382007-07-26 03:11:44 +00001225 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001226 FieldDecl *MemberDecl = RDecl->getMember(&Member);
1227 if (!MemberDecl)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001228 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner65cae292008-11-19 08:23:25 +00001229 << &Member << BaseExpr->getSourceRange();
Eli Friedman76b49832008-02-06 22:48:16 +00001230
1231 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +00001232 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +00001233 QualType MemberType = MemberDecl->getType();
1234 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +00001235 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +00001236 if (CXXFieldDecl *CXXMember = dyn_cast<CXXFieldDecl>(MemberDecl)) {
1237 if (CXXMember->isMutable())
1238 combinedQualifiers &= ~QualType::Const;
1239 }
Eli Friedman76b49832008-02-06 22:48:16 +00001240 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1241
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001242 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +00001243 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +00001244 }
1245
Chris Lattnere9d71612008-07-21 04:59:05 +00001246 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1247 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001248 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
1249 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001250 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +00001251 OpKind == tok::arrow);
Chris Lattner8ba580c2008-11-19 05:08:23 +00001252 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattner271d4c22008-11-24 05:29:24 +00001253 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattner8ba580c2008-11-19 05:08:23 +00001254 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001255 }
1256
Chris Lattnere9d71612008-07-21 04:59:05 +00001257 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1258 // pointer to a (potentially qualified) interface type.
1259 const PointerType *PTy;
1260 const ObjCInterfaceType *IFTy;
1261 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1262 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1263 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001264
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001265 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001266 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1267 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1268
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001269 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001270 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1271 E = IFTy->qual_end(); I != E; ++I)
1272 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1273 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001274
1275 // If that failed, look for an "implicit" property by seeing if the nullary
1276 // selector is implemented.
1277
1278 // FIXME: The logic for looking up nullary and unary selectors should be
1279 // shared with the code in ActOnInstanceMessage.
1280
1281 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1282 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1283
1284 // If this reference is in an @implementation, check for 'private' methods.
1285 if (!Getter)
1286 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1287 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1288 if (ObjCImplementationDecl *ImpDecl =
1289 ObjCImplementations[ClassDecl->getIdentifier()])
1290 Getter = ImpDecl->getInstanceMethod(Sel);
1291
Steve Naroff04151f32008-10-22 19:16:27 +00001292 // Look through local category implementations associated with the class.
1293 if (!Getter) {
1294 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1295 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1296 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1297 }
1298 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001299 if (Getter) {
1300 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001301 // will look for the matching setter, in case it is needed.
1302 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1303 &Member);
1304 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1305 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1306 if (!Setter) {
1307 // If this reference is in an @implementation, also check for 'private'
1308 // methods.
1309 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1310 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1311 if (ObjCImplementationDecl *ImpDecl =
1312 ObjCImplementations[ClassDecl->getIdentifier()])
1313 Setter = ImpDecl->getInstanceMethod(SetterSel);
1314 }
1315 // Look through local category implementations associated with the class.
1316 if (!Setter) {
1317 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1318 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1319 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1320 }
1321 }
1322
1323 // FIXME: we must check that the setter has property type.
1324 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00001325 MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001326 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001327 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001328 // Handle properties on qualified "id" protocols.
1329 const ObjCQualifiedIdType *QIdTy;
1330 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1331 // Check protocols on qualified interfaces.
1332 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001333 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001334 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1335 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001336 // Also must look for a getter name which uses property syntax.
1337 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1338 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1339 return new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(), OMD,
1340 OpLoc, MemberLoc, NULL, 0);
1341 }
1342 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001343 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001344 // Handle 'field access' to vectors, such as 'V.xx'.
1345 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1346 // Component access limited to variables (reject vec4.rg.g).
1347 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1348 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001349 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1350 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001351 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1352 if (ret.isNull())
1353 return true;
1354 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1355 }
1356
Chris Lattner8ba580c2008-11-19 05:08:23 +00001357 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001358 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001359}
1360
Steve Naroff87d58b42007-09-16 03:34:24 +00001361/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001362/// This provides the location of the left/right parens and a list of comma
1363/// locations.
1364Action::ExprResult Sema::
Douglas Gregora133e262008-12-06 00:22:45 +00001365ActOnCallExpr(Scope *S, ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001366 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001367 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1368 Expr *Fn = static_cast<Expr *>(fn);
1369 Expr **Args = reinterpret_cast<Expr**>(args);
1370 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001371 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001372 OverloadedFunctionDecl *Ovl = NULL;
1373
Douglas Gregora133e262008-12-06 00:22:45 +00001374 // Determine whether this is a dependent call inside a C++ template,
1375 // in which case we won't do any semantic analysis now.
1376 bool Dependent = false;
1377 if (Fn->isTypeDependent()) {
1378 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1379 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1380 Dependent = true;
1381 else {
1382 // Resolve the CXXDependentNameExpr to an actual identifier;
1383 // it wasn't really a dependent name after all.
1384 ExprResult Resolved
1385 = ActOnDeclarationNameExpr(S, FnName->getLocation(), FnName->getName(),
1386 /*HasTrailingLParen=*/true,
1387 /*SS=*/0,
1388 /*ForceResolution=*/true);
1389 if (Resolved.isInvalid)
1390 return true;
1391 else {
1392 delete Fn;
1393 Fn = (Expr *)Resolved.Val;
1394 }
1395 }
1396 } else
1397 Dependent = true;
1398 } else
1399 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1400
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001401 // FIXME: Will need to cache the results of name lookup (including
1402 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001403 if (Dependent)
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001404 return new CallExpr(Fn, Args, NumArgs, Context.DependentTy, RParenLoc);
1405
Douglas Gregord2baafd2008-10-21 16:13:35 +00001406 // If we're directly calling a function or a set of overloaded
1407 // functions, get the appropriate declaration.
1408 {
1409 DeclRefExpr *DRExpr = NULL;
1410 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1411 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1412 else
1413 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1414
1415 if (DRExpr) {
1416 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1417 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1418 }
1419 }
1420
Douglas Gregord2baafd2008-10-21 16:13:35 +00001421 if (Ovl) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001422 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1423 RParenLoc);
1424 if (!FDecl)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001425 return true;
1426
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001427 // Update Fn to refer to the actual function selected.
1428 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1429 Fn->getSourceRange().getBegin());
1430 Fn->Destroy(Context);
1431 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001432 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001433
Douglas Gregor10f3c502008-11-19 21:05:33 +00001434 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Douglas Gregora133e262008-12-06 00:22:45 +00001435 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregor10f3c502008-11-19 21:05:33 +00001436 CommaLocs, RParenLoc);
1437
Chris Lattner3e254fb2008-04-08 04:40:51 +00001438 // Promote the function operand.
1439 UsualUnaryConversions(Fn);
1440
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001441 // Make the call expr early, before semantic checks. This guarantees cleanup
1442 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001443 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001444 Context.BoolTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001445
Steve Naroffd6163f32008-09-05 22:11:13 +00001446 const FunctionType *FuncT;
1447 if (!Fn->getType()->isBlockPointerType()) {
1448 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1449 // have type pointer to function".
1450 const PointerType *PT = Fn->getType()->getAsPointerType();
1451 if (PT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001452 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001453 << Fn->getType() << Fn->getSourceRange();
Steve Naroffd6163f32008-09-05 22:11:13 +00001454 FuncT = PT->getPointeeType()->getAsFunctionType();
1455 } else { // This is a block call.
1456 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1457 getAsFunctionType();
1458 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001459 if (FuncT == 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();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001462
1463 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001464 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001465
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001466 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001467 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1468 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001469 unsigned NumArgsInProto = Proto->getNumArgs();
1470 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001471
Chris Lattner3e254fb2008-04-08 04:40:51 +00001472 // If too few arguments are available (and we don't have default
1473 // arguments for the remaining parameters), don't make the call.
1474 if (NumArgs < NumArgsInProto) {
Chris Lattner66beaba2008-11-21 18:44:24 +00001475 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1476 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1477 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1478 // Use default arguments for missing arguments
1479 NumArgsToCheck = NumArgsInProto;
1480 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001481 }
1482
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001483 // If too many are passed and not variadic, error on the extras and drop
1484 // them.
1485 if (NumArgs > NumArgsInProto) {
1486 if (!Proto->isVariadic()) {
Chris Lattner66beaba2008-11-21 18:44:24 +00001487 Diag(Args[NumArgsInProto]->getLocStart(),
1488 diag::err_typecheck_call_too_many_args)
1489 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
Chris Lattner8ba580c2008-11-19 05:08:23 +00001490 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1491 Args[NumArgs-1]->getLocEnd());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001492 // This deletes the extra arguments.
1493 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001494 }
1495 NumArgsToCheck = NumArgsInProto;
1496 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001497
Chris Lattner4b009652007-07-25 00:24:17 +00001498 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001499 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001500 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001501
1502 Expr *Arg;
1503 if (i < NumArgs)
1504 Arg = Args[i];
1505 else
1506 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001507 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001508
Douglas Gregor81c29152008-10-29 00:13:59 +00001509 // Pass the argument.
1510 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner005ed752008-01-04 18:04:52 +00001511 return true;
Douglas Gregor81c29152008-10-29 00:13:59 +00001512
1513 TheCall->setArg(i, Arg);
Chris Lattner4b009652007-07-25 00:24:17 +00001514 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001515
1516 // If this is a variadic call, handle args passed through "...".
1517 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001518 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001519 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1520 Expr *Arg = Args[i];
1521 DefaultArgumentPromotion(Arg);
1522 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001523 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001524 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001525 } else {
1526 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1527
Steve Naroffdb65e052007-08-28 23:30:39 +00001528 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001529 for (unsigned i = 0; i != NumArgs; i++) {
1530 Expr *Arg = Args[i];
1531 DefaultArgumentPromotion(Arg);
1532 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001533 }
Chris Lattner4b009652007-07-25 00:24:17 +00001534 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001535
Chris Lattner2e64c072007-08-10 20:18:51 +00001536 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001537 if (FDecl)
1538 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001539
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001540 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001541}
1542
1543Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001544ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001545 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001546 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001547 QualType literalType = QualType::getFromOpaquePtr(Ty);
1548 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001549 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001550 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001551
Eli Friedman8c2173d2008-05-20 05:22:08 +00001552 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001553 if (literalType->isVariableArrayType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001554 return Diag(LParenLoc, diag::err_variable_object_no_init)
1555 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001556 } else if (literalType->isIncompleteType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001557 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +00001558 << literalType
Chris Lattner8ba580c2008-11-19 05:08:23 +00001559 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001560 }
1561
Douglas Gregor6428e762008-11-05 15:29:30 +00001562 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Chris Lattner271d4c22008-11-24 05:29:24 +00001563 DeclarationName()))
Steve Naroff92590f92008-01-09 20:58:06 +00001564 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001565
Chris Lattnere5cb5862008-12-04 23:50:19 +00001566 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001567 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001568 if (CheckForConstantInitializer(literalExpr, literalType))
1569 return true;
1570 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001571 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1572 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001573}
1574
1575Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001576ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001577 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001578 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001579 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001580
Steve Naroff0acc9c92007-09-15 18:49:24 +00001581 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001582 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001583
Chris Lattner71ca8c82008-10-26 23:43:26 +00001584 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1585 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001586 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1587 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001588}
1589
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001590/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001591bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001592 UsualUnaryConversions(castExpr);
1593
1594 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1595 // type needs to be scalar.
1596 if (castType->isVoidType()) {
1597 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001598 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1599 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001600 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1601 // GCC struct/union extension: allow cast to self.
1602 if (Context.getCanonicalType(castType) !=
1603 Context.getCanonicalType(castExpr->getType()) ||
1604 (!castType->isStructureType() && !castType->isUnionType())) {
1605 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001606 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001607 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001608 }
1609
1610 // accept this, but emit an ext-warn.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001611 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001612 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001613 } else if (!castExpr->getType()->isScalarType() &&
1614 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001615 return Diag(castExpr->getLocStart(),
1616 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001617 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001618 } else if (castExpr->getType()->isVectorType()) {
1619 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1620 return true;
1621 } else if (castType->isVectorType()) {
1622 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1623 return true;
1624 }
1625 return false;
1626}
1627
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001628bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001629 assert(VectorTy->isVectorType() && "Not a vector type!");
1630
1631 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001632 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001633 return Diag(R.getBegin(),
1634 Ty->isVectorType() ?
1635 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00001636 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001637 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001638 } else
1639 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001640 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001641 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001642
1643 return false;
1644}
1645
Chris Lattner4b009652007-07-25 00:24:17 +00001646Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001647ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001648 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001649 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001650
1651 Expr *castExpr = static_cast<Expr*>(Op);
1652 QualType castType = QualType::getFromOpaquePtr(Ty);
1653
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001654 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1655 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00001656 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001657}
1658
Chris Lattner98a425c2007-11-26 01:40:58 +00001659/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1660/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001661inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1662 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1663 UsualUnaryConversions(cond);
1664 UsualUnaryConversions(lex);
1665 UsualUnaryConversions(rex);
1666 QualType condT = cond->getType();
1667 QualType lexT = lex->getType();
1668 QualType rexT = rex->getType();
1669
1670 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001671 if (!cond->isTypeDependent()) {
1672 if (!condT->isScalarType()) { // C99 6.5.15p2
1673 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
1674 return QualType();
1675 }
Chris Lattner4b009652007-07-25 00:24:17 +00001676 }
Chris Lattner992ae932008-01-06 22:42:25 +00001677
1678 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001679 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
1680 return Context.DependentTy;
1681
Chris Lattner992ae932008-01-06 22:42:25 +00001682 // If both operands have arithmetic type, do the usual arithmetic conversions
1683 // to find a common type: C99 6.5.15p3,5.
1684 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001685 UsualArithmeticConversions(lex, rex);
1686 return lex->getType();
1687 }
Chris Lattner992ae932008-01-06 22:42:25 +00001688
1689 // If both operands are the same structure or union type, the result is that
1690 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001691 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001692 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001693 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001694 // "If both the operands have structure or union type, the result has
1695 // that type." This implies that CV qualifiers are dropped.
1696 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001697 }
Chris Lattner992ae932008-01-06 22:42:25 +00001698
1699 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001700 // The following || allows only one side to be void (a GCC-ism).
1701 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001702 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001703 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
1704 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00001705 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001706 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
1707 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00001708 ImpCastExprToType(lex, Context.VoidTy);
1709 ImpCastExprToType(rex, Context.VoidTy);
1710 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001711 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001712 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1713 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001714 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1715 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001716 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001717 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001718 return lexT;
1719 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001720 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1721 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001722 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001723 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001724 return rexT;
1725 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001726 // Handle the case where both operands are pointers before we handle null
1727 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001728 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1729 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1730 // get the "pointed to" types
1731 QualType lhptee = LHSPT->getPointeeType();
1732 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001733
Chris Lattner71225142007-07-31 21:27:01 +00001734 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1735 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001736 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001737 // Figure out necessary qualifiers (C99 6.5.15p6)
1738 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001739 QualType destType = Context.getPointerType(destPointee);
1740 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1741 ImpCastExprToType(rex, destType); // promote to void*
1742 return destType;
1743 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001744 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001745 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001746 QualType destType = Context.getPointerType(destPointee);
1747 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1748 ImpCastExprToType(rex, destType); // promote to void*
1749 return destType;
1750 }
Chris Lattner4b009652007-07-25 00:24:17 +00001751
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001752 QualType compositeType = lexT;
1753
1754 // If either type is an Objective-C object type then check
1755 // compatibility according to Objective-C.
1756 if (Context.isObjCObjectPointerType(lexT) ||
1757 Context.isObjCObjectPointerType(rexT)) {
1758 // If both operands are interfaces and either operand can be
1759 // assigned to the other, use that type as the composite
1760 // type. This allows
1761 // xxx ? (A*) a : (B*) b
1762 // where B is a subclass of A.
1763 //
1764 // Additionally, as for assignment, if either type is 'id'
1765 // allow silent coercion. Finally, if the types are
1766 // incompatible then make sure to use 'id' as the composite
1767 // type so the result is acceptable for sending messages to.
1768
1769 // FIXME: This code should not be localized to here. Also this
1770 // should use a compatible check instead of abusing the
1771 // canAssignObjCInterfaces code.
1772 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1773 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1774 if (LHSIface && RHSIface &&
1775 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1776 compositeType = lexT;
1777 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00001778 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001779 compositeType = rexT;
1780 } else if (Context.isObjCIdType(lhptee) ||
1781 Context.isObjCIdType(rhptee)) {
1782 // FIXME: This code looks wrong, because isObjCIdType checks
1783 // the struct but getObjCIdType returns the pointer to
1784 // struct. This is horrible and should be fixed.
1785 compositeType = Context.getObjCIdType();
1786 } else {
1787 QualType incompatTy = Context.getObjCIdType();
1788 ImpCastExprToType(lex, incompatTy);
1789 ImpCastExprToType(rex, incompatTy);
1790 return incompatTy;
1791 }
1792 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1793 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00001794 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001795 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001796 // In this situation, we assume void* type. No especially good
1797 // reason, but this is what gcc does, and we do have to pick
1798 // to get a consistent AST.
1799 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001800 ImpCastExprToType(lex, incompatTy);
1801 ImpCastExprToType(rex, incompatTy);
1802 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001803 }
1804 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001805 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1806 // differently qualified versions of compatible types, the result type is
1807 // a pointer to an appropriately qualified version of the *composite*
1808 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001809 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001810 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001811 ImpCastExprToType(lex, compositeType);
1812 ImpCastExprToType(rex, compositeType);
1813 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001814 }
Chris Lattner4b009652007-07-25 00:24:17 +00001815 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001816 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1817 // evaluates to "struct objc_object *" (and is handled above when comparing
1818 // id with statically typed objects).
1819 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1820 // GCC allows qualified id and any Objective-C type to devolve to
1821 // id. Currently localizing to here until clear this should be
1822 // part of ObjCQualifiedIdTypesAreCompatible.
1823 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1824 (lexT->isObjCQualifiedIdType() &&
1825 Context.isObjCObjectPointerType(rexT)) ||
1826 (rexT->isObjCQualifiedIdType() &&
1827 Context.isObjCObjectPointerType(lexT))) {
1828 // FIXME: This is not the correct composite type. This only
1829 // happens to work because id can more or less be used anywhere,
1830 // however this may change the type of method sends.
1831 // FIXME: gcc adds some type-checking of the arguments and emits
1832 // (confusing) incompatible comparison warnings in some
1833 // cases. Investigate.
1834 QualType compositeType = Context.getObjCIdType();
1835 ImpCastExprToType(lex, compositeType);
1836 ImpCastExprToType(rex, compositeType);
1837 return compositeType;
1838 }
1839 }
1840
Steve Naroff3eac7692008-09-10 19:17:48 +00001841 // Selection between block pointer types is ok as long as they are the same.
1842 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1843 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1844 return lexT;
1845
Chris Lattner992ae932008-01-06 22:42:25 +00001846 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00001847 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001848 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001849 return QualType();
1850}
1851
Steve Naroff87d58b42007-09-16 03:34:24 +00001852/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001853/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001854Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001855 SourceLocation ColonLoc,
1856 ExprTy *Cond, ExprTy *LHS,
1857 ExprTy *RHS) {
1858 Expr *CondExpr = (Expr *) Cond;
1859 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001860
1861 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1862 // was the condition.
1863 bool isLHSNull = LHSExpr == 0;
1864 if (isLHSNull)
1865 LHSExpr = CondExpr;
1866
Chris Lattner4b009652007-07-25 00:24:17 +00001867 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1868 RHSExpr, QuestionLoc);
1869 if (result.isNull())
1870 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001871 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1872 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001873}
1874
Chris Lattner4b009652007-07-25 00:24:17 +00001875
1876// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1877// being closely modeled after the C99 spec:-). The odd characteristic of this
1878// routine is it effectively iqnores the qualifiers on the top level pointee.
1879// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1880// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001881Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001882Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1883 QualType lhptee, rhptee;
1884
1885 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001886 lhptee = lhsType->getAsPointerType()->getPointeeType();
1887 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001888
1889 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001890 lhptee = Context.getCanonicalType(lhptee);
1891 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001892
Chris Lattner005ed752008-01-04 18:04:52 +00001893 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001894
1895 // C99 6.5.16.1p1: This following citation is common to constraints
1896 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1897 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001898 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001899 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001900 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001901
1902 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1903 // incomplete type and the other is a pointer to a qualified or unqualified
1904 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001905 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001906 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001907 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001908
1909 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001910 assert(rhptee->isFunctionType());
1911 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001912 }
1913
1914 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001915 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001916 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001917
1918 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001919 assert(lhptee->isFunctionType());
1920 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001921 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001922
1923 // Check for ObjC interfaces
1924 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1925 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1926 if (LHSIface && RHSIface &&
1927 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1928 return ConvTy;
1929
1930 // ID acts sort of like void* for ObjC interfaces
1931 if (LHSIface && Context.isObjCIdType(rhptee))
1932 return ConvTy;
1933 if (RHSIface && Context.isObjCIdType(lhptee))
1934 return ConvTy;
1935
Chris Lattner4b009652007-07-25 00:24:17 +00001936 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1937 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001938 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1939 rhptee.getUnqualifiedType()))
1940 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001941 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001942}
1943
Steve Naroff3454b6c2008-09-04 15:10:53 +00001944/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1945/// block pointer types are compatible or whether a block and normal pointer
1946/// are compatible. It is more restrict than comparing two function pointer
1947// types.
1948Sema::AssignConvertType
1949Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1950 QualType rhsType) {
1951 QualType lhptee, rhptee;
1952
1953 // get the "pointed to" type (ignoring qualifiers at the top level)
1954 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1955 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1956
1957 // make sure we operate on the canonical type
1958 lhptee = Context.getCanonicalType(lhptee);
1959 rhptee = Context.getCanonicalType(rhptee);
1960
1961 AssignConvertType ConvTy = Compatible;
1962
1963 // For blocks we enforce that qualifiers are identical.
1964 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1965 ConvTy = CompatiblePointerDiscardsQualifiers;
1966
1967 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1968 return IncompatibleBlockPointer;
1969 return ConvTy;
1970}
1971
Chris Lattner4b009652007-07-25 00:24:17 +00001972/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1973/// has code to accommodate several GCC extensions when type checking
1974/// pointers. Here are some objectionable examples that GCC considers warnings:
1975///
1976/// int a, *pint;
1977/// short *pshort;
1978/// struct foo *pfoo;
1979///
1980/// pint = pshort; // warning: assignment from incompatible pointer type
1981/// a = pint; // warning: assignment makes integer from pointer without a cast
1982/// pint = a; // warning: assignment makes pointer from integer without a cast
1983/// pint = pfoo; // warning: assignment from incompatible pointer type
1984///
1985/// As a result, the code for dealing with pointers is more complex than the
1986/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001987///
Chris Lattner005ed752008-01-04 18:04:52 +00001988Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001989Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001990 // Get canonical types. We're not formatting these types, just comparing
1991 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001992 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1993 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001994
1995 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001996 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001997
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001998 // If the left-hand side is a reference type, then we are in a
1999 // (rare!) case where we've allowed the use of references in C,
2000 // e.g., as a parameter type in a built-in function. In this case,
2001 // just make sure that the type referenced is compatible with the
2002 // right-hand side type. The caller is responsible for adjusting
2003 // lhsType so that the resulting expression does not have reference
2004 // type.
2005 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2006 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002007 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002008 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002009 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002010
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002011 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2012 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002013 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002014 // Relax integer conversions like we do for pointers below.
2015 if (rhsType->isIntegerType())
2016 return IntToPointer;
2017 if (lhsType->isIntegerType())
2018 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002019 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002020 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002021
Nate Begemanc5f0f652008-07-14 18:02:46 +00002022 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002023 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002024 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2025 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002026 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002027
Nate Begemanc5f0f652008-07-14 18:02:46 +00002028 // If we are allowing lax vector conversions, and LHS and RHS are both
2029 // vectors, the total size only needs to be the same. This is a bitcast;
2030 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002031 if (getLangOptions().LaxVectorConversions &&
2032 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002033 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2034 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002035 }
2036 return Incompatible;
2037 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002038
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002039 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002040 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002041
Chris Lattner390564e2008-04-07 06:49:41 +00002042 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002043 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002044 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002045
Chris Lattner390564e2008-04-07 06:49:41 +00002046 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002047 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002048
Steve Naroffa982c712008-09-29 18:10:17 +00002049 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002050 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002051 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002052
2053 // Treat block pointers as objects.
2054 if (getLangOptions().ObjC1 &&
2055 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2056 return Compatible;
2057 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002058 return Incompatible;
2059 }
2060
2061 if (isa<BlockPointerType>(lhsType)) {
2062 if (rhsType->isIntegerType())
2063 return IntToPointer;
2064
Steve Naroffa982c712008-09-29 18:10:17 +00002065 // Treat block pointers as objects.
2066 if (getLangOptions().ObjC1 &&
2067 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2068 return Compatible;
2069
Steve Naroff3454b6c2008-09-04 15:10:53 +00002070 if (rhsType->isBlockPointerType())
2071 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2072
2073 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2074 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002075 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002076 }
Chris Lattner1853da22008-01-04 23:18:45 +00002077 return Incompatible;
2078 }
2079
Chris Lattner390564e2008-04-07 06:49:41 +00002080 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002081 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002082 if (lhsType == Context.BoolTy)
2083 return Compatible;
2084
2085 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002086 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002087
Chris Lattner390564e2008-04-07 06:49:41 +00002088 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002089 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002090
2091 if (isa<BlockPointerType>(lhsType) &&
2092 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002093 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002094 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002095 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002096
Chris Lattner1853da22008-01-04 23:18:45 +00002097 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002098 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002099 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002100 }
2101 return Incompatible;
2102}
2103
Chris Lattner005ed752008-01-04 18:04:52 +00002104Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002105Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002106 if (getLangOptions().CPlusPlus) {
2107 if (!lhsType->isRecordType()) {
2108 // C++ 5.17p3: If the left operand is not of class type, the
2109 // expression is implicitly converted (C++ 4) to the
2110 // cv-unqualified type of the left operand.
Douglas Gregorbb461502008-10-24 04:54:22 +00002111 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002112 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002113 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002114 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002115 }
2116
2117 // FIXME: Currently, we fall through and treat C++ classes like C
2118 // structures.
2119 }
2120
Steve Naroffcdee22d2007-11-27 17:58:44 +00002121 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2122 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002123 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2124 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002125 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002126 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002127 return Compatible;
2128 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002129
2130 // We don't allow conversion of non-null-pointer constants to integers.
2131 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2132 return IntToBlockPointer;
2133
Chris Lattner5f505bf2007-10-16 02:55:40 +00002134 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002135 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002136 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002137 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002138 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002139 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002140 if (!lhsType->isReferenceType())
2141 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002142
Chris Lattner005ed752008-01-04 18:04:52 +00002143 Sema::AssignConvertType result =
2144 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002145
2146 // C99 6.5.16.1p2: The value of the right operand is converted to the
2147 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002148 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2149 // so that we can use references in built-in functions even in C.
2150 // The getNonReferenceType() call makes sure that the resulting expression
2151 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002152 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002153 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002154 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002155}
2156
Chris Lattner005ed752008-01-04 18:04:52 +00002157Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002158Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2159 return CheckAssignmentConstraints(lhsType, rhsType);
2160}
2161
Chris Lattner1eafdea2008-11-18 01:30:42 +00002162QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002163 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002164 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002165 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002166 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002167}
2168
Chris Lattner1eafdea2008-11-18 01:30:42 +00002169inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002170 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002171 // For conversion purposes, we ignore any qualifiers.
2172 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002173 QualType lhsType =
2174 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2175 QualType rhsType =
2176 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002177
Nate Begemanc5f0f652008-07-14 18:02:46 +00002178 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002179 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002180 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002181
Nate Begemanc5f0f652008-07-14 18:02:46 +00002182 // Handle the case of a vector & extvector type of the same size and element
2183 // type. It would be nice if we only had one vector type someday.
2184 if (getLangOptions().LaxVectorConversions)
2185 if (const VectorType *LV = lhsType->getAsVectorType())
2186 if (const VectorType *RV = rhsType->getAsVectorType())
2187 if (LV->getElementType() == RV->getElementType() &&
2188 LV->getNumElements() == RV->getNumElements())
2189 return lhsType->isExtVectorType() ? lhsType : rhsType;
2190
2191 // If the lhs is an extended vector and the rhs is a scalar of the same type
2192 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002193 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002194 QualType eltType = V->getElementType();
2195
2196 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2197 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2198 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002199 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002200 return lhsType;
2201 }
2202 }
2203
Nate Begemanc5f0f652008-07-14 18:02:46 +00002204 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002205 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002206 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002207 QualType eltType = V->getElementType();
2208
2209 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2210 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2211 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002212 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002213 return rhsType;
2214 }
2215 }
2216
Chris Lattner4b009652007-07-25 00:24:17 +00002217 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002218 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002219 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002220 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002221 return QualType();
2222}
2223
2224inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002225 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002226{
2227 QualType lhsType = lex->getType(), rhsType = rex->getType();
2228
2229 if (lhsType->isVectorType() || rhsType->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002230 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002231
Steve Naroff8f708362007-08-24 19:07:16 +00002232 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002233
Chris Lattner4b009652007-07-25 00:24:17 +00002234 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002235 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002236 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002237}
2238
2239inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002240 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002241{
2242 QualType lhsType = lex->getType(), rhsType = rex->getType();
2243
Steve Naroff8f708362007-08-24 19:07:16 +00002244 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002245
Chris Lattner4b009652007-07-25 00:24:17 +00002246 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002247 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002248 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002249}
2250
2251inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002252 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002253{
2254 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002255 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002256
Steve Naroff8f708362007-08-24 19:07:16 +00002257 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002258
Chris Lattner4b009652007-07-25 00:24:17 +00002259 // handle the common case first (both operands are arithmetic).
2260 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002261 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002262
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002263 // Put any potential pointer into PExp
2264 Expr* PExp = lex, *IExp = rex;
2265 if (IExp->getType()->isPointerType())
2266 std::swap(PExp, IExp);
2267
2268 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2269 if (IExp->getType()->isIntegerType()) {
2270 // Check for arithmetic on pointers to incomplete types
2271 if (!PTy->getPointeeType()->isObjectType()) {
2272 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002273 Diag(Loc, diag::ext_gnu_void_ptr)
2274 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002275 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002276 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002277 << lex->getType() << lex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002278 return QualType();
2279 }
2280 }
2281 return PExp->getType();
2282 }
2283 }
2284
Chris Lattner1eafdea2008-11-18 01:30:42 +00002285 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002286}
2287
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002288// C99 6.5.6
2289QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002290 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002291 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002292 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002293
Steve Naroff8f708362007-08-24 19:07:16 +00002294 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002295
Chris Lattnerf6da2912007-12-09 21:53:25 +00002296 // Enforce type constraints: C99 6.5.6p3.
2297
2298 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002299 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002300 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002301
2302 // Either ptr - int or ptr - ptr.
2303 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002304 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002305
Chris Lattnerf6da2912007-12-09 21:53:25 +00002306 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002307 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002308 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002309 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002310 Diag(Loc, diag::ext_gnu_void_ptr)
2311 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002312 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002313 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002314 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002315 return QualType();
2316 }
2317 }
2318
2319 // The result type of a pointer-int computation is the pointer type.
2320 if (rex->getType()->isIntegerType())
2321 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002322
Chris Lattnerf6da2912007-12-09 21:53:25 +00002323 // Handle pointer-pointer subtractions.
2324 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002325 QualType rpointee = RHSPTy->getPointeeType();
2326
Chris Lattnerf6da2912007-12-09 21:53:25 +00002327 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002328 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002329 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002330 if (rpointee->isVoidType()) {
2331 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002332 Diag(Loc, diag::ext_gnu_void_ptr)
2333 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002334 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002335 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002336 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002337 return QualType();
2338 }
2339 }
2340
2341 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002342 if (!Context.typesAreCompatible(
2343 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2344 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002345 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002346 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002347 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002348 return QualType();
2349 }
2350
2351 return Context.getPointerDiffType();
2352 }
2353 }
2354
Chris Lattner1eafdea2008-11-18 01:30:42 +00002355 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002356}
2357
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002358// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002359QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002360 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002361 // C99 6.5.7p2: Each of the operands shall have integer type.
2362 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002363 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002364
Chris Lattner2c8bff72007-12-12 05:47:28 +00002365 // Shifts don't perform usual arithmetic conversions, they just do integer
2366 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002367 if (!isCompAssign)
2368 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002369 UsualUnaryConversions(rex);
2370
2371 // "The type of the result is that of the promoted left operand."
2372 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002373}
2374
Eli Friedman0d9549b2008-08-22 00:56:42 +00002375static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2376 ASTContext& Context) {
2377 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2378 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2379 // ID acts sort of like void* for ObjC interfaces
2380 if (LHSIface && Context.isObjCIdType(RHS))
2381 return true;
2382 if (RHSIface && Context.isObjCIdType(LHS))
2383 return true;
2384 if (!LHSIface || !RHSIface)
2385 return false;
2386 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2387 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2388}
2389
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002390// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002391QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002392 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002393 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002394 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002395
Chris Lattner254f3bc2007-08-26 01:18:55 +00002396 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002397 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2398 UsualArithmeticConversions(lex, rex);
2399 else {
2400 UsualUnaryConversions(lex);
2401 UsualUnaryConversions(rex);
2402 }
Chris Lattner4b009652007-07-25 00:24:17 +00002403 QualType lType = lex->getType();
2404 QualType rType = rex->getType();
2405
Ted Kremenek486509e2007-10-29 17:13:39 +00002406 // For non-floating point types, check for self-comparisons of the form
2407 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2408 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002409 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002410 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2411 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002412 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002413 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002414 }
2415
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002416 // The result of comparisons is 'bool' in C++, 'int' in C.
2417 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2418
Chris Lattner254f3bc2007-08-26 01:18:55 +00002419 if (isRelational) {
2420 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002421 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002422 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002423 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002424 if (lType->isFloatingType()) {
2425 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002426 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002427 }
2428
Chris Lattner254f3bc2007-08-26 01:18:55 +00002429 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002430 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002431 }
Chris Lattner4b009652007-07-25 00:24:17 +00002432
Chris Lattner22be8422007-08-26 01:10:14 +00002433 bool LHSIsNull = lex->isNullPointerConstant(Context);
2434 bool RHSIsNull = rex->isNullPointerConstant(Context);
2435
Chris Lattner254f3bc2007-08-26 01:18:55 +00002436 // All of the following pointer related warnings are GCC extensions, except
2437 // when handling null pointer constants. One day, we can consider making them
2438 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002439 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002440 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002441 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002442 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002443 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002444
Steve Naroff3b435622007-11-13 14:57:38 +00002445 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002446 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2447 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002448 RCanPointeeTy.getUnqualifiedType()) &&
2449 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002450 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002451 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002452 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002453 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002454 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002455 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002456 // Handle block pointer types.
2457 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2458 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2459 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2460
2461 if (!LHSIsNull && !RHSIsNull &&
2462 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002463 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002464 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002465 }
2466 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002467 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002468 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002469 // Allow block pointers to be compared with null pointer constants.
2470 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2471 (lType->isPointerType() && rType->isBlockPointerType())) {
2472 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002473 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002474 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002475 }
2476 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002477 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002478 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002479
Steve Naroff936c4362008-06-03 14:04:54 +00002480 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002481 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002482 const PointerType *LPT = lType->getAsPointerType();
2483 const PointerType *RPT = rType->getAsPointerType();
2484 bool LPtrToVoid = LPT ?
2485 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2486 bool RPtrToVoid = RPT ?
2487 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2488
2489 if (!LPtrToVoid && !RPtrToVoid &&
2490 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002491 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002492 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002493 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002494 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002495 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002496 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002497 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002498 }
Steve Naroff936c4362008-06-03 14:04:54 +00002499 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2500 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002501 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002502 } else {
2503 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002504 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002505 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002506 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002507 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002508 }
Steve Naroff936c4362008-06-03 14:04:54 +00002509 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002510 }
Steve Naroff936c4362008-06-03 14:04:54 +00002511 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2512 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002513 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002514 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002515 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002516 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002517 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002518 }
Steve Naroff936c4362008-06-03 14:04:54 +00002519 if (lType->isIntegerType() &&
2520 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002521 if (!LHSIsNull)
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(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002525 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002526 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002527 // Handle block pointers.
2528 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2529 if (!RHSIsNull)
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();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002532 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002533 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002534 }
2535 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2536 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002537 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002538 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002539 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002540 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002541 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002542 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002543}
2544
Nate Begemanc5f0f652008-07-14 18:02:46 +00002545/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2546/// operates on extended vector types. Instead of producing an IntTy result,
2547/// like a scalar comparison, a vector comparison produces a vector of integer
2548/// types.
2549QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002550 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002551 bool isRelational) {
2552 // Check to make sure we're operating on vectors of the same type and width,
2553 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002554 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002555 if (vType.isNull())
2556 return vType;
2557
2558 QualType lType = lex->getType();
2559 QualType rType = rex->getType();
2560
2561 // For non-floating point types, check for self-comparisons of the form
2562 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2563 // often indicate logic errors in the program.
2564 if (!lType->isFloatingType()) {
2565 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2566 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2567 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002568 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002569 }
2570
2571 // Check for comparisons of floating point operands using != and ==.
2572 if (!isRelational && lType->isFloatingType()) {
2573 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002574 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002575 }
2576
2577 // Return the type for the comparison, which is the same as vector type for
2578 // integer vectors, or an integer type of identical size and number of
2579 // elements for floating point vectors.
2580 if (lType->isIntegerType())
2581 return lType;
2582
2583 const VectorType *VTy = lType->getAsVectorType();
2584
2585 // FIXME: need to deal with non-32b int / non-64b long long
2586 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2587 if (TypeSize == 32) {
2588 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2589 }
2590 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2591 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2592}
2593
Chris Lattner4b009652007-07-25 00:24:17 +00002594inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002595 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002596{
2597 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002598 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002599
Steve Naroff8f708362007-08-24 19:07:16 +00002600 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002601
2602 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002603 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002604 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002605}
2606
2607inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00002608 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00002609{
2610 UsualUnaryConversions(lex);
2611 UsualUnaryConversions(rex);
2612
Eli Friedmanbea3f842008-05-13 20:16:47 +00002613 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002614 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002615 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002616}
2617
Chris Lattner4c2642c2008-11-18 01:22:49 +00002618/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2619/// emit an error and return true. If so, return false.
2620static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2621 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2622 if (IsLV == Expr::MLV_Valid)
2623 return false;
2624
2625 unsigned Diag = 0;
2626 bool NeedType = false;
2627 switch (IsLV) { // C99 6.5.16p2
2628 default: assert(0 && "Unknown result from isModifiableLvalue!");
2629 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00002630 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002631 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2632 NeedType = true;
2633 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002634 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002635 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2636 NeedType = true;
2637 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00002638 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002639 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2640 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002641 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002642 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2643 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002644 case Expr::MLV_IncompleteType:
2645 case Expr::MLV_IncompleteVoidType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002646 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2647 NeedType = true;
2648 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002649 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002650 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2651 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00002652 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002653 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2654 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00002655 case Expr::MLV_ReadonlyProperty:
2656 Diag = diag::error_readonly_property_assignment;
2657 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00002658 case Expr::MLV_NoSetterProperty:
2659 Diag = diag::error_nosetter_property_assignment;
2660 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002661 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002662
Chris Lattner4c2642c2008-11-18 01:22:49 +00002663 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002664 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002665 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00002666 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002667 return true;
2668}
2669
2670
2671
2672// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00002673QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
2674 SourceLocation Loc,
2675 QualType CompoundType) {
2676 // Verify that LHS is a modifiable lvalue, and emit error if not.
2677 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00002678 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00002679
2680 QualType LHSType = LHS->getType();
2681 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00002682
Chris Lattner005ed752008-01-04 18:04:52 +00002683 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002684 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00002685 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002686 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner34c85082008-08-21 18:04:13 +00002687
2688 // If the RHS is a unary plus or minus, check to see if they = and + are
2689 // right next to each other. If so, the user may have typo'd "x =+ 4"
2690 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002691 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00002692 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2693 RHSCheck = ICE->getSubExpr();
2694 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2695 if ((UO->getOpcode() == UnaryOperator::Plus ||
2696 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00002697 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00002698 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002699 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00002700 Diag(Loc, diag::warn_not_compound_assign)
2701 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
2702 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00002703 }
2704 } else {
2705 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00002706 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00002707 }
Chris Lattner005ed752008-01-04 18:04:52 +00002708
Chris Lattner1eafdea2008-11-18 01:30:42 +00002709 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
2710 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00002711 return QualType();
2712
Chris Lattner4b009652007-07-25 00:24:17 +00002713 // C99 6.5.16p3: The type of an assignment expression is the type of the
2714 // left operand unless the left operand has qualified type, in which case
2715 // it is the unqualified version of the type of the left operand.
2716 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2717 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002718 // C++ 5.17p1: the type of the assignment expression is that of its left
2719 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002720 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002721}
2722
Chris Lattner1eafdea2008-11-18 01:30:42 +00002723// C99 6.5.17
2724QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
2725 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00002726
2727 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002728 DefaultFunctionArrayConversion(RHS);
2729 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002730}
2731
2732/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2733/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Chris Lattnere65182c2008-11-21 07:05:48 +00002734QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc) {
2735 QualType ResType = Op->getType();
2736 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002737
Steve Naroffd30e1932007-08-24 17:20:07 +00002738 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattnere65182c2008-11-21 07:05:48 +00002739 if (ResType->isRealType()) {
2740 // OK!
2741 } else if (const PointerType *PT = ResType->getAsPointerType()) {
2742 // C99 6.5.2.4p2, 6.5.6p2
2743 if (PT->getPointeeType()->isObjectType()) {
2744 // Pointer to object is ok!
2745 } else if (PT->getPointeeType()->isVoidType()) {
2746 // Pointer to void is extension.
2747 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
2748 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +00002749 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002750 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002751 return QualType();
2752 }
Chris Lattnere65182c2008-11-21 07:05:48 +00002753 } else if (ResType->isComplexType()) {
2754 // C99 does not support ++/-- on complex types, we allow as an extension.
2755 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002756 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002757 } else {
2758 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002759 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002760 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002761 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002762 // At this point, we know we have a real, complex or pointer type.
2763 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00002764 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00002765 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00002766 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00002767}
2768
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002769/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002770/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002771/// where the declaration is needed for type checking. We only need to
2772/// handle cases when the expression references a function designator
2773/// or is an lvalue. Here are some examples:
2774/// - &(x) => x
2775/// - &*****f => f for f a function designator.
2776/// - &s.xx => s
2777/// - &s.zz[1].yy -> s, if zz is an array
2778/// - *(x + 1) -> x, if x is an array
2779/// - &"123"[2] -> 0
2780/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002781static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002782 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002783 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002784 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002785 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002786 // Fields cannot be declared with a 'register' storage class.
2787 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002788 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002789 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002790 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002791 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002792 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002793
Douglas Gregord2baafd2008-10-21 16:13:35 +00002794 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002795 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002796 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002797 return 0;
2798 else
2799 return VD;
2800 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002801 case Stmt::UnaryOperatorClass: {
2802 UnaryOperator *UO = cast<UnaryOperator>(E);
2803
2804 switch(UO->getOpcode()) {
2805 case UnaryOperator::Deref: {
2806 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002807 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2808 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2809 if (!VD || VD->getType()->isPointerType())
2810 return 0;
2811 return VD;
2812 }
2813 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002814 }
2815 case UnaryOperator::Real:
2816 case UnaryOperator::Imag:
2817 case UnaryOperator::Extension:
2818 return getPrimaryDecl(UO->getSubExpr());
2819 default:
2820 return 0;
2821 }
2822 }
2823 case Stmt::BinaryOperatorClass: {
2824 BinaryOperator *BO = cast<BinaryOperator>(E);
2825
2826 // Handle cases involving pointer arithmetic. The result of an
2827 // Assign or AddAssign is not an lvalue so they can be ignored.
2828
2829 // (x + n) or (n + x) => x
2830 if (BO->getOpcode() == BinaryOperator::Add) {
2831 if (BO->getLHS()->getType()->isPointerType()) {
2832 return getPrimaryDecl(BO->getLHS());
2833 } else if (BO->getRHS()->getType()->isPointerType()) {
2834 return getPrimaryDecl(BO->getRHS());
2835 }
2836 }
2837
2838 return 0;
2839 }
Chris Lattner4b009652007-07-25 00:24:17 +00002840 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002841 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002842 case Stmt::ImplicitCastExprClass:
2843 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002844 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002845 default:
2846 return 0;
2847 }
2848}
2849
2850/// CheckAddressOfOperand - The operand of & must be either a function
2851/// designator or an lvalue designating an object. If it is an lvalue, the
2852/// object cannot be declared with storage class register or be a bit field.
2853/// Note: The usual conversions are *not* applied to the operand of the &
2854/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00002855/// In C++, the operand might be an overloaded function name, in which case
2856/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00002857QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002858 if (getLangOptions().C99) {
2859 // Implement C99-only parts of addressof rules.
2860 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2861 if (uOp->getOpcode() == UnaryOperator::Deref)
2862 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2863 // (assuming the deref expression is valid).
2864 return uOp->getSubExpr()->getType();
2865 }
2866 // Technically, there should be a check for array subscript
2867 // expressions here, but the result of one is always an lvalue anyway.
2868 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002869 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002870 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002871
2872 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002873 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2874 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00002875 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
2876 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002877 return QualType();
2878 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002879 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2880 if (MemExpr->getMemberDecl()->isBitField()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002881 Diag(OpLoc, diag::err_typecheck_address_of)
2882 << "bit-field" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00002883 return QualType();
2884 }
2885 // Check for Apple extension for accessing vector components.
2886 } else if (isa<ArraySubscriptExpr>(op) &&
2887 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002888 Diag(OpLoc, diag::err_typecheck_address_of)
2889 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00002890 return QualType();
2891 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002892 // We have an lvalue with a decl. Make sure the decl is not declared
2893 // with the register storage-class specifier.
2894 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2895 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002896 Diag(OpLoc, diag::err_typecheck_address_of)
2897 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002898 return QualType();
2899 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00002900 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00002901 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00002902 } else if (isa<FieldDecl>(dcl)) {
2903 // Okay: we can take the address of a field.
2904 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00002905 else
Chris Lattner4b009652007-07-25 00:24:17 +00002906 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002907 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002908
Chris Lattner4b009652007-07-25 00:24:17 +00002909 // If the operand has type "type", the result has type "pointer to type".
2910 return Context.getPointerType(op->getType());
2911}
2912
Chris Lattnerda5c0872008-11-23 09:13:29 +00002913QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
2914 UsualUnaryConversions(Op);
2915 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002916
Chris Lattnerda5c0872008-11-23 09:13:29 +00002917 // Note that per both C89 and C99, this is always legal, even if ptype is an
2918 // incomplete type or void. It would be possible to warn about dereferencing
2919 // a void pointer, but it's completely well-defined, and such a warning is
2920 // unlikely to catch any mistakes.
2921 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00002922 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00002923
Chris Lattner77d52da2008-11-20 06:06:08 +00002924 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002925 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002926 return QualType();
2927}
2928
2929static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2930 tok::TokenKind Kind) {
2931 BinaryOperator::Opcode Opc;
2932 switch (Kind) {
2933 default: assert(0 && "Unknown binop!");
2934 case tok::star: Opc = BinaryOperator::Mul; break;
2935 case tok::slash: Opc = BinaryOperator::Div; break;
2936 case tok::percent: Opc = BinaryOperator::Rem; break;
2937 case tok::plus: Opc = BinaryOperator::Add; break;
2938 case tok::minus: Opc = BinaryOperator::Sub; break;
2939 case tok::lessless: Opc = BinaryOperator::Shl; break;
2940 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2941 case tok::lessequal: Opc = BinaryOperator::LE; break;
2942 case tok::less: Opc = BinaryOperator::LT; break;
2943 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2944 case tok::greater: Opc = BinaryOperator::GT; break;
2945 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2946 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2947 case tok::amp: Opc = BinaryOperator::And; break;
2948 case tok::caret: Opc = BinaryOperator::Xor; break;
2949 case tok::pipe: Opc = BinaryOperator::Or; break;
2950 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2951 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2952 case tok::equal: Opc = BinaryOperator::Assign; break;
2953 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2954 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2955 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2956 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2957 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2958 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2959 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2960 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2961 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2962 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2963 case tok::comma: Opc = BinaryOperator::Comma; break;
2964 }
2965 return Opc;
2966}
2967
2968static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2969 tok::TokenKind Kind) {
2970 UnaryOperator::Opcode Opc;
2971 switch (Kind) {
2972 default: assert(0 && "Unknown unary op!");
2973 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2974 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2975 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2976 case tok::star: Opc = UnaryOperator::Deref; break;
2977 case tok::plus: Opc = UnaryOperator::Plus; break;
2978 case tok::minus: Opc = UnaryOperator::Minus; break;
2979 case tok::tilde: Opc = UnaryOperator::Not; break;
2980 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002981 case tok::kw___real: Opc = UnaryOperator::Real; break;
2982 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2983 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2984 }
2985 return Opc;
2986}
2987
Douglas Gregord7f915e2008-11-06 23:29:22 +00002988/// CreateBuiltinBinOp - Creates a new built-in binary operation with
2989/// operator @p Opc at location @c TokLoc. This routine only supports
2990/// built-in operations; ActOnBinOp handles overloaded operators.
2991Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
2992 unsigned Op,
2993 Expr *lhs, Expr *rhs) {
2994 QualType ResultTy; // Result type of the binary operator.
2995 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2996 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
2997
2998 switch (Opc) {
2999 default:
3000 assert(0 && "Unknown binary expr!");
3001 case BinaryOperator::Assign:
3002 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3003 break;
3004 case BinaryOperator::Mul:
3005 case BinaryOperator::Div:
3006 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3007 break;
3008 case BinaryOperator::Rem:
3009 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3010 break;
3011 case BinaryOperator::Add:
3012 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3013 break;
3014 case BinaryOperator::Sub:
3015 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3016 break;
3017 case BinaryOperator::Shl:
3018 case BinaryOperator::Shr:
3019 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3020 break;
3021 case BinaryOperator::LE:
3022 case BinaryOperator::LT:
3023 case BinaryOperator::GE:
3024 case BinaryOperator::GT:
3025 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3026 break;
3027 case BinaryOperator::EQ:
3028 case BinaryOperator::NE:
3029 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3030 break;
3031 case BinaryOperator::And:
3032 case BinaryOperator::Xor:
3033 case BinaryOperator::Or:
3034 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3035 break;
3036 case BinaryOperator::LAnd:
3037 case BinaryOperator::LOr:
3038 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3039 break;
3040 case BinaryOperator::MulAssign:
3041 case BinaryOperator::DivAssign:
3042 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3043 if (!CompTy.isNull())
3044 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3045 break;
3046 case BinaryOperator::RemAssign:
3047 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3048 if (!CompTy.isNull())
3049 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3050 break;
3051 case BinaryOperator::AddAssign:
3052 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3053 if (!CompTy.isNull())
3054 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3055 break;
3056 case BinaryOperator::SubAssign:
3057 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3058 if (!CompTy.isNull())
3059 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3060 break;
3061 case BinaryOperator::ShlAssign:
3062 case BinaryOperator::ShrAssign:
3063 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3064 if (!CompTy.isNull())
3065 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3066 break;
3067 case BinaryOperator::AndAssign:
3068 case BinaryOperator::XorAssign:
3069 case BinaryOperator::OrAssign:
3070 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3071 if (!CompTy.isNull())
3072 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3073 break;
3074 case BinaryOperator::Comma:
3075 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3076 break;
3077 }
3078 if (ResultTy.isNull())
3079 return true;
3080 if (CompTy.isNull())
3081 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
3082 else
3083 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
3084}
3085
Chris Lattner4b009652007-07-25 00:24:17 +00003086// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003087Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3088 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00003089 ExprTy *LHS, ExprTy *RHS) {
3090 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3091 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
3092
Steve Naroff87d58b42007-09-16 03:34:24 +00003093 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3094 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003095
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003096 // If either expression is type-dependent, just build the AST.
3097 // FIXME: We'll need to perform some caching of the result of name
3098 // lookup for operator+.
3099 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3100 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3101 return new CompoundAssignOperator(lhs, rhs, Opc, Context.DependentTy,
3102 Context.DependentTy, TokLoc);
3103 else
3104 return new BinaryOperator(lhs, rhs, Opc, Context.DependentTy, TokLoc);
3105 }
3106
Douglas Gregord7f915e2008-11-06 23:29:22 +00003107 if (getLangOptions().CPlusPlus &&
3108 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3109 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003110 // If this is one of the assignment operators, we only perform
3111 // overload resolution if the left-hand side is a class or
3112 // enumeration type (C++ [expr.ass]p3).
3113 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3114 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3115 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3116 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003117
3118 // Determine which overloaded operator we're dealing with.
3119 static const OverloadedOperatorKind OverOps[] = {
3120 OO_Star, OO_Slash, OO_Percent,
3121 OO_Plus, OO_Minus,
3122 OO_LessLess, OO_GreaterGreater,
3123 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3124 OO_EqualEqual, OO_ExclaimEqual,
3125 OO_Amp,
3126 OO_Caret,
3127 OO_Pipe,
3128 OO_AmpAmp,
3129 OO_PipePipe,
3130 OO_Equal, OO_StarEqual,
3131 OO_SlashEqual, OO_PercentEqual,
3132 OO_PlusEqual, OO_MinusEqual,
3133 OO_LessLessEqual, OO_GreaterGreaterEqual,
3134 OO_AmpEqual, OO_CaretEqual,
3135 OO_PipeEqual,
3136 OO_Comma
3137 };
3138 OverloadedOperatorKind OverOp = OverOps[Opc];
3139
Douglas Gregor5ed15042008-11-18 23:14:02 +00003140 // Add the appropriate overloaded operators (C++ [over.match.oper])
3141 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003142 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003143 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003144 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003145
3146 // Perform overload resolution.
3147 OverloadCandidateSet::iterator Best;
3148 switch (BestViableFunction(CandidateSet, Best)) {
3149 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003150 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003151 FunctionDecl *FnDecl = Best->Function;
3152
Douglas Gregor70d26122008-11-12 17:17:38 +00003153 if (FnDecl) {
3154 // We matched an overloaded operator. Build a call to that
3155 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003156
Douglas Gregor70d26122008-11-12 17:17:38 +00003157 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003158 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3159 if (PerformObjectArgumentInitialization(lhs, Method) ||
3160 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3161 "passing"))
3162 return true;
3163 } else {
3164 // Convert the arguments.
3165 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3166 "passing") ||
3167 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3168 "passing"))
3169 return true;
3170 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003171
Douglas Gregor70d26122008-11-12 17:17:38 +00003172 // Determine the result type
3173 QualType ResultTy
3174 = FnDecl->getType()->getAsFunctionType()->getResultType();
3175 ResultTy = ResultTy.getNonReferenceType();
3176
3177 // Build the actual expression node.
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003178 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3179 SourceLocation());
3180 UsualUnaryConversions(FnExpr);
3181
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003182 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregor70d26122008-11-12 17:17:38 +00003183 } else {
3184 // We matched a built-in operator. Convert the arguments, then
3185 // break out so that we will build the appropriate built-in
3186 // operator node.
3187 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
3188 "passing") ||
3189 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
3190 "passing"))
3191 return true;
3192
3193 break;
3194 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003195 }
3196
3197 case OR_No_Viable_Function:
3198 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003199 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003200 break;
3201
3202 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003203 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3204 << BinaryOperator::getOpcodeStr(Opc)
3205 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003206 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3207 return true;
3208 }
3209
Douglas Gregor70d26122008-11-12 17:17:38 +00003210 // Either we found no viable overloaded operator or we matched a
3211 // built-in operator. In either case, fall through to trying to
3212 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003213 }
Chris Lattner4b009652007-07-25 00:24:17 +00003214
Douglas Gregord7f915e2008-11-06 23:29:22 +00003215 // Build a built-in binary operation.
3216 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003217}
3218
3219// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003220Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3221 tok::TokenKind Op, ExprTy *input) {
Chris Lattner4b009652007-07-25 00:24:17 +00003222 Expr *Input = (Expr*)input;
3223 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003224
3225 if (getLangOptions().CPlusPlus &&
3226 (Input->getType()->isRecordType()
3227 || Input->getType()->isEnumeralType())) {
3228 // Determine which overloaded operator we're dealing with.
3229 static const OverloadedOperatorKind OverOps[] = {
3230 OO_None, OO_None,
3231 OO_PlusPlus, OO_MinusMinus,
3232 OO_Amp, OO_Star,
3233 OO_Plus, OO_Minus,
3234 OO_Tilde, OO_Exclaim,
3235 OO_None, OO_None,
3236 OO_None,
3237 OO_None
3238 };
3239 OverloadedOperatorKind OverOp = OverOps[Opc];
3240
3241 // Add the appropriate overloaded operators (C++ [over.match.oper])
3242 // to the candidate set.
3243 OverloadCandidateSet CandidateSet;
3244 if (OverOp != OO_None)
3245 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3246
3247 // Perform overload resolution.
3248 OverloadCandidateSet::iterator Best;
3249 switch (BestViableFunction(CandidateSet, Best)) {
3250 case OR_Success: {
3251 // We found a built-in operator or an overloaded operator.
3252 FunctionDecl *FnDecl = Best->Function;
3253
3254 if (FnDecl) {
3255 // We matched an overloaded operator. Build a call to that
3256 // operator.
3257
3258 // Convert the arguments.
3259 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3260 if (PerformObjectArgumentInitialization(Input, Method))
3261 return true;
3262 } else {
3263 // Convert the arguments.
3264 if (PerformCopyInitialization(Input,
3265 FnDecl->getParamDecl(0)->getType(),
3266 "passing"))
3267 return true;
3268 }
3269
3270 // Determine the result type
3271 QualType ResultTy
3272 = FnDecl->getType()->getAsFunctionType()->getResultType();
3273 ResultTy = ResultTy.getNonReferenceType();
3274
3275 // Build the actual expression node.
3276 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3277 SourceLocation());
3278 UsualUnaryConversions(FnExpr);
3279
3280 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3281 } else {
3282 // We matched a built-in operator. Convert the arguments, then
3283 // break out so that we will build the appropriate built-in
3284 // operator node.
3285 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0],
3286 "passing"))
3287 return true;
3288
3289 break;
3290 }
3291 }
3292
3293 case OR_No_Viable_Function:
3294 // No viable function; fall through to handling this as a
3295 // built-in operator, which will produce an error message for us.
3296 break;
3297
3298 case OR_Ambiguous:
3299 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3300 << UnaryOperator::getOpcodeStr(Opc)
3301 << Input->getSourceRange();
3302 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3303 return true;
3304 }
3305
3306 // Either we found no viable overloaded operator or we matched a
3307 // built-in operator. In either case, fall through to trying to
3308 // build a built-in operation.
3309 }
3310
Chris Lattner4b009652007-07-25 00:24:17 +00003311 QualType resultType;
3312 switch (Opc) {
3313 default:
3314 assert(0 && "Unimplemented unary expr!");
3315 case UnaryOperator::PreInc:
3316 case UnaryOperator::PreDec:
3317 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
3318 break;
3319 case UnaryOperator::AddrOf:
3320 resultType = CheckAddressOfOperand(Input, OpLoc);
3321 break;
3322 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003323 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003324 resultType = CheckIndirectionOperand(Input, OpLoc);
3325 break;
3326 case UnaryOperator::Plus:
3327 case UnaryOperator::Minus:
3328 UsualUnaryConversions(Input);
3329 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003330 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3331 break;
3332 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3333 resultType->isEnumeralType())
3334 break;
3335 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3336 Opc == UnaryOperator::Plus &&
3337 resultType->isPointerType())
3338 break;
3339
Chris Lattner77d52da2008-11-20 06:06:08 +00003340 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003341 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003342 case UnaryOperator::Not: // bitwise complement
3343 UsualUnaryConversions(Input);
3344 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003345 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3346 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3347 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003348 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003349 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003350 else if (!resultType->isIntegerType())
Chris Lattner77d52da2008-11-20 06:06:08 +00003351 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003352 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003353 break;
3354 case UnaryOperator::LNot: // logical negation
3355 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3356 DefaultFunctionArrayConversion(Input);
3357 resultType = Input->getType();
3358 if (!resultType->isScalarType()) // C99 6.5.3.3p1
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 // LNot always has type int. C99 6.5.3.3p5.
3362 resultType = Context.IntTy;
3363 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003364 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003365 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003366 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003367 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003368 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003369 resultType = Input->getType();
3370 break;
3371 }
3372 if (resultType.isNull())
3373 return true;
3374 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3375}
3376
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003377/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3378Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003379 SourceLocation LabLoc,
3380 IdentifierInfo *LabelII) {
3381 // Look up the record for this label identifier.
3382 LabelStmt *&LabelDecl = LabelMap[LabelII];
3383
Daniel Dunbar879788d2008-08-04 16:51:22 +00003384 // If we haven't seen this label yet, create a forward reference. It
3385 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003386 if (LabelDecl == 0)
3387 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3388
3389 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003390 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3391 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003392}
3393
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003394Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003395 SourceLocation RPLoc) { // "({..})"
3396 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3397 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3398 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3399
3400 // FIXME: there are a variety of strange constraints to enforce here, for
3401 // example, it is not possible to goto into a stmt expression apparently.
3402 // More semantic analysis is needed.
3403
3404 // FIXME: the last statement in the compount stmt has its value used. We
3405 // should not warn about it being unused.
3406
3407 // If there are sub stmts in the compound stmt, take the type of the last one
3408 // as the type of the stmtexpr.
3409 QualType Ty = Context.VoidTy;
3410
Chris Lattner200964f2008-07-26 19:51:01 +00003411 if (!Compound->body_empty()) {
3412 Stmt *LastStmt = Compound->body_back();
3413 // If LastStmt is a label, skip down through into the body.
3414 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3415 LastStmt = Label->getSubStmt();
3416
3417 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003418 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003419 }
Chris Lattner4b009652007-07-25 00:24:17 +00003420
3421 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3422}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003423
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003424Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003425 SourceLocation TypeLoc,
3426 TypeTy *argty,
3427 OffsetOfComponent *CompPtr,
3428 unsigned NumComponents,
3429 SourceLocation RPLoc) {
3430 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3431 assert(!ArgTy.isNull() && "Missing type argument!");
3432
3433 // We must have at least one component that refers to the type, and the first
3434 // one is known to be a field designator. Verify that the ArgTy represents
3435 // a struct/union/class.
3436 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003437 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003438
3439 // Otherwise, create a compound literal expression as the base, and
3440 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003441 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003442
Chris Lattnerb37522e2007-08-31 21:49:13 +00003443 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3444 // GCC extension, diagnose them.
3445 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003446 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3447 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003448
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003449 for (unsigned i = 0; i != NumComponents; ++i) {
3450 const OffsetOfComponent &OC = CompPtr[i];
3451 if (OC.isBrackets) {
3452 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003453 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003454 if (!AT) {
3455 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003456 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003457 }
3458
Chris Lattner2af6a802007-08-30 17:59:59 +00003459 // FIXME: C++: Verify that operator[] isn't overloaded.
3460
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003461 // C99 6.5.2.1p1
3462 Expr *Idx = static_cast<Expr*>(OC.U.E);
3463 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003464 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3465 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003466
3467 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3468 continue;
3469 }
3470
3471 const RecordType *RC = Res->getType()->getAsRecordType();
3472 if (!RC) {
3473 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003474 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003475 }
3476
3477 // Get the decl corresponding to this.
3478 RecordDecl *RD = RC->getDecl();
3479 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
3480 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003481 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3482 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003483
3484 // FIXME: C++: Verify that MemberDecl isn't a static field.
3485 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003486 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3487 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003488 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3489 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003490 }
3491
3492 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3493 BuiltinLoc);
3494}
3495
3496
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003497Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003498 TypeTy *arg1, TypeTy *arg2,
3499 SourceLocation RPLoc) {
3500 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3501 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3502
3503 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3504
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003505 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003506}
3507
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003508Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003509 ExprTy *expr1, ExprTy *expr2,
3510 SourceLocation RPLoc) {
3511 Expr *CondExpr = static_cast<Expr*>(cond);
3512 Expr *LHSExpr = static_cast<Expr*>(expr1);
3513 Expr *RHSExpr = static_cast<Expr*>(expr2);
3514
3515 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3516
3517 // The conditional expression is required to be a constant expression.
3518 llvm::APSInt condEval(32);
3519 SourceLocation ExpLoc;
3520 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003521 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3522 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00003523
3524 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3525 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3526 RHSExpr->getType();
3527 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3528}
3529
Steve Naroff52a81c02008-09-03 18:15:37 +00003530//===----------------------------------------------------------------------===//
3531// Clang Extensions.
3532//===----------------------------------------------------------------------===//
3533
3534/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003535void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003536 // Analyze block parameters.
3537 BlockSemaInfo *BSI = new BlockSemaInfo();
3538
3539 // Add BSI to CurBlock.
3540 BSI->PrevBlockInfo = CurBlock;
3541 CurBlock = BSI;
3542
3543 BSI->ReturnType = 0;
3544 BSI->TheScope = BlockScope;
3545
Steve Naroff52059382008-10-10 01:28:17 +00003546 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
3547 PushDeclContext(BSI->TheDecl);
3548}
3549
3550void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003551 // Analyze arguments to block.
3552 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3553 "Not a function declarator!");
3554 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3555
Steve Naroff52059382008-10-10 01:28:17 +00003556 CurBlock->hasPrototype = FTI.hasPrototype;
3557 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003558
3559 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3560 // no arguments, not a function that takes a single void argument.
3561 if (FTI.hasPrototype &&
3562 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3563 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3564 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3565 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003566 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003567 } else if (FTI.hasPrototype) {
3568 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003569 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3570 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003571 }
Steve Naroff52059382008-10-10 01:28:17 +00003572 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3573
3574 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3575 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3576 // If this has an identifier, add it to the scope stack.
3577 if ((*AI)->getIdentifier())
3578 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003579}
3580
3581/// ActOnBlockError - If there is an error parsing a block, this callback
3582/// is invoked to pop the information about the block from the action impl.
3583void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3584 // Ensure that CurBlock is deleted.
3585 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3586
3587 // Pop off CurBlock, handle nested blocks.
3588 CurBlock = CurBlock->PrevBlockInfo;
3589
3590 // FIXME: Delete the ParmVarDecl objects as well???
3591
3592}
3593
3594/// ActOnBlockStmtExpr - This is called when the body of a block statement
3595/// literal was successfully completed. ^(int x){...}
3596Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3597 Scope *CurScope) {
3598 // Ensure that CurBlock is deleted.
3599 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3600 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3601
Steve Naroff52059382008-10-10 01:28:17 +00003602 PopDeclContext();
3603
Steve Naroff52a81c02008-09-03 18:15:37 +00003604 // Pop off CurBlock, handle nested blocks.
3605 CurBlock = CurBlock->PrevBlockInfo;
3606
3607 QualType RetTy = Context.VoidTy;
3608 if (BSI->ReturnType)
3609 RetTy = QualType(BSI->ReturnType, 0);
3610
3611 llvm::SmallVector<QualType, 8> ArgTypes;
3612 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3613 ArgTypes.push_back(BSI->Params[i]->getType());
3614
3615 QualType BlockTy;
3616 if (!BSI->hasPrototype)
3617 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3618 else
3619 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003620 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003621
3622 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003623
Steve Naroff95029d92008-10-08 18:44:00 +00003624 BSI->TheDecl->setBody(Body.take());
3625 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003626}
3627
Nate Begemanbd881ef2008-01-30 20:50:20 +00003628/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003629/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003630/// The number of arguments has already been validated to match the number of
3631/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003632static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3633 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003634 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003635 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003636 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3637 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003638
3639 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003640 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003641 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003642 return true;
3643}
3644
3645Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3646 SourceLocation *CommaLocs,
3647 SourceLocation BuiltinLoc,
3648 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003649 // __builtin_overload requires at least 2 arguments
3650 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003651 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3652 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003653
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003654 // The first argument is required to be a constant expression. It tells us
3655 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003656 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003657 Expr *NParamsExpr = Args[0];
3658 llvm::APSInt constEval(32);
3659 SourceLocation ExpLoc;
3660 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003661 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3662 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003663
3664 // Verify that the number of parameters is > 0
3665 unsigned NumParams = constEval.getZExtValue();
3666 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003667 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3668 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003669 // Verify that we have at least 1 + NumParams arguments to the builtin.
3670 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003671 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3672 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003673
3674 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003675 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003676 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003677 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3678 // UsualUnaryConversions will convert the function DeclRefExpr into a
3679 // pointer to function.
3680 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003681 const FunctionTypeProto *FnType = 0;
3682 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3683 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003684
3685 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3686 // parameters, and the number of parameters must match the value passed to
3687 // the builtin.
3688 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003689 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
3690 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003691
3692 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003693 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003694 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003695 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003696 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003697 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
3698 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00003699 // Remember our match, and continue processing the remaining arguments
3700 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003701 OE = new OverloadExpr(Args, NumArgs, i,
3702 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003703 BuiltinLoc, RParenLoc);
3704 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003705 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003706 // Return the newly created OverloadExpr node, if we succeded in matching
3707 // exactly one of the candidate functions.
3708 if (OE)
3709 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003710
3711 // If we didn't find a matching function Expr in the __builtin_overload list
3712 // the return an error.
3713 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003714 for (unsigned i = 0; i != NumParams; ++i) {
3715 if (i != 0) typeNames += ", ";
3716 typeNames += Args[i+1]->getType().getAsString();
3717 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003718
Chris Lattner77d52da2008-11-20 06:06:08 +00003719 return Diag(BuiltinLoc, diag::err_overload_no_match)
3720 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003721}
3722
Anders Carlsson36760332007-10-15 20:28:48 +00003723Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3724 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003725 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003726 Expr *E = static_cast<Expr*>(expr);
3727 QualType T = QualType::getFromOpaquePtr(type);
3728
3729 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003730
3731 // Get the va_list type
3732 QualType VaListType = Context.getBuiltinVaListType();
3733 // Deal with implicit array decay; for example, on x86-64,
3734 // va_list is an array, but it's supposed to decay to
3735 // a pointer for va_arg.
3736 if (VaListType->isArrayType())
3737 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003738 // Make sure the input expression also decays appropriately.
3739 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003740
3741 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003742 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00003743 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003744 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00003745
3746 // FIXME: Warn if a non-POD type is passed in.
3747
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003748 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003749}
3750
Douglas Gregorad4b3792008-11-29 04:51:27 +00003751Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
3752 // The type of __null will be int or long, depending on the size of
3753 // pointers on the target.
3754 QualType Ty;
3755 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
3756 Ty = Context.IntTy;
3757 else
3758 Ty = Context.LongTy;
3759
3760 return new GNUNullExpr(Ty, TokenLoc);
3761}
3762
Chris Lattner005ed752008-01-04 18:04:52 +00003763bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3764 SourceLocation Loc,
3765 QualType DstType, QualType SrcType,
3766 Expr *SrcExpr, const char *Flavor) {
3767 // Decode the result (notice that AST's are still created for extensions).
3768 bool isInvalid = false;
3769 unsigned DiagKind;
3770 switch (ConvTy) {
3771 default: assert(0 && "Unknown conversion type");
3772 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003773 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003774 DiagKind = diag::ext_typecheck_convert_pointer_int;
3775 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003776 case IntToPointer:
3777 DiagKind = diag::ext_typecheck_convert_int_pointer;
3778 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003779 case IncompatiblePointer:
3780 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3781 break;
3782 case FunctionVoidPointer:
3783 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3784 break;
3785 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003786 // If the qualifiers lost were because we were applying the
3787 // (deprecated) C++ conversion from a string literal to a char*
3788 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3789 // Ideally, this check would be performed in
3790 // CheckPointerTypesForAssignment. However, that would require a
3791 // bit of refactoring (so that the second argument is an
3792 // expression, rather than a type), which should be done as part
3793 // of a larger effort to fix CheckPointerTypesForAssignment for
3794 // C++ semantics.
3795 if (getLangOptions().CPlusPlus &&
3796 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3797 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003798 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3799 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003800 case IntToBlockPointer:
3801 DiagKind = diag::err_int_to_block_pointer;
3802 break;
3803 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003804 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003805 break;
Steve Naroff19608432008-10-14 22:18:38 +00003806 case IncompatibleObjCQualifiedId:
3807 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3808 // it can give a more specific diagnostic.
3809 DiagKind = diag::warn_incompatible_qualified_id;
3810 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003811 case Incompatible:
3812 DiagKind = diag::err_typecheck_convert_incompatible;
3813 isInvalid = true;
3814 break;
3815 }
3816
Chris Lattner271d4c22008-11-24 05:29:24 +00003817 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
3818 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00003819 return isInvalid;
3820}
Anders Carlssond5201b92008-11-30 19:50:32 +00003821
3822bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
3823{
3824 Expr::EvalResult EvalResult;
3825
3826 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
3827 EvalResult.HasSideEffects) {
3828 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
3829
3830 if (EvalResult.Diag) {
3831 // We only show the note if it's not the usual "invalid subexpression"
3832 // or if it's actually in a subexpression.
3833 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
3834 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
3835 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3836 }
3837
3838 return true;
3839 }
3840
3841 if (EvalResult.Diag) {
3842 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
3843 E->getSourceRange();
3844
3845 // Print the reason it's not a constant.
3846 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
3847 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3848 }
3849
3850 if (Result)
3851 *Result = EvalResult.Val.getInt();
3852 return false;
3853}