blob: 3ee601faca82340512db58b8f6a5ef8f0d4f3969 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner04421082008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Chris Lattnere7a2e912008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-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).
Argyrios Kyrtzidisc39a3d72008-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 Lattner67d33d82008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-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 Lattner05faf172008-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 Lattnere7a2e912008-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 Gregoreb8f3062008-11-12 17:17:38 +0000102
Chris Lattnere7a2e912008-07-25 21:10:04 +0000103 // For conversion purposes, we ignore any qualifiers.
104 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000105 QualType lhs =
106 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
107 QualType rhs =
108 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-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 Gregorbf3af052008-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 Gregoreb8f3062008-11-12 17:17:38 +0000137
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-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 Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000174 } else if (result < 0) { // The right side is bigger, convert lhs.
175 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000182 return rhs;
183 } else { // handle "_Complex double, double".
Chris Lattnere7a2e912008-07-25 21:10:04 +0000184 return lhs;
185 }
186 }
187 return lhs; // The domain/size match exactly.
188 }
189 // Now handle "real" floating types (i.e. float, double, long double).
190 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
191 // if we have an integer operand, the result is the real floating type.
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000192 if (rhs->isIntegerType()) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000193 // convert rhs to the lhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000194 return lhs;
195 }
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000196 if (rhs->isComplexIntegerType()) {
197 // convert rhs to the complex floating point type.
198 return Context.getComplexType(lhs);
199 }
200 if (lhs->isIntegerType()) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000201 // convert lhs to the rhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000202 return rhs;
203 }
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000204 if (lhs->isComplexIntegerType()) {
205 // convert lhs to the complex floating point type.
206 return Context.getComplexType(rhs);
207 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000208 // We have two real floating types, float/complex combos were handled above.
209 // Convert the smaller operand to the bigger result.
210 int result = Context.getFloatingTypeOrder(lhs, rhs);
211
212 if (result > 0) { // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000213 return lhs;
214 }
215 if (result < 0) { // convert the lhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000216 return rhs;
217 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000218 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattnere7a2e912008-07-25 21:10:04 +0000219 }
220 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
221 // Handle GCC complex int extension.
222 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
223 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
224
225 if (lhsComplexInt && rhsComplexInt) {
226 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
227 rhsComplexInt->getElementType()) >= 0) {
228 // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000229 return lhs;
230 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000231 return rhs;
232 } else if (lhsComplexInt && rhs->isIntegerType()) {
233 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000234 return lhs;
235 } else if (rhsComplexInt && lhs->isIntegerType()) {
236 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000237 return rhs;
238 }
239 }
240 // Finally, we have two differing integer types.
241 // The rules for this case are in C99 6.3.1.8
242 int compare = Context.getIntegerTypeOrder(lhs, rhs);
243 bool lhsSigned = lhs->isSignedIntegerType(),
244 rhsSigned = rhs->isSignedIntegerType();
245 QualType destType;
246 if (lhsSigned == rhsSigned) {
247 // Same signedness; use the higher-ranked type
248 destType = compare >= 0 ? lhs : rhs;
249 } else if (compare != (lhsSigned ? 1 : -1)) {
250 // The unsigned type has greater than or equal rank to the
251 // signed type, so use the unsigned type
252 destType = lhsSigned ? rhs : lhs;
253 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
254 // The two types are different widths; if we are here, that
255 // means the signed type is larger than the unsigned type, so
256 // use the signed type.
257 destType = lhsSigned ? lhs : rhs;
258 } else {
259 // The signed type is higher-ranked than the unsigned type,
260 // but isn't actually any bigger (like unsigned int and long
261 // on most 32-bit systems). Use the unsigned type corresponding
262 // to the signed type.
263 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
264 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000265 return destType;
266}
267
268//===----------------------------------------------------------------------===//
269// Semantic Analysis for various Expression Types
270//===----------------------------------------------------------------------===//
271
272
Steve Narofff69936d2007-09-16 03:34:24 +0000273/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000274/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
275/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
276/// multiple tokens. However, the common case is that StringToks points to one
277/// string.
278///
279Action::ExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000280Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 assert(NumStringToks && "Must have at least one string!");
282
283 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
284 if (Literal.hadError)
285 return ExprResult(true);
286
287 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
288 for (unsigned i = 0; i != NumStringToks; ++i)
289 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000290
291 // Verify that pascal strings aren't too large.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000292 if (Literal.Pascal && Literal.GetStringLength() > 256)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000293 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
294 << SourceRange(StringToks[0].getLocation(),
295 StringToks[NumStringToks-1].getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000296
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000297 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000298 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000299 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000300
301 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
302 if (getLangOptions().CPlusPlus)
303 StrTy.addConst();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000304
305 // Get an array type for the string, according to C99 6.4.5. This includes
306 // the nul terminator character as well as the string length for pascal
307 // strings.
308 StrTy = Context.getConstantArrayType(StrTy,
309 llvm::APInt(32, Literal.GetStringLength()+1),
310 ArrayType::Normal, 0);
311
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
313 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000314 Literal.AnyWide, StrTy,
Anders Carlssonee98ac52007-10-15 02:50:23 +0000315 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000316 StringToks[NumStringToks-1].getLocation());
317}
318
Chris Lattner639e2d32008-10-20 05:16:36 +0000319/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
320/// CurBlock to VD should cause it to be snapshotted (as we do for auto
321/// variables defined outside the block) or false if this is not needed (e.g.
322/// for values inside the block or for globals).
323///
324/// FIXME: This will create BlockDeclRefExprs for global variables,
325/// function references, etc which is suboptimal :) and breaks
326/// things like "integer constant expression" tests.
327static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
328 ValueDecl *VD) {
329 // If the value is defined inside the block, we couldn't snapshot it even if
330 // we wanted to.
331 if (CurBlock->TheDecl == VD->getDeclContext())
332 return false;
333
334 // If this is an enum constant or function, it is constant, don't snapshot.
335 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
336 return false;
337
338 // If this is a reference to an extern, static, or global variable, no need to
339 // snapshot it.
340 // FIXME: What about 'const' variables in C++?
341 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
342 return Var->hasLocalStorage();
343
344 return true;
345}
346
347
348
Steve Naroff08d92e42007-09-15 18:49:24 +0000349/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000350/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000351/// identifier is used in a function call context.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000352/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the
353/// class or namespace that the identifier must be a member of.
Steve Naroff08d92e42007-09-15 18:49:24 +0000354Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000355 IdentifierInfo &II,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000356 bool HasTrailingLParen,
357 const CXXScopeSpec *SS) {
Douglas Gregor10c42622008-11-18 15:03:34 +0000358 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
359}
360
361/// ActOnDeclarationNameExpr - The parser has read some kind of name
362/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
363/// performs lookup on that name and returns an expression that refers
364/// to that name. This routine isn't directly called from the parser,
365/// because the parser doesn't know about DeclarationName. Rather,
366/// this routine is called by ActOnIdentifierExpr,
367/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
368/// which form the DeclarationName from the corresponding syntactic
369/// forms.
370///
371/// HasTrailingLParen indicates whether this identifier is used in a
372/// function call context. LookupCtx is only used for a C++
373/// qualified-id (foo::bar) to indicate the class or namespace that
374/// the identifier must be a member of.
Douglas Gregor5c37de72008-12-06 00:22:45 +0000375///
376/// If ForceResolution is true, then we will attempt to resolve the
377/// name even if it looks like a dependent name. This option is off by
378/// default.
Douglas Gregor10c42622008-11-18 15:03:34 +0000379Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
380 DeclarationName Name,
381 bool HasTrailingLParen,
Douglas Gregor5c37de72008-12-06 00:22:45 +0000382 const CXXScopeSpec *SS,
383 bool ForceResolution) {
384 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
385 HasTrailingLParen && !SS && !ForceResolution) {
386 // We've seen something of the form
387 // identifier(
388 // and we are in a template, so it is likely that 's' is a
389 // dependent name. However, we won't know until we've parsed all
390 // of the call arguments. So, build a CXXDependentNameExpr node
391 // to represent this name. Then, if it turns out that none of the
392 // arguments are type-dependent, we'll force the resolution of the
393 // dependent name at that point.
394 return new CXXDependentNameExpr(Name.getAsIdentifierInfo(),
395 Context.DependentTy, Loc);
396 }
397
Chris Lattner8a934232008-03-31 00:36:02 +0000398 // Could be enum-constant, value decl, instance variable, etc.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000399 Decl *D;
400 if (SS && !SS->isEmpty()) {
401 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
402 if (DC == 0)
403 return true;
Douglas Gregor10c42622008-11-18 15:03:34 +0000404 D = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000405 } else
Douglas Gregor10c42622008-11-18 15:03:34 +0000406 D = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Douglas Gregor5c37de72008-12-06 00:22:45 +0000407
Chris Lattner8a934232008-03-31 00:36:02 +0000408 // If this reference is in an Objective-C method, then ivar lookup happens as
409 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000410 IdentifierInfo *II = Name.getAsIdentifierInfo();
411 if (II && getCurMethodDecl()) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000412 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattner8a934232008-03-31 00:36:02 +0000413 // There are two cases to handle here. 1) scoped lookup could have failed,
414 // in which case we should look for an ivar. 2) scoped lookup could have
415 // found a decl, but that decl is outside the current method (i.e. a global
416 // variable). In these two cases, we do a lookup for an ivar with this
417 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe8043c32008-04-01 23:04:06 +0000418 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000419 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregor10c42622008-11-18 15:03:34 +0000420 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner8a934232008-03-31 00:36:02 +0000421 // FIXME: This should use a new expr for a direct reference, don't turn
422 // this into Self->ivar, just return a BareIVarExpr or something.
423 IdentifierInfo &II = Context.Idents.get("self");
424 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +0000425 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), Loc,
426 static_cast<Expr*>(SelfExpr.Val), true, true);
427 Context.setFieldDecl(IFace, IV, MRef);
428 return MRef;
Chris Lattner8a934232008-03-31 00:36:02 +0000429 }
430 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000431 // Needed to implement property "super.method" notation.
Chris Lattner84692652008-11-20 05:35:30 +0000432 if (SD == 0 && II->isStr("super")) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000433 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000434 getCurMethodDecl()->getClassInterface()));
Douglas Gregorcd9b46e2008-11-04 14:56:14 +0000435 return new ObjCSuperExpr(Loc, T);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000436 }
Chris Lattner8a934232008-03-31 00:36:02 +0000437 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000438 if (D == 0) {
439 // Otherwise, this could be an implicitly declared function reference (legal
440 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000441 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000442 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000443 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000444 else {
445 // If this name wasn't predeclared and if this is not a function call,
446 // diagnose the problem.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000447 if (SS && !SS->isEmpty())
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000448 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattner08631c52008-11-23 21:45:46 +0000449 << Name << SS->getRange();
Douglas Gregor10c42622008-11-18 15:03:34 +0000450 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
451 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000452 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000453 else
Chris Lattner08631c52008-11-23 21:45:46 +0000454 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Reid Spencer5f016e22007-07-11 17:01:13 +0000455 }
456 }
Chris Lattner8a934232008-03-31 00:36:02 +0000457
Douglas Gregor44b43212008-12-11 16:49:14 +0000458 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000459 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
460 if (MD->isStatic())
461 // "invalid use of member 'x' in static member function"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000462 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000463 << FD->getDeclName();
Douglas Gregor44b43212008-12-11 16:49:14 +0000464 if (MD->getParent() != FD->getDeclContext())
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000465 // "invalid use of nonstatic data member 'x'"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000466 return Diag(Loc, diag::err_invalid_non_static_member_use)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000467 << FD->getDeclName();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000468
469 if (FD->isInvalidDecl())
470 return true;
471
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +0000472 // FIXME: Handle 'mutable'.
473 return new DeclRefExpr(FD,
474 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000475 }
476
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000477 return Diag(Loc, diag::err_invalid_non_static_member_use)
478 << FD->getDeclName();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000479 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000480 if (isa<TypedefDecl>(D))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000481 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000482 if (isa<ObjCInterfaceDecl>(D))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000483 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000484 if (isa<NamespaceDecl>(D))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000485 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Reid Spencer5f016e22007-07-11 17:01:13 +0000486
Steve Naroffdd972f22008-09-05 22:11:13 +0000487 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000488 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
489 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
490
Steve Naroffdd972f22008-09-05 22:11:13 +0000491 ValueDecl *VD = cast<ValueDecl>(D);
492
493 // check if referencing an identifier with __attribute__((deprecated)).
494 if (VD->getAttr<DeprecatedAttr>())
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000495 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000496
497 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
498 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
499 Scope *CheckS = S;
500 while (CheckS) {
501 if (CheckS->isWithinElse() &&
502 CheckS->getControlParent()->isDeclScope(Var)) {
503 if (Var->getType()->isBooleanType())
504 Diag(Loc, diag::warn_value_always_false) << Var->getDeclName();
505 else
506 Diag(Loc, diag::warn_value_always_zero) << Var->getDeclName();
507 break;
508 }
509
510 // Move up one more control parent to check again.
511 CheckS = CheckS->getControlParent();
512 if (CheckS)
513 CheckS = CheckS->getParent();
514 }
515 }
516 }
Steve Naroffdd972f22008-09-05 22:11:13 +0000517
518 // Only create DeclRefExpr's for valid Decl's.
519 if (VD->isInvalidDecl())
520 return true;
Chris Lattner639e2d32008-10-20 05:16:36 +0000521
522 // If the identifier reference is inside a block, and it refers to a value
523 // that is outside the block, create a BlockDeclRefExpr instead of a
524 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
525 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000526 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000527 // We do not do this for things like enum constants, global variables, etc,
528 // as they do not get snapshotted.
529 //
530 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff090276f2008-10-10 01:28:17 +0000531 // The BlocksAttr indicates the variable is bound by-reference.
532 if (VD->getAttr<BlocksAttr>())
Douglas Gregor9d293df2008-10-28 00:22:11 +0000533 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
534 Loc, true);
Steve Naroff090276f2008-10-10 01:28:17 +0000535
536 // Variable will be bound by-copy, make it const within the closure.
537 VD->getType().addConst();
Douglas Gregor9d293df2008-10-28 00:22:11 +0000538 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
539 Loc, false);
Steve Naroff090276f2008-10-10 01:28:17 +0000540 }
541 // If this reference is not in a block or if the referenced variable is
542 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +0000543
Douglas Gregor898574e2008-12-05 23:32:09 +0000544 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +0000545 bool ValueDependent = false;
546 if (getLangOptions().CPlusPlus) {
547 // C++ [temp.dep.expr]p3:
548 // An id-expression is type-dependent if it contains:
549 // - an identifier that was declared with a dependent type,
550 if (VD->getType()->isDependentType())
551 TypeDependent = true;
552 // - FIXME: a template-id that is dependent,
553 // - a conversion-function-id that specifies a dependent type,
554 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
555 Name.getCXXNameType()->isDependentType())
556 TypeDependent = true;
557 // - a nested-name-specifier that contains a class-name that
558 // names a dependent type.
559 else if (SS && !SS->isEmpty()) {
560 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
561 DC; DC = DC->getParent()) {
562 // FIXME: could stop early at namespace scope.
563 if (DC->isCXXRecord()) {
564 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
565 if (Context.getTypeDeclType(Record)->isDependentType()) {
566 TypeDependent = true;
567 break;
568 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000569 }
570 }
571 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000572
Douglas Gregor83f96f62008-12-10 20:57:37 +0000573 // C++ [temp.dep.constexpr]p2:
574 //
575 // An identifier is value-dependent if it is:
576 // - a name declared with a dependent type,
577 if (TypeDependent)
578 ValueDependent = true;
579 // - the name of a non-type template parameter,
580 else if (isa<NonTypeTemplateParmDecl>(VD))
581 ValueDependent = true;
582 // - a constant with integral or enumeration type and is
583 // initialized with an expression that is value-dependent
584 // (FIXME!).
585 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000586
587 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
588 TypeDependent, ValueDependent);
Reid Spencer5f016e22007-07-11 17:01:13 +0000589}
590
Chris Lattnerd9f69102008-08-10 01:53:14 +0000591Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000592 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000593 PredefinedExpr::IdentType IT;
Anders Carlsson22742662007-07-21 05:21:51 +0000594
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000596 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000597 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
598 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
599 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000600 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000601
Chris Lattnerfa28b302008-01-12 08:14:25 +0000602 // Pre-defined identifiers are of type char[x], where x is the length of the
603 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000604 unsigned Length;
Chris Lattner371f2582008-12-04 23:50:19 +0000605 if (FunctionDecl *FD = getCurFunctionDecl())
606 Length = FD->getIdentifier()->getLength();
Chris Lattnerb0da9232008-12-12 05:05:20 +0000607 else if (ObjCMethodDecl *MD = getCurMethodDecl())
608 Length = MD->getSynthesizedMethodSize();
609 else {
610 Diag(Loc, diag::ext_predef_outside_function);
611 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
612 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
613 }
614
Chris Lattner1423ea42008-01-12 18:39:25 +0000615
Chris Lattner8f978d52008-01-12 19:32:28 +0000616 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000617 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000618 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerd9f69102008-08-10 01:53:14 +0000619 return new PredefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000620}
621
Steve Narofff69936d2007-09-16 03:34:24 +0000622Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000623 llvm::SmallString<16> CharBuffer;
624 CharBuffer.resize(Tok.getLength());
625 const char *ThisTokBegin = &CharBuffer[0];
626 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
627
628 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
629 Tok.getLocation(), PP);
630 if (Literal.hadError())
631 return ExprResult(true);
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000632
633 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
634
Chris Lattnerc250aae2008-06-07 22:35:38 +0000635 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
636 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000637}
638
Steve Narofff69936d2007-09-16 03:34:24 +0000639Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 // fast path for a single digit (which is quite common). A single digit
641 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
642 if (Tok.getLength() == 1) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000643 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000644
Chris Lattner98be4942008-03-05 18:54:05 +0000645 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000646 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +0000647 Context.IntTy,
648 Tok.getLocation()));
649 }
650 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000651 // Add padding so that NumericLiteralParser can overread by one character.
652 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000653 const char *ThisTokBegin = &IntegerBuffer[0];
654
655 // Get the spelling of the token, which eliminates trigraphs, etc.
656 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner28997ec2008-09-30 20:51:14 +0000657
Reid Spencer5f016e22007-07-11 17:01:13 +0000658 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
659 Tok.getLocation(), PP);
660 if (Literal.hadError)
661 return ExprResult(true);
662
Chris Lattner5d661452007-08-26 03:42:43 +0000663 Expr *Res;
664
665 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000666 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000667 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000668 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000669 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000670 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000671 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000672 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000673
674 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
675
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000676 // isExact will be set by GetFloatValue().
677 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000678 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000679 Ty, Tok.getLocation());
680
Chris Lattner5d661452007-08-26 03:42:43 +0000681 } else if (!Literal.isIntegerLiteral()) {
682 return ExprResult(true);
683 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000684 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000685
Neil Boothb9449512007-08-29 22:00:19 +0000686 // long long is a C99 feature.
687 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000688 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000689 Diag(Tok.getLocation(), diag::ext_longlong);
690
Reid Spencer5f016e22007-07-11 17:01:13 +0000691 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000692 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000693
694 if (Literal.GetIntegerValue(ResultVal)) {
695 // If this value didn't fit into uintmax_t, warn and force to ull.
696 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000697 Ty = Context.UnsignedLongLongTy;
698 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000699 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 } else {
701 // If this value fits into a ULL, try to figure out what else it fits into
702 // according to the rules of C99 6.4.4.1p5.
703
704 // Octal, Hexadecimal, and integers with a U suffix are allowed to
705 // be an unsigned int.
706 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
707
708 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000709 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000710 if (!Literal.isLong && !Literal.isLongLong) {
711 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000712 unsigned IntSize = Context.Target.getIntWidth();
713
Reid Spencer5f016e22007-07-11 17:01:13 +0000714 // Does it fit in a unsigned int?
715 if (ResultVal.isIntN(IntSize)) {
716 // Does it fit in a signed int?
717 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000718 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000719 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000720 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000721 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000722 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000723 }
724
725 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000726 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000727 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000728
729 // Does it fit in a unsigned long?
730 if (ResultVal.isIntN(LongSize)) {
731 // Does it fit in a signed long?
732 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000733 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000735 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000736 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000738 }
739
740 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000741 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000742 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000743
744 // Does it fit in a unsigned long long?
745 if (ResultVal.isIntN(LongLongSize)) {
746 // Does it fit in a signed long long?
747 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000748 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000749 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000750 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000751 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000752 }
753 }
754
755 // If we still couldn't decide a type, we probably have something that
756 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000757 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000758 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000759 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000760 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000762
763 if (ResultVal.getBitWidth() != Width)
764 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 }
766
Chris Lattnerf0467b32008-04-02 04:24:33 +0000767 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000768 }
Chris Lattner5d661452007-08-26 03:42:43 +0000769
770 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
771 if (Literal.isImaginary)
772 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
773
774 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000775}
776
Steve Narofff69936d2007-09-16 03:34:24 +0000777Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000778 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000779 Expr *E = (Expr *)Val;
780 assert((E != 0) && "ActOnParenExpr() missing expr");
781 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +0000782}
783
784/// The UsualUnaryConversions() function is *not* called by this routine.
785/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl05189992008-11-11 17:56:53 +0000786bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
787 SourceLocation OpLoc,
788 const SourceRange &ExprRange,
789 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000790 // C99 6.5.3.4p1:
791 if (isa<FunctionType>(exprType) && isSizeof)
792 // alignof(function) is allowed.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000793 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Reid Spencer5f016e22007-07-11 17:01:13 +0000794 else if (exprType->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000795 Diag(OpLoc, diag::ext_sizeof_void_type)
796 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
797 else if (exprType->isIncompleteType())
798 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
799 diag::err_alignof_incomplete_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000800 << exprType << ExprRange;
Sebastian Redl05189992008-11-11 17:56:53 +0000801
802 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000803}
804
Sebastian Redl05189992008-11-11 17:56:53 +0000805/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
806/// the same for @c alignof and @c __alignof
807/// Note that the ArgRange is invalid if isType is false.
808Action::ExprResult
809Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
810 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000811 // If error parsing type, ignore.
Sebastian Redl05189992008-11-11 17:56:53 +0000812 if (TyOrEx == 0) return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000813
Sebastian Redl05189992008-11-11 17:56:53 +0000814 QualType ArgTy;
815 SourceRange Range;
816 if (isType) {
817 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
818 Range = ArgRange;
819 } else {
820 // Get the end location.
821 Expr *ArgEx = (Expr *)TyOrEx;
822 Range = ArgEx->getSourceRange();
823 ArgTy = ArgEx->getType();
824 }
825
826 // Verify that the operand is valid.
827 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Reid Spencer5f016e22007-07-11 17:01:13 +0000828 return true;
Sebastian Redl05189992008-11-11 17:56:53 +0000829
830 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
831 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
832 OpLoc, Range.getEnd());
Reid Spencer5f016e22007-07-11 17:01:13 +0000833}
834
Chris Lattner5d794252007-08-24 21:41:10 +0000835QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000836 DefaultFunctionArrayConversion(V);
837
Chris Lattnercc26ed72007-08-26 05:39:26 +0000838 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000839 if (const ComplexType *CT = V->getType()->getAsComplexType())
840 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000841
842 // Otherwise they pass through real integer and floating point types here.
843 if (V->getType()->isArithmeticType())
844 return V->getType();
845
846 // Reject anything else.
Chris Lattnerd1625842008-11-24 06:25:27 +0000847 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnercc26ed72007-08-26 05:39:26 +0000848 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +0000849}
850
851
Reid Spencer5f016e22007-07-11 17:01:13 +0000852
Douglas Gregor74253732008-11-19 15:42:04 +0000853Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000854 tok::TokenKind Kind,
855 ExprTy *Input) {
Douglas Gregor74253732008-11-19 15:42:04 +0000856 Expr *Arg = (Expr *)Input;
857
Reid Spencer5f016e22007-07-11 17:01:13 +0000858 UnaryOperator::Opcode Opc;
859 switch (Kind) {
860 default: assert(0 && "Unknown unary op!");
861 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
862 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
863 }
Douglas Gregor74253732008-11-19 15:42:04 +0000864
865 if (getLangOptions().CPlusPlus &&
866 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
867 // Which overloaded operator?
868 OverloadedOperatorKind OverOp =
869 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
870
871 // C++ [over.inc]p1:
872 //
873 // [...] If the function is a member function with one
874 // parameter (which shall be of type int) or a non-member
875 // function with two parameters (the second of which shall be
876 // of type int), it defines the postfix increment operator ++
877 // for objects of that type. When the postfix increment is
878 // called as a result of using the ++ operator, the int
879 // argument will have value zero.
880 Expr *Args[2] = {
881 Arg,
882 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
883 /*isSigned=*/true),
884 Context.IntTy, SourceLocation())
885 };
886
887 // Build the candidate set for overloading
888 OverloadCandidateSet CandidateSet;
889 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
890
891 // Perform overload resolution.
892 OverloadCandidateSet::iterator Best;
893 switch (BestViableFunction(CandidateSet, Best)) {
894 case OR_Success: {
895 // We found a built-in operator or an overloaded operator.
896 FunctionDecl *FnDecl = Best->Function;
897
898 if (FnDecl) {
899 // We matched an overloaded operator. Build a call to that
900 // operator.
901
902 // Convert the arguments.
903 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
904 if (PerformObjectArgumentInitialization(Arg, Method))
905 return true;
906 } else {
907 // Convert the arguments.
908 if (PerformCopyInitialization(Arg,
909 FnDecl->getParamDecl(0)->getType(),
910 "passing"))
911 return true;
912 }
913
914 // Determine the result type
915 QualType ResultTy
916 = FnDecl->getType()->getAsFunctionType()->getResultType();
917 ResultTy = ResultTy.getNonReferenceType();
918
919 // Build the actual expression node.
920 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
921 SourceLocation());
922 UsualUnaryConversions(FnExpr);
923
924 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
925 } else {
926 // We matched a built-in operator. Convert the arguments, then
927 // break out so that we will build the appropriate built-in
928 // operator node.
929 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
930 "passing"))
931 return true;
932
933 break;
934 }
935 }
936
937 case OR_No_Viable_Function:
938 // No viable function; fall through to handling this as a
939 // built-in operator, which will produce an error message for us.
940 break;
941
942 case OR_Ambiguous:
943 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
944 << UnaryOperator::getOpcodeStr(Opc)
945 << Arg->getSourceRange();
946 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
947 return true;
948 }
949
950 // Either we found no viable overloaded operator or we matched a
951 // built-in operator. In either case, fall through to trying to
952 // build a built-in operation.
953 }
954
955 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000956 if (result.isNull())
957 return true;
Douglas Gregor74253732008-11-19 15:42:04 +0000958 return new UnaryOperator(Arg, Opc, result, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000959}
960
961Action::ExprResult Sema::
Douglas Gregor337c6b92008-11-19 17:17:41 +0000962ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000963 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000964 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000965
Douglas Gregor337c6b92008-11-19 17:17:41 +0000966 if (getLangOptions().CPlusPlus &&
Eli Friedman03f332a2008-12-15 22:34:21 +0000967 (LHSExp->getType()->isRecordType() ||
968 LHSExp->getType()->isEnumeralType() ||
969 RHSExp->getType()->isRecordType() ||
970 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor337c6b92008-11-19 17:17:41 +0000971 // Add the appropriate overloaded operators (C++ [over.match.oper])
972 // to the candidate set.
973 OverloadCandidateSet CandidateSet;
974 Expr *Args[2] = { LHSExp, RHSExp };
975 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
976
977 // Perform overload resolution.
978 OverloadCandidateSet::iterator Best;
979 switch (BestViableFunction(CandidateSet, Best)) {
980 case OR_Success: {
981 // We found a built-in operator or an overloaded operator.
982 FunctionDecl *FnDecl = Best->Function;
983
984 if (FnDecl) {
985 // We matched an overloaded operator. Build a call to that
986 // operator.
987
988 // Convert the arguments.
989 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
990 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
991 PerformCopyInitialization(RHSExp,
992 FnDecl->getParamDecl(0)->getType(),
993 "passing"))
994 return true;
995 } else {
996 // Convert the arguments.
997 if (PerformCopyInitialization(LHSExp,
998 FnDecl->getParamDecl(0)->getType(),
999 "passing") ||
1000 PerformCopyInitialization(RHSExp,
1001 FnDecl->getParamDecl(1)->getType(),
1002 "passing"))
1003 return true;
1004 }
1005
1006 // Determine the result type
1007 QualType ResultTy
1008 = FnDecl->getType()->getAsFunctionType()->getResultType();
1009 ResultTy = ResultTy.getNonReferenceType();
1010
1011 // Build the actual expression node.
1012 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1013 SourceLocation());
1014 UsualUnaryConversions(FnExpr);
1015
1016 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
1017 } else {
1018 // We matched a built-in operator. Convert the arguments, then
1019 // break out so that we will build the appropriate built-in
1020 // operator node.
1021 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1022 "passing") ||
1023 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1024 "passing"))
1025 return true;
1026
1027 break;
1028 }
1029 }
1030
1031 case OR_No_Viable_Function:
1032 // No viable function; fall through to handling this as a
1033 // built-in operator, which will produce an error message for us.
1034 break;
1035
1036 case OR_Ambiguous:
1037 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1038 << "[]"
1039 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1040 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1041 return true;
1042 }
1043
1044 // Either we found no viable overloaded operator or we matched a
1045 // built-in operator. In either case, fall through to trying to
1046 // build a built-in operation.
1047 }
1048
Chris Lattner12d9ff62007-07-16 00:14:47 +00001049 // Perform default conversions.
1050 DefaultFunctionArrayConversion(LHSExp);
1051 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +00001052
Chris Lattner12d9ff62007-07-16 00:14:47 +00001053 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001054
Reid Spencer5f016e22007-07-11 17:01:13 +00001055 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001056 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +00001057 // in the subscript position. As a result, we need to derive the array base
1058 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001059 Expr *BaseExpr, *IndexExpr;
1060 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +00001061 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001062 BaseExpr = LHSExp;
1063 IndexExpr = RHSExp;
1064 // FIXME: need to deal with const...
1065 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +00001066 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001067 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001068 BaseExpr = RHSExp;
1069 IndexExpr = LHSExp;
1070 // FIXME: need to deal with const...
1071 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +00001072 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1073 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001074 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +00001075
1076 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +00001077 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1078 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001079 return Diag(LLoc, diag::err_ext_vector_component_access)
1080 << SourceRange(LLoc, RLoc);
Chris Lattner12d9ff62007-07-16 00:14:47 +00001081 // FIXME: need to deal with const...
1082 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001084 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
1085 << RHSExp->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001086 }
1087 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +00001088 if (!IndexExpr->getType()->isIntegerType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001089 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
1090 << IndexExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001091
Chris Lattner12d9ff62007-07-16 00:14:47 +00001092 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1093 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001094 // void (*)(int)) and pointers to incomplete types. Functions are not
1095 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001096 if (!ResultType->isObjectType())
1097 return Diag(BaseExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001098 diag::err_typecheck_subscript_not_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00001099 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner12d9ff62007-07-16 00:14:47 +00001100
1101 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001102}
1103
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001104QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001105CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001106 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001107 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001108
1109 // This flag determines whether or not the component is to be treated as a
1110 // special name, or a regular GLSL-style component access.
1111 bool SpecialComponent = false;
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001112
1113 // The vector accessor can't exceed the number of elements.
1114 const char *compStr = CompName.getName();
1115 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001116 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattnerd1625842008-11-24 06:25:27 +00001117 << baseType << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001118 return QualType();
1119 }
Nate Begeman8a997642008-05-09 06:41:27 +00001120
1121 // Check that we've found one of the special components, or that the component
1122 // names must come from the same set.
1123 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1124 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1125 SpecialComponent = true;
1126 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001127 do
1128 compStr++;
1129 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1130 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1131 do
1132 compStr++;
1133 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1134 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1135 do
1136 compStr++;
1137 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1138 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001139
Nate Begeman8a997642008-05-09 06:41:27 +00001140 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001141 // We didn't get to the end of the string. This means the component names
1142 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001143 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1144 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001145 return QualType();
1146 }
1147 // Each component accessor can't exceed the vector type.
1148 compStr = CompName.getName();
1149 while (*compStr) {
1150 if (vecType->isAccessorWithinNumElements(*compStr))
1151 compStr++;
1152 else
1153 break;
1154 }
Nate Begeman8a997642008-05-09 06:41:27 +00001155 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001156 // We didn't get to the end of the string. This means a component accessor
1157 // exceeds the number of elements in the vector.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001158 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattnerd1625842008-11-24 06:25:27 +00001159 << baseType << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001160 return QualType();
1161 }
Nate Begeman8a997642008-05-09 06:41:27 +00001162
1163 // If we have a special component name, verify that the current vector length
1164 // is an even number, since all special component names return exactly half
1165 // the elements.
1166 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001167 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001168 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001169 return QualType();
1170 }
1171
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001172 // The component accessor looks fine - now we need to compute the actual type.
1173 // The vector type is implied by the component accessor. For example,
1174 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001175 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1176 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner3c73c412008-11-19 08:23:25 +00001177 : CompName.getLength();
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001178 if (CompSize == 1)
1179 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +00001180
Nate Begeman213541a2008-04-18 23:10:10 +00001181 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +00001182 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001183 // diagostics look bad. We want extended vector types to appear built-in.
1184 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1185 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1186 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001187 }
1188 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001189}
1190
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001191/// constructSetterName - Return the setter name for the given
1192/// identifier, i.e. "set" + Name where the initial character of Name
1193/// has been capitalized.
1194// FIXME: Merge with same routine in Parser. But where should this
1195// live?
1196static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1197 const IdentifierInfo *Name) {
1198 llvm::SmallString<100> SelectorName;
1199 SelectorName = "set";
1200 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1201 SelectorName[3] = toupper(SelectorName[3]);
1202 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1203}
1204
Reid Spencer5f016e22007-07-11 17:01:13 +00001205Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001206ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001207 tok::TokenKind OpKind, SourceLocation MemberLoc,
1208 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001209 Expr *BaseExpr = static_cast<Expr *>(Base);
1210 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +00001211
1212 // Perform default conversions.
1213 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001214
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001215 QualType BaseType = BaseExpr->getType();
1216 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00001217
Chris Lattner68a057b2008-07-21 04:36:39 +00001218 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1219 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001220 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +00001221 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001222 BaseType = PT->getPointeeType();
Douglas Gregor8ba10742008-11-20 16:27:02 +00001223 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
1224 return BuildOverloadedArrowExpr(BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001225 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001226 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00001227 << BaseType << BaseExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001229
Chris Lattner68a057b2008-07-21 04:36:39 +00001230 // Handle field access to simple records. This also handles access to fields
1231 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +00001232 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001233 RecordDecl *RDecl = RTy->getDecl();
1234 if (RTy->isIncompleteType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001235 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001236 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001237 // The record definition is complete, now make sure the member is valid.
Douglas Gregor44b43212008-12-11 16:49:14 +00001238 // FIXME: Qualified name lookup for C++ is a bit more complicated
1239 // than this.
1240 DeclContext::lookup_result Lookup = RDecl->lookup(Context, &Member);
1241 if (Lookup.first == Lookup.second) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001242 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner3c73c412008-11-19 08:23:25 +00001243 << &Member << BaseExpr->getSourceRange();
Douglas Gregor44b43212008-12-11 16:49:14 +00001244 }
1245
1246 FieldDecl *MemberDecl = dyn_cast<FieldDecl>(*Lookup.first);
1247 if (!MemberDecl) {
1248 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
1249 "Clang only supports references to members");
1250 return Diag(MemberLoc, DiagID);
1251 }
Eli Friedman51019072008-02-06 22:48:16 +00001252
1253 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedman64ec0cc2008-02-07 05:24:51 +00001254 // FIXME: Handle address space modifiers
Eli Friedman51019072008-02-06 22:48:16 +00001255 QualType MemberType = MemberDecl->getType();
1256 unsigned combinedQualifiers =
Chris Lattnerf46699c2008-02-20 20:55:12 +00001257 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor44b43212008-12-11 16:49:14 +00001258 if (MemberDecl->isMutable())
1259 combinedQualifiers &= ~QualType::Const;
Eli Friedman51019072008-02-06 22:48:16 +00001260 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1261
Chris Lattner68a057b2008-07-21 04:36:39 +00001262 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman51019072008-02-06 22:48:16 +00001263 MemberLoc, MemberType);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001264 }
1265
Chris Lattnera38e6b12008-07-21 04:59:05 +00001266 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1267 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +00001268 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001269 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +00001270 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc,
1271 BaseExpr,
1272 OpKind == tok::arrow);
1273 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
1274 return MRef;
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001275 }
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001276 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001277 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001278 << BaseExpr->getSourceRange();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001279 }
1280
Chris Lattnera38e6b12008-07-21 04:59:05 +00001281 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1282 // pointer to a (potentially qualified) interface type.
1283 const PointerType *PTy;
1284 const ObjCInterfaceType *IFTy;
1285 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1286 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1287 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001288
Daniel Dunbar2307d312008-09-03 01:05:41 +00001289 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +00001290 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1291 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1292
Daniel Dunbar2307d312008-09-03 01:05:41 +00001293 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00001294 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1295 E = IFTy->qual_end(); I != E; ++I)
1296 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1297 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +00001298
1299 // If that failed, look for an "implicit" property by seeing if the nullary
1300 // selector is implemented.
1301
1302 // FIXME: The logic for looking up nullary and unary selectors should be
1303 // shared with the code in ActOnInstanceMessage.
1304
1305 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1306 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1307
1308 // If this reference is in an @implementation, check for 'private' methods.
1309 if (!Getter)
1310 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1311 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1312 if (ObjCImplementationDecl *ImpDecl =
1313 ObjCImplementations[ClassDecl->getIdentifier()])
1314 Getter = ImpDecl->getInstanceMethod(Sel);
1315
Steve Naroff7692ed62008-10-22 19:16:27 +00001316 // Look through local category implementations associated with the class.
1317 if (!Getter) {
1318 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1319 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1320 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1321 }
1322 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001323 if (Getter) {
1324 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001325 // will look for the matching setter, in case it is needed.
1326 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1327 &Member);
1328 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1329 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1330 if (!Setter) {
1331 // If this reference is in an @implementation, also check for 'private'
1332 // methods.
1333 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1334 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1335 if (ObjCImplementationDecl *ImpDecl =
1336 ObjCImplementations[ClassDecl->getIdentifier()])
1337 Setter = ImpDecl->getInstanceMethod(SetterSel);
1338 }
1339 // Look through local category implementations associated with the class.
1340 if (!Setter) {
1341 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1342 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1343 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1344 }
1345 }
1346
1347 // FIXME: we must check that the setter has property type.
1348 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00001349 MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +00001350 }
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001351 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001352 // Handle properties on qualified "id" protocols.
1353 const ObjCQualifiedIdType *QIdTy;
1354 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1355 // Check protocols on qualified interfaces.
1356 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001357 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroff18bc1642008-10-20 22:53:06 +00001358 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1359 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001360 // Also must look for a getter name which uses property syntax.
1361 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1362 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1363 return new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(), OMD,
1364 OpLoc, MemberLoc, NULL, 0);
1365 }
1366 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001367 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001368 // Handle 'field access' to vectors, such as 'V.xx'.
1369 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1370 // Component access limited to variables (reject vec4.rg.g).
1371 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1372 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001373 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1374 << BaseExpr->getSourceRange();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001375 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1376 if (ret.isNull())
1377 return true;
1378 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1379 }
1380
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001381 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattnerd1625842008-11-24 06:25:27 +00001382 << BaseType << BaseExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001383}
1384
Steve Narofff69936d2007-09-16 03:34:24 +00001385/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001386/// This provides the location of the left/right parens and a list of comma
1387/// locations.
1388Action::ExprResult Sema::
Douglas Gregor5c37de72008-12-06 00:22:45 +00001389ActOnCallExpr(Scope *S, ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +00001390 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +00001392 Expr *Fn = static_cast<Expr *>(fn);
1393 Expr **Args = reinterpret_cast<Expr**>(args);
1394 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001395 FunctionDecl *FDecl = NULL;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001396 OverloadedFunctionDecl *Ovl = NULL;
1397
Douglas Gregor5c37de72008-12-06 00:22:45 +00001398 // Determine whether this is a dependent call inside a C++ template,
1399 // in which case we won't do any semantic analysis now.
1400 bool Dependent = false;
1401 if (Fn->isTypeDependent()) {
1402 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1403 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1404 Dependent = true;
1405 else {
1406 // Resolve the CXXDependentNameExpr to an actual identifier;
1407 // it wasn't really a dependent name after all.
1408 ExprResult Resolved
1409 = ActOnDeclarationNameExpr(S, FnName->getLocation(), FnName->getName(),
1410 /*HasTrailingLParen=*/true,
1411 /*SS=*/0,
1412 /*ForceResolution=*/true);
1413 if (Resolved.isInvalid)
1414 return true;
1415 else {
1416 delete Fn;
1417 Fn = (Expr *)Resolved.Val;
1418 }
1419 }
1420 } else
1421 Dependent = true;
1422 } else
1423 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1424
Douglas Gregor898574e2008-12-05 23:32:09 +00001425 // FIXME: Will need to cache the results of name lookup (including
1426 // ADL) in Fn.
Douglas Gregor5c37de72008-12-06 00:22:45 +00001427 if (Dependent)
Douglas Gregor898574e2008-12-05 23:32:09 +00001428 return new CallExpr(Fn, Args, NumArgs, Context.DependentTy, RParenLoc);
1429
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001430 // If we're directly calling a function or a set of overloaded
1431 // functions, get the appropriate declaration.
1432 {
1433 DeclRefExpr *DRExpr = NULL;
1434 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1435 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1436 else
1437 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1438
1439 if (DRExpr) {
1440 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1441 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1442 }
1443 }
1444
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001445 if (Ovl) {
Douglas Gregor0a396682008-11-26 06:01:48 +00001446 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1447 RParenLoc);
1448 if (!FDecl)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001449 return true;
1450
Douglas Gregor0a396682008-11-26 06:01:48 +00001451 // Update Fn to refer to the actual function selected.
1452 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1453 Fn->getSourceRange().getBegin());
1454 Fn->Destroy(Context);
1455 Fn = NewFn;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001456 }
Chris Lattner04421082008-04-08 04:40:51 +00001457
Douglas Gregorf9eb9052008-11-19 21:05:33 +00001458 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Douglas Gregor5c37de72008-12-06 00:22:45 +00001459 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00001460 CommaLocs, RParenLoc);
1461
Chris Lattner04421082008-04-08 04:40:51 +00001462 // Promote the function operand.
1463 UsualUnaryConversions(Fn);
1464
Chris Lattner925e60d2007-12-28 05:29:59 +00001465 // Make the call expr early, before semantic checks. This guarantees cleanup
1466 // of arguments and function on error.
Chris Lattner8123a952008-04-10 02:22:51 +00001467 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001468 Context.BoolTy, RParenLoc));
Douglas Gregor898574e2008-12-05 23:32:09 +00001469
Steve Naroffdd972f22008-09-05 22:11:13 +00001470 const FunctionType *FuncT;
1471 if (!Fn->getType()->isBlockPointerType()) {
1472 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1473 // have type pointer to function".
1474 const PointerType *PT = Fn->getType()->getAsPointerType();
1475 if (PT == 0)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001476 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattnerd1625842008-11-24 06:25:27 +00001477 << Fn->getType() << Fn->getSourceRange();
Steve Naroffdd972f22008-09-05 22:11:13 +00001478 FuncT = PT->getPointeeType()->getAsFunctionType();
1479 } else { // This is a block call.
1480 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1481 getAsFunctionType();
1482 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001483 if (FuncT == 0)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001484 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattnerd1625842008-11-24 06:25:27 +00001485 << Fn->getType() << Fn->getSourceRange();
Chris Lattner925e60d2007-12-28 05:29:59 +00001486
1487 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001488 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001489
Chris Lattner925e60d2007-12-28 05:29:59 +00001490 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001491 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1492 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +00001493 unsigned NumArgsInProto = Proto->getNumArgs();
1494 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001495
Chris Lattner04421082008-04-08 04:40:51 +00001496 // If too few arguments are available (and we don't have default
1497 // arguments for the remaining parameters), don't make the call.
1498 if (NumArgs < NumArgsInProto) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001499 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1500 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1501 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1502 // Use default arguments for missing arguments
1503 NumArgsToCheck = NumArgsInProto;
1504 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner04421082008-04-08 04:40:51 +00001505 }
1506
Chris Lattner925e60d2007-12-28 05:29:59 +00001507 // If too many are passed and not variadic, error on the extras and drop
1508 // them.
1509 if (NumArgs > NumArgsInProto) {
1510 if (!Proto->isVariadic()) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001511 Diag(Args[NumArgsInProto]->getLocStart(),
1512 diag::err_typecheck_call_too_many_args)
1513 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001514 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1515 Args[NumArgs-1]->getLocEnd());
Chris Lattner925e60d2007-12-28 05:29:59 +00001516 // This deletes the extra arguments.
1517 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 }
1519 NumArgsToCheck = NumArgsInProto;
1520 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001521
Reid Spencer5f016e22007-07-11 17:01:13 +00001522 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +00001523 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00001524 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner04421082008-04-08 04:40:51 +00001525
1526 Expr *Arg;
1527 if (i < NumArgs)
1528 Arg = Args[i];
1529 else
1530 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner5cf216b2008-01-04 18:04:52 +00001531 QualType ArgType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +00001532
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001533 // Pass the argument.
1534 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00001535 return true;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001536
1537 TheCall->setArg(i, Arg);
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001539
1540 // If this is a variadic call, handle args passed through "...".
1541 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +00001542 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-12-28 05:29:59 +00001543 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1544 Expr *Arg = Args[i];
1545 DefaultArgumentPromotion(Arg);
1546 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001547 }
Steve Naroffb291ab62007-08-28 23:30:39 +00001548 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001549 } else {
1550 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1551
Steve Naroffb291ab62007-08-28 23:30:39 +00001552 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001553 for (unsigned i = 0; i != NumArgs; i++) {
1554 Expr *Arg = Args[i];
1555 DefaultArgumentPromotion(Arg);
1556 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001557 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001559
Chris Lattner59907c42007-08-10 20:18:51 +00001560 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001561 if (FDecl)
1562 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001563
Chris Lattner925e60d2007-12-28 05:29:59 +00001564 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001565}
1566
1567Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001568ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +00001569 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001570 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001571 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001572 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001573 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +00001574 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +00001575
Eli Friedman6223c222008-05-20 05:22:08 +00001576 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001577 if (literalType->isVariableArrayType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001578 return Diag(LParenLoc, diag::err_variable_object_no_init)
1579 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman6223c222008-05-20 05:22:08 +00001580 } else if (literalType->isIncompleteType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001581 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001582 << literalType
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001583 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman6223c222008-05-20 05:22:08 +00001584 }
1585
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001586 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001587 DeclarationName()))
Steve Naroff58d18212008-01-09 20:58:06 +00001588 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +00001589
Chris Lattner371f2582008-12-04 23:50:19 +00001590 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00001591 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001592 if (CheckForConstantInitializer(literalExpr, literalType))
1593 return true;
1594 }
Chris Lattner220ad7c2008-10-26 23:35:51 +00001595 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1596 isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001597}
1598
1599Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001600ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattner220ad7c2008-10-26 23:35:51 +00001601 InitListDesignations &Designators,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001602 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +00001603 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001604
Steve Naroff08d92e42007-09-15 18:49:24 +00001605 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001606 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001607
Chris Lattner418f6c72008-10-26 23:43:26 +00001608 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1609 Designators.hasAnyDesignators());
Chris Lattnerf0467b32008-04-02 04:24:33 +00001610 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1611 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001612}
1613
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001614/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001615bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001616 UsualUnaryConversions(castExpr);
1617
1618 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1619 // type needs to be scalar.
1620 if (castType->isVoidType()) {
1621 // Cast to void allows any expr type.
Douglas Gregor898574e2008-12-05 23:32:09 +00001622 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1623 // We can't check any more until template instantiation time.
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001624 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1625 // GCC struct/union extension: allow cast to self.
1626 if (Context.getCanonicalType(castType) !=
1627 Context.getCanonicalType(castExpr->getType()) ||
1628 (!castType->isStructureType() && !castType->isUnionType())) {
1629 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001630 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00001631 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001632 }
1633
1634 // accept this, but emit an ext-warn.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001635 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00001636 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001637 } else if (!castExpr->getType()->isScalarType() &&
1638 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001639 return Diag(castExpr->getLocStart(),
1640 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00001641 << castExpr->getType() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001642 } else if (castExpr->getType()->isVectorType()) {
1643 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1644 return true;
1645 } else if (castType->isVectorType()) {
1646 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1647 return true;
1648 }
1649 return false;
1650}
1651
Chris Lattnerfe23e212007-12-20 00:44:32 +00001652bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00001653 assert(VectorTy->isVectorType() && "Not a vector type!");
1654
1655 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00001656 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00001657 return Diag(R.getBegin(),
1658 Ty->isVectorType() ?
1659 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001660 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00001661 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00001662 } else
1663 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001664 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00001665 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00001666
1667 return false;
1668}
1669
Steve Naroff4aa88f82007-07-19 01:06:55 +00001670Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001671ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +00001673 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00001674
1675 Expr *castExpr = static_cast<Expr*>(Op);
1676 QualType castType = QualType::getFromOpaquePtr(Ty);
1677
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001678 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1679 return true;
Steve Naroffb2f9e512008-11-03 23:29:32 +00001680 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001681}
1682
Chris Lattnera21ddb32007-11-26 01:40:58 +00001683/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1684/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00001685inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00001686 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001687 UsualUnaryConversions(cond);
1688 UsualUnaryConversions(lex);
1689 UsualUnaryConversions(rex);
1690 QualType condT = cond->getType();
1691 QualType lexT = lex->getType();
1692 QualType rexT = rex->getType();
1693
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 // first, check the condition.
Douglas Gregor898574e2008-12-05 23:32:09 +00001695 if (!cond->isTypeDependent()) {
1696 if (!condT->isScalarType()) { // C99 6.5.15p2
1697 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
1698 return QualType();
1699 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001701
1702 // Now check the two expressions.
Douglas Gregor898574e2008-12-05 23:32:09 +00001703 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
1704 return Context.DependentTy;
1705
Chris Lattner70d67a92008-01-06 22:42:25 +00001706 // If both operands have arithmetic type, do the usual arithmetic conversions
1707 // to find a common type: C99 6.5.15p3,5.
1708 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00001709 UsualArithmeticConversions(lex, rex);
1710 return lex->getType();
1711 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001712
1713 // If both operands are the same structure or union type, the result is that
1714 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001715 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00001716 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00001717 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00001718 // "If both the operands have structure or union type, the result has
1719 // that type." This implies that CV qualifiers are dropped.
1720 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001721 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001722
1723 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00001724 // The following || allows only one side to be void (a GCC-ism).
1725 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00001726 if (!lexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001727 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
1728 << rex->getSourceRange();
Steve Naroffe701c0a2008-05-12 21:44:38 +00001729 if (!rexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001730 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
1731 << lex->getSourceRange();
Eli Friedman0e724012008-06-04 19:47:51 +00001732 ImpCastExprToType(lex, Context.VoidTy);
1733 ImpCastExprToType(rex, Context.VoidTy);
1734 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00001735 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00001736 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1737 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001738 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1739 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00001740 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001741 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001742 return lexT;
1743 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001744 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1745 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00001746 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001747 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001748 return rexT;
1749 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00001750 // Handle the case where both operands are pointers before we handle null
1751 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001752 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1753 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1754 // get the "pointed to" types
1755 QualType lhptee = LHSPT->getPointeeType();
1756 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001757
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001758 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1759 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00001760 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001761 // Figure out necessary qualifiers (C99 6.5.15p6)
1762 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001763 QualType destType = Context.getPointerType(destPointee);
1764 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1765 ImpCastExprToType(rex, destType); // promote to void*
1766 return destType;
1767 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00001768 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001769 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001770 QualType destType = Context.getPointerType(destPointee);
1771 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1772 ImpCastExprToType(rex, destType); // promote to void*
1773 return destType;
1774 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001775
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001776 QualType compositeType = lexT;
1777
1778 // If either type is an Objective-C object type then check
1779 // compatibility according to Objective-C.
1780 if (Context.isObjCObjectPointerType(lexT) ||
1781 Context.isObjCObjectPointerType(rexT)) {
1782 // If both operands are interfaces and either operand can be
1783 // assigned to the other, use that type as the composite
1784 // type. This allows
1785 // xxx ? (A*) a : (B*) b
1786 // where B is a subclass of A.
1787 //
1788 // Additionally, as for assignment, if either type is 'id'
1789 // allow silent coercion. Finally, if the types are
1790 // incompatible then make sure to use 'id' as the composite
1791 // type so the result is acceptable for sending messages to.
1792
1793 // FIXME: This code should not be localized to here. Also this
1794 // should use a compatible check instead of abusing the
1795 // canAssignObjCInterfaces code.
1796 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1797 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1798 if (LHSIface && RHSIface &&
1799 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1800 compositeType = lexT;
1801 } else if (LHSIface && RHSIface &&
Douglas Gregor7ffd0de2008-11-26 06:43:45 +00001802 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001803 compositeType = rexT;
1804 } else if (Context.isObjCIdType(lhptee) ||
1805 Context.isObjCIdType(rhptee)) {
1806 // FIXME: This code looks wrong, because isObjCIdType checks
1807 // the struct but getObjCIdType returns the pointer to
1808 // struct. This is horrible and should be fixed.
1809 compositeType = Context.getObjCIdType();
1810 } else {
1811 QualType incompatTy = Context.getObjCIdType();
1812 ImpCastExprToType(lex, incompatTy);
1813 ImpCastExprToType(rex, incompatTy);
1814 return incompatTy;
1815 }
1816 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1817 rhptee.getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001818 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00001819 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001820 // In this situation, we assume void* type. No especially good
1821 // reason, but this is what gcc does, and we do have to pick
1822 // to get a consistent AST.
1823 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00001824 ImpCastExprToType(lex, incompatTy);
1825 ImpCastExprToType(rex, incompatTy);
1826 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001827 }
1828 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001829 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1830 // differently qualified versions of compatible types, the result type is
1831 // a pointer to an appropriately qualified version of the *composite*
1832 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00001833 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00001834 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00001835 ImpCastExprToType(lex, compositeType);
1836 ImpCastExprToType(rex, compositeType);
1837 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001838 }
1839 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001840 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1841 // evaluates to "struct objc_object *" (and is handled above when comparing
1842 // id with statically typed objects).
1843 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1844 // GCC allows qualified id and any Objective-C type to devolve to
1845 // id. Currently localizing to here until clear this should be
1846 // part of ObjCQualifiedIdTypesAreCompatible.
1847 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1848 (lexT->isObjCQualifiedIdType() &&
1849 Context.isObjCObjectPointerType(rexT)) ||
1850 (rexT->isObjCQualifiedIdType() &&
1851 Context.isObjCObjectPointerType(lexT))) {
1852 // FIXME: This is not the correct composite type. This only
1853 // happens to work because id can more or less be used anywhere,
1854 // however this may change the type of method sends.
1855 // FIXME: gcc adds some type-checking of the arguments and emits
1856 // (confusing) incompatible comparison warnings in some
1857 // cases. Investigate.
1858 QualType compositeType = Context.getObjCIdType();
1859 ImpCastExprToType(lex, compositeType);
1860 ImpCastExprToType(rex, compositeType);
1861 return compositeType;
1862 }
1863 }
1864
Steve Naroff61f40a22008-09-10 19:17:48 +00001865 // Selection between block pointer types is ok as long as they are the same.
1866 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1867 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1868 return lexT;
1869
Chris Lattner70d67a92008-01-06 22:42:25 +00001870 // Otherwise, the operands are not compatible.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001871 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattnerd1625842008-11-24 06:25:27 +00001872 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001873 return QualType();
1874}
1875
Steve Narofff69936d2007-09-16 03:34:24 +00001876/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00001877/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00001878Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001879 SourceLocation ColonLoc,
1880 ExprTy *Cond, ExprTy *LHS,
1881 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00001882 Expr *CondExpr = (Expr *) Cond;
1883 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001884
1885 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1886 // was the condition.
1887 bool isLHSNull = LHSExpr == 0;
1888 if (isLHSNull)
1889 LHSExpr = CondExpr;
1890
Chris Lattner26824902007-07-16 21:39:03 +00001891 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1892 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001893 if (result.isNull())
1894 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001895 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1896 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001897}
1898
Reid Spencer5f016e22007-07-11 17:01:13 +00001899
1900// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1901// being closely modeled after the C99 spec:-). The odd characteristic of this
1902// routine is it effectively iqnores the qualifiers on the top level pointee.
1903// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1904// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001905Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001906Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1907 QualType lhptee, rhptee;
1908
1909 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001910 lhptee = lhsType->getAsPointerType()->getPointeeType();
1911 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001912
1913 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00001914 lhptee = Context.getCanonicalType(lhptee);
1915 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00001916
Chris Lattner5cf216b2008-01-04 18:04:52 +00001917 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001918
1919 // C99 6.5.16.1p1: This following citation is common to constraints
1920 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1921 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00001922 // FIXME: Handle ASQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00001923 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00001924 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001925
1926 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1927 // incomplete type and the other is a pointer to a qualified or unqualified
1928 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001929 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001930 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001931 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001932
1933 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001934 assert(rhptee->isFunctionType());
1935 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001936 }
1937
1938 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001939 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001940 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001941
1942 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001943 assert(lhptee->isFunctionType());
1944 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001945 }
Eli Friedman3d815e72008-08-22 00:56:42 +00001946
1947 // Check for ObjC interfaces
1948 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1949 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1950 if (LHSIface && RHSIface &&
1951 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1952 return ConvTy;
1953
1954 // ID acts sort of like void* for ObjC interfaces
1955 if (LHSIface && Context.isObjCIdType(rhptee))
1956 return ConvTy;
1957 if (RHSIface && Context.isObjCIdType(lhptee))
1958 return ConvTy;
1959
Reid Spencer5f016e22007-07-11 17:01:13 +00001960 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1961 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001962 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1963 rhptee.getUnqualifiedType()))
1964 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00001965 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001966}
1967
Steve Naroff1c7d0672008-09-04 15:10:53 +00001968/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1969/// block pointer types are compatible or whether a block and normal pointer
1970/// are compatible. It is more restrict than comparing two function pointer
1971// types.
1972Sema::AssignConvertType
1973Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1974 QualType rhsType) {
1975 QualType lhptee, rhptee;
1976
1977 // get the "pointed to" type (ignoring qualifiers at the top level)
1978 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1979 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1980
1981 // make sure we operate on the canonical type
1982 lhptee = Context.getCanonicalType(lhptee);
1983 rhptee = Context.getCanonicalType(rhptee);
1984
1985 AssignConvertType ConvTy = Compatible;
1986
1987 // For blocks we enforce that qualifiers are identical.
1988 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1989 ConvTy = CompatiblePointerDiscardsQualifiers;
1990
1991 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1992 return IncompatibleBlockPointer;
1993 return ConvTy;
1994}
1995
Reid Spencer5f016e22007-07-11 17:01:13 +00001996/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1997/// has code to accommodate several GCC extensions when type checking
1998/// pointers. Here are some objectionable examples that GCC considers warnings:
1999///
2000/// int a, *pint;
2001/// short *pshort;
2002/// struct foo *pfoo;
2003///
2004/// pint = pshort; // warning: assignment from incompatible pointer type
2005/// a = pint; // warning: assignment makes integer from pointer without a cast
2006/// pint = a; // warning: assignment makes pointer from integer without a cast
2007/// pint = pfoo; // warning: assignment from incompatible pointer type
2008///
2009/// As a result, the code for dealing with pointers is more complex than the
2010/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00002011///
Chris Lattner5cf216b2008-01-04 18:04:52 +00002012Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002013Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00002014 // Get canonical types. We're not formatting these types, just comparing
2015 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002016 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2017 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002018
2019 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00002020 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00002021
Douglas Gregor9d293df2008-10-28 00:22:11 +00002022 // If the left-hand side is a reference type, then we are in a
2023 // (rare!) case where we've allowed the use of references in C,
2024 // e.g., as a parameter type in a built-in function. In this case,
2025 // just make sure that the type referenced is compatible with the
2026 // right-hand side type. The caller is responsible for adjusting
2027 // lhsType so that the resulting expression does not have reference
2028 // type.
2029 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2030 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00002031 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002032 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002033 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002034
Chris Lattnereca7be62008-04-07 05:30:13 +00002035 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2036 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002037 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00002038 // Relax integer conversions like we do for pointers below.
2039 if (rhsType->isIntegerType())
2040 return IntToPointer;
2041 if (lhsType->isIntegerType())
2042 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00002043 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002044 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00002045
Nate Begemanbe2341d2008-07-14 18:02:46 +00002046 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002047 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00002048 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2049 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00002050 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002051
Nate Begemanbe2341d2008-07-14 18:02:46 +00002052 // If we are allowing lax vector conversions, and LHS and RHS are both
2053 // vectors, the total size only needs to be the same. This is a bitcast;
2054 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00002055 if (getLangOptions().LaxVectorConversions &&
2056 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002057 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2058 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00002059 }
2060 return Incompatible;
2061 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002062
Chris Lattnere8b3e962008-01-04 23:32:24 +00002063 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002064 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002065
Chris Lattner78eca282008-04-07 06:49:41 +00002066 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002067 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002068 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002069
Chris Lattner78eca282008-04-07 06:49:41 +00002070 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002071 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002072
Steve Naroffb4406862008-09-29 18:10:17 +00002073 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00002074 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002075 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00002076
2077 // Treat block pointers as objects.
2078 if (getLangOptions().ObjC1 &&
2079 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2080 return Compatible;
2081 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002082 return Incompatible;
2083 }
2084
2085 if (isa<BlockPointerType>(lhsType)) {
2086 if (rhsType->isIntegerType())
2087 return IntToPointer;
2088
Steve Naroffb4406862008-09-29 18:10:17 +00002089 // Treat block pointers as objects.
2090 if (getLangOptions().ObjC1 &&
2091 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2092 return Compatible;
2093
Steve Naroff1c7d0672008-09-04 15:10:53 +00002094 if (rhsType->isBlockPointerType())
2095 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2096
2097 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2098 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002099 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002100 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00002101 return Incompatible;
2102 }
2103
Chris Lattner78eca282008-04-07 06:49:41 +00002104 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002105 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002106 if (lhsType == Context.BoolTy)
2107 return Compatible;
2108
2109 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002110 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00002111
Chris Lattner78eca282008-04-07 06:49:41 +00002112 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002113 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002114
2115 if (isa<BlockPointerType>(lhsType) &&
2116 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002117 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002118 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002119 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002120
Chris Lattnerfc144e22008-01-04 23:18:45 +00002121 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00002122 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002123 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002124 }
2125 return Incompatible;
2126}
2127
Chris Lattner5cf216b2008-01-04 18:04:52 +00002128Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002129Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002130 if (getLangOptions().CPlusPlus) {
2131 if (!lhsType->isRecordType()) {
2132 // C++ 5.17p3: If the left operand is not of class type, the
2133 // expression is implicitly converted (C++ 4) to the
2134 // cv-unqualified type of the left operand.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002135 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002136 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002137 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00002138 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002139 }
2140
2141 // FIXME: Currently, we fall through and treat C++ classes like C
2142 // structures.
2143 }
2144
Steve Naroff529a4ad2007-11-27 17:58:44 +00002145 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2146 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00002147 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2148 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00002149 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002150 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00002151 return Compatible;
2152 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002153
2154 // We don't allow conversion of non-null-pointer constants to integers.
2155 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2156 return IntToBlockPointer;
2157
Chris Lattner943140e2007-10-16 02:55:40 +00002158 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00002159 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00002160 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00002161 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00002162 //
Douglas Gregor9d293df2008-10-28 00:22:11 +00002163 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00002164 if (!lhsType->isReferenceType())
2165 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00002166
Chris Lattner5cf216b2008-01-04 18:04:52 +00002167 Sema::AssignConvertType result =
2168 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00002169
2170 // C99 6.5.16.1p2: The value of the right operand is converted to the
2171 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00002172 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2173 // so that we can use references in built-in functions even in C.
2174 // The getNonReferenceType() call makes sure that the resulting expression
2175 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00002176 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00002177 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00002178 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00002179}
2180
Chris Lattner5cf216b2008-01-04 18:04:52 +00002181Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002182Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2183 return CheckAssignmentConstraints(lhsType, rhsType);
2184}
2185
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002186QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002187 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00002188 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002189 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00002190 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002191}
2192
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002193inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00002194 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00002195 // For conversion purposes, we ignore any qualifiers.
2196 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002197 QualType lhsType =
2198 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2199 QualType rhsType =
2200 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002201
Nate Begemanbe2341d2008-07-14 18:02:46 +00002202 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00002203 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002204 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00002205
Nate Begemanbe2341d2008-07-14 18:02:46 +00002206 // Handle the case of a vector & extvector type of the same size and element
2207 // type. It would be nice if we only had one vector type someday.
2208 if (getLangOptions().LaxVectorConversions)
2209 if (const VectorType *LV = lhsType->getAsVectorType())
2210 if (const VectorType *RV = rhsType->getAsVectorType())
2211 if (LV->getElementType() == RV->getElementType() &&
2212 LV->getNumElements() == RV->getNumElements())
2213 return lhsType->isExtVectorType() ? lhsType : rhsType;
2214
2215 // If the lhs is an extended vector and the rhs is a scalar of the same type
2216 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002217 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002218 QualType eltType = V->getElementType();
2219
2220 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2221 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2222 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002223 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002224 return lhsType;
2225 }
2226 }
2227
Nate Begemanbe2341d2008-07-14 18:02:46 +00002228 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00002229 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002230 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002231 QualType eltType = V->getElementType();
2232
2233 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2234 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2235 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002236 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002237 return rhsType;
2238 }
2239 }
2240
Reid Spencer5f016e22007-07-11 17:01:13 +00002241 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002242 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00002243 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002244 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002245 return QualType();
2246}
2247
2248inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002249 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002250{
Steve Naroff90045e82007-07-13 23:32:42 +00002251 QualType lhsType = lex->getType(), rhsType = rex->getType();
2252
2253 if (lhsType->isVectorType() || rhsType->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002254 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002255
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002256 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002257
Steve Naroffa4332e22007-07-17 00:58:39 +00002258 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002259 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002260 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002261}
2262
2263inline QualType Sema::CheckRemainderOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002264 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002265{
Steve Naroff90045e82007-07-13 23:32:42 +00002266 QualType lhsType = lex->getType(), rhsType = rex->getType();
2267
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002268 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002269
Steve Naroffa4332e22007-07-17 00:58:39 +00002270 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002271 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002272 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002273}
2274
2275inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002276 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002277{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002278 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002279 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002280
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002281 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00002282
Reid Spencer5f016e22007-07-11 17:01:13 +00002283 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002284 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002285 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002286
Eli Friedmand72d16e2008-05-18 18:08:51 +00002287 // Put any potential pointer into PExp
2288 Expr* PExp = lex, *IExp = rex;
2289 if (IExp->getType()->isPointerType())
2290 std::swap(PExp, IExp);
2291
2292 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2293 if (IExp->getType()->isIntegerType()) {
2294 // Check for arithmetic on pointers to incomplete types
2295 if (!PTy->getPointeeType()->isObjectType()) {
2296 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002297 Diag(Loc, diag::ext_gnu_void_ptr)
2298 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002299 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002300 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00002301 << lex->getType() << lex->getSourceRange();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002302 return QualType();
2303 }
2304 }
2305 return PExp->getType();
2306 }
2307 }
2308
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002309 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002310}
2311
Chris Lattnereca7be62008-04-07 05:30:13 +00002312// C99 6.5.6
2313QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002314 SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00002315 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002316 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002317
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002318 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002319
Chris Lattner6e4ab612007-12-09 21:53:25 +00002320 // Enforce type constraints: C99 6.5.6p3.
2321
2322 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002323 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002324 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00002325
2326 // Either ptr - int or ptr - ptr.
2327 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00002328 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00002329
Chris Lattner6e4ab612007-12-09 21:53:25 +00002330 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00002331 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002332 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002333 if (lpointee->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002334 Diag(Loc, diag::ext_gnu_void_ptr)
2335 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002336 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002337 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002338 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002339 return QualType();
2340 }
2341 }
2342
2343 // The result type of a pointer-int computation is the pointer type.
2344 if (rex->getType()->isIntegerType())
2345 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00002346
Chris Lattner6e4ab612007-12-09 21:53:25 +00002347 // Handle pointer-pointer subtractions.
2348 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00002349 QualType rpointee = RHSPTy->getPointeeType();
2350
Chris Lattner6e4ab612007-12-09 21:53:25 +00002351 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00002352 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002353 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002354 if (rpointee->isVoidType()) {
2355 if (!lpointee->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002356 Diag(Loc, diag::ext_gnu_void_ptr)
2357 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002358 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002359 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002360 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002361 return QualType();
2362 }
2363 }
2364
2365 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00002366 if (!Context.typesAreCompatible(
2367 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2368 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002369 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattnerd1625842008-11-24 06:25:27 +00002370 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002371 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002372 return QualType();
2373 }
2374
2375 return Context.getPointerDiffType();
2376 }
2377 }
2378
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002379 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002380}
2381
Chris Lattnereca7be62008-04-07 05:30:13 +00002382// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002383QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002384 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002385 // C99 6.5.7p2: Each of the operands shall have integer type.
2386 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002387 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002388
Chris Lattnerca5eede2007-12-12 05:47:28 +00002389 // Shifts don't perform usual arithmetic conversions, they just do integer
2390 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002391 if (!isCompAssign)
2392 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002393 UsualUnaryConversions(rex);
2394
2395 // "The type of the result is that of the promoted left operand."
2396 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002397}
2398
Eli Friedman3d815e72008-08-22 00:56:42 +00002399static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2400 ASTContext& Context) {
2401 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2402 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2403 // ID acts sort of like void* for ObjC interfaces
2404 if (LHSIface && Context.isObjCIdType(RHS))
2405 return true;
2406 if (RHSIface && Context.isObjCIdType(LHS))
2407 return true;
2408 if (!LHSIface || !RHSIface)
2409 return false;
2410 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2411 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2412}
2413
Chris Lattnereca7be62008-04-07 05:30:13 +00002414// C99 6.5.8
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002415QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002416 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002417 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002418 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002419
Chris Lattnera5937dd2007-08-26 01:18:55 +00002420 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002421 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2422 UsualArithmeticConversions(lex, rex);
2423 else {
2424 UsualUnaryConversions(lex);
2425 UsualUnaryConversions(rex);
2426 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002427 QualType lType = lex->getType();
2428 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002429
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002430 // For non-floating point types, check for self-comparisons of the form
2431 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2432 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002433 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002434 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2435 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002436 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002437 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002438 }
2439
Douglas Gregor447b69e2008-11-19 03:25:36 +00002440 // The result of comparisons is 'bool' in C++, 'int' in C.
2441 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2442
Chris Lattnera5937dd2007-08-26 01:18:55 +00002443 if (isRelational) {
2444 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002445 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002446 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002447 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002448 if (lType->isFloatingType()) {
2449 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002450 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002451 }
2452
Chris Lattnera5937dd2007-08-26 01:18:55 +00002453 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002454 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002455 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002456
Chris Lattnerd28f8152007-08-26 01:10:14 +00002457 bool LHSIsNull = lex->isNullPointerConstant(Context);
2458 bool RHSIsNull = rex->isNullPointerConstant(Context);
2459
Chris Lattnera5937dd2007-08-26 01:18:55 +00002460 // All of the following pointer related warnings are GCC extensions, except
2461 // when handling null pointer constants. One day, we can consider making them
2462 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002463 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002464 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002465 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002466 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002467 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002468
Steve Naroff66296cb2007-11-13 14:57:38 +00002469 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002470 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2471 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002472 RCanPointeeTy.getUnqualifiedType()) &&
2473 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002474 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002475 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002476 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002477 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002478 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002479 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002480 // Handle block pointer types.
2481 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2482 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2483 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2484
2485 if (!LHSIsNull && !RHSIsNull &&
2486 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002487 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002488 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00002489 }
2490 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002491 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002492 }
Steve Naroff59f53942008-09-28 01:11:11 +00002493 // Allow block pointers to be compared with null pointer constants.
2494 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2495 (lType->isPointerType() && rType->isBlockPointerType())) {
2496 if (!LHSIsNull && !RHSIsNull) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002497 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002498 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00002499 }
2500 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002501 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00002502 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002503
Steve Naroff20373222008-06-03 14:04:54 +00002504 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00002505 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00002506 const PointerType *LPT = lType->getAsPointerType();
2507 const PointerType *RPT = rType->getAsPointerType();
2508 bool LPtrToVoid = LPT ?
2509 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2510 bool RPtrToVoid = RPT ?
2511 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2512
2513 if (!LPtrToVoid && !RPtrToVoid &&
2514 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002515 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002516 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00002517 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002518 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00002519 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002520 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002521 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00002522 }
Steve Naroff20373222008-06-03 14:04:54 +00002523 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2524 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002525 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002526 } else {
2527 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002528 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002529 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002530 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002531 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002532 }
Steve Naroff20373222008-06-03 14:04:54 +00002533 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00002534 }
Steve Naroff20373222008-06-03 14:04:54 +00002535 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2536 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002537 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002538 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002539 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002540 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002541 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002542 }
Steve Naroff20373222008-06-03 14:04:54 +00002543 if (lType->isIntegerType() &&
2544 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002545 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002546 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002547 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002548 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002549 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002550 }
Steve Naroff39218df2008-09-04 16:56:14 +00002551 // Handle block pointers.
2552 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2553 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002554 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002555 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002556 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002557 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00002558 }
2559 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2560 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002561 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002562 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002563 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002564 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00002565 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002566 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002567}
2568
Nate Begemanbe2341d2008-07-14 18:02:46 +00002569/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2570/// operates on extended vector types. Instead of producing an IntTy result,
2571/// like a scalar comparison, a vector comparison produces a vector of integer
2572/// types.
2573QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002574 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00002575 bool isRelational) {
2576 // Check to make sure we're operating on vectors of the same type and width,
2577 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002578 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002579 if (vType.isNull())
2580 return vType;
2581
2582 QualType lType = lex->getType();
2583 QualType rType = rex->getType();
2584
2585 // For non-floating point types, check for self-comparisons of the form
2586 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2587 // often indicate logic errors in the program.
2588 if (!lType->isFloatingType()) {
2589 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2590 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2591 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002592 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002593 }
2594
2595 // Check for comparisons of floating point operands using != and ==.
2596 if (!isRelational && lType->isFloatingType()) {
2597 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002598 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002599 }
2600
2601 // Return the type for the comparison, which is the same as vector type for
2602 // integer vectors, or an integer type of identical size and number of
2603 // elements for floating point vectors.
2604 if (lType->isIntegerType())
2605 return lType;
2606
2607 const VectorType *VTy = lType->getAsVectorType();
2608
2609 // FIXME: need to deal with non-32b int / non-64b long long
2610 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2611 if (TypeSize == 32) {
2612 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2613 }
2614 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2615 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2616}
2617
Reid Spencer5f016e22007-07-11 17:01:13 +00002618inline QualType Sema::CheckBitwiseOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002619 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002620{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002621 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002622 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002623
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002624 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002625
Steve Naroffa4332e22007-07-17 00:58:39 +00002626 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002627 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002628 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002629}
2630
2631inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002632 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00002633{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002634 UsualUnaryConversions(lex);
2635 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002636
Eli Friedman5773a6c2008-05-13 20:16:47 +00002637 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002638 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002639 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002640}
2641
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002642/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2643/// emit an error and return true. If so, return false.
2644static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2645 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2646 if (IsLV == Expr::MLV_Valid)
2647 return false;
2648
2649 unsigned Diag = 0;
2650 bool NeedType = false;
2651 switch (IsLV) { // C99 6.5.16p2
2652 default: assert(0 && "Unknown result from isModifiableLvalue!");
2653 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002654 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002655 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2656 NeedType = true;
2657 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002658 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002659 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2660 NeedType = true;
2661 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00002662 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002663 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2664 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002665 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002666 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2667 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002668 case Expr::MLV_IncompleteType:
2669 case Expr::MLV_IncompleteVoidType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002670 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2671 NeedType = true;
2672 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002673 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002674 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2675 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00002676 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002677 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2678 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00002679 case Expr::MLV_ReadonlyProperty:
2680 Diag = diag::error_readonly_property_assignment;
2681 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00002682 case Expr::MLV_NoSetterProperty:
2683 Diag = diag::error_nosetter_property_assignment;
2684 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002685 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00002686
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002687 if (NeedType)
Chris Lattnerd1625842008-11-24 06:25:27 +00002688 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002689 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002690 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002691 return true;
2692}
2693
2694
2695
2696// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002697QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
2698 SourceLocation Loc,
2699 QualType CompoundType) {
2700 // Verify that LHS is a modifiable lvalue, and emit error if not.
2701 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002702 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002703
2704 QualType LHSType = LHS->getType();
2705 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002706
Chris Lattner5cf216b2008-01-04 18:04:52 +00002707 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002708 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00002709 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002710 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner2c156472008-08-21 18:04:13 +00002711
2712 // If the RHS is a unary plus or minus, check to see if they = and + are
2713 // right next to each other. If so, the user may have typo'd "x =+ 4"
2714 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002715 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00002716 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2717 RHSCheck = ICE->getSubExpr();
2718 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2719 if ((UO->getOpcode() == UnaryOperator::Plus ||
2720 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002721 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00002722 // Only if the two operators are exactly adjacent.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002723 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002724 Diag(Loc, diag::warn_not_compound_assign)
2725 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
2726 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner2c156472008-08-21 18:04:13 +00002727 }
2728 } else {
2729 // Compound assignment "x += y"
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002730 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00002731 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00002732
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002733 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
2734 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00002735 return QualType();
2736
Reid Spencer5f016e22007-07-11 17:01:13 +00002737 // C99 6.5.16p3: The type of an assignment expression is the type of the
2738 // left operand unless the left operand has qualified type, in which case
2739 // it is the unqualified version of the type of the left operand.
2740 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2741 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002742 // C++ 5.17p1: the type of the assignment expression is that of its left
2743 // oprdu.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002744 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002745}
2746
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002747// C99 6.5.17
2748QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
2749 // FIXME: what is required for LHS?
Chris Lattner53fcaa92008-07-25 20:54:07 +00002750
2751 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002752 DefaultFunctionArrayConversion(RHS);
2753 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002754}
2755
Steve Naroff49b45262007-07-13 16:58:59 +00002756/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2757/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Chris Lattner3528d352008-11-21 07:05:48 +00002758QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc) {
2759 QualType ResType = Op->getType();
2760 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00002761
Steve Naroff084f9ed2007-08-24 17:20:07 +00002762 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Chris Lattner3528d352008-11-21 07:05:48 +00002763 if (ResType->isRealType()) {
2764 // OK!
2765 } else if (const PointerType *PT = ResType->getAsPointerType()) {
2766 // C99 6.5.2.4p2, 6.5.6p2
2767 if (PT->getPointeeType()->isObjectType()) {
2768 // Pointer to object is ok!
2769 } else if (PT->getPointeeType()->isVoidType()) {
2770 // Pointer to void is extension.
2771 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
2772 } else {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002773 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00002774 << ResType << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002775 return QualType();
2776 }
Chris Lattner3528d352008-11-21 07:05:48 +00002777 } else if (ResType->isComplexType()) {
2778 // C99 does not support ++/-- on complex types, we allow as an extension.
2779 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00002780 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00002781 } else {
2782 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00002783 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00002784 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002785 }
Steve Naroffdd10e022007-08-23 21:37:33 +00002786 // At this point, we know we have a real, complex or pointer type.
2787 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00002788 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00002789 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00002790 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002791}
2792
Anders Carlsson369dee42008-02-01 07:15:58 +00002793/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00002794/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002795/// where the declaration is needed for type checking. We only need to
2796/// handle cases when the expression references a function designator
2797/// or is an lvalue. Here are some examples:
2798/// - &(x) => x
2799/// - &*****f => f for f a function designator.
2800/// - &s.xx => s
2801/// - &s.zz[1].yy -> s, if zz is an array
2802/// - *(x + 1) -> x, if x is an array
2803/// - &"123"[2] -> 0
2804/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002805static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002806 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002807 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002808 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002809 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00002810 // Fields cannot be declared with a 'register' storage class.
2811 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002812 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00002813 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00002814 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00002815 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002816 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00002817
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002818 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00002819 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00002820 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00002821 return 0;
2822 else
2823 return VD;
2824 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002825 case Stmt::UnaryOperatorClass: {
2826 UnaryOperator *UO = cast<UnaryOperator>(E);
2827
2828 switch(UO->getOpcode()) {
2829 case UnaryOperator::Deref: {
2830 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002831 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2832 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2833 if (!VD || VD->getType()->isPointerType())
2834 return 0;
2835 return VD;
2836 }
2837 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002838 }
2839 case UnaryOperator::Real:
2840 case UnaryOperator::Imag:
2841 case UnaryOperator::Extension:
2842 return getPrimaryDecl(UO->getSubExpr());
2843 default:
2844 return 0;
2845 }
2846 }
2847 case Stmt::BinaryOperatorClass: {
2848 BinaryOperator *BO = cast<BinaryOperator>(E);
2849
2850 // Handle cases involving pointer arithmetic. The result of an
2851 // Assign or AddAssign is not an lvalue so they can be ignored.
2852
2853 // (x + n) or (n + x) => x
2854 if (BO->getOpcode() == BinaryOperator::Add) {
2855 if (BO->getLHS()->getType()->isPointerType()) {
2856 return getPrimaryDecl(BO->getLHS());
2857 } else if (BO->getRHS()->getType()->isPointerType()) {
2858 return getPrimaryDecl(BO->getRHS());
2859 }
2860 }
2861
2862 return 0;
2863 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002864 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002865 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00002866 case Stmt::ImplicitCastExprClass:
2867 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002868 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00002869 default:
2870 return 0;
2871 }
2872}
2873
2874/// CheckAddressOfOperand - The operand of & must be either a function
2875/// designator or an lvalue designating an object. If it is an lvalue, the
2876/// object cannot be declared with storage class register or be a bit field.
2877/// Note: The usual conversions are *not* applied to the operand of the &
2878/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor904eed32008-11-10 20:40:00 +00002879/// In C++, the operand might be an overloaded function name, in which case
2880/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002881QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregor9103bb22008-12-17 22:52:20 +00002882 if (op->isTypeDependent())
2883 return Context.DependentTy;
2884
Steve Naroff08f19672008-01-13 17:10:08 +00002885 if (getLangOptions().C99) {
2886 // Implement C99-only parts of addressof rules.
2887 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2888 if (uOp->getOpcode() == UnaryOperator::Deref)
2889 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2890 // (assuming the deref expression is valid).
2891 return uOp->getSubExpr()->getType();
2892 }
2893 // Technically, there should be a check for array subscript
2894 // expressions here, but the result of one is always an lvalue anyway.
2895 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002896 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00002897 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00002898
Reid Spencer5f016e22007-07-11 17:01:13 +00002899 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00002900 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2901 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002902 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
2903 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002904 return QualType();
2905 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00002906 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2907 if (MemExpr->getMemberDecl()->isBitField()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002908 Diag(OpLoc, diag::err_typecheck_address_of)
2909 << "bit-field" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00002910 return QualType();
2911 }
2912 // Check for Apple extension for accessing vector components.
2913 } else if (isa<ArraySubscriptExpr>(op) &&
2914 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002915 Diag(OpLoc, diag::err_typecheck_address_of)
2916 << "vector" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00002917 return QualType();
2918 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00002919 // We have an lvalue with a decl. Make sure the decl is not declared
2920 // with the register storage-class specifier.
2921 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2922 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002923 Diag(OpLoc, diag::err_typecheck_address_of)
2924 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002925 return QualType();
2926 }
Douglas Gregor29882052008-12-10 21:26:49 +00002927 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00002928 return Context.OverloadTy;
Douglas Gregor29882052008-12-10 21:26:49 +00002929 } else if (isa<FieldDecl>(dcl)) {
2930 // Okay: we can take the address of a field.
Nuno Lopes6fea8d22008-12-16 22:58:26 +00002931 } else if (isa<FunctionDecl>(dcl)) {
2932 // Okay: we can take the address of a function.
Douglas Gregor29882052008-12-10 21:26:49 +00002933 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00002934 else
Reid Spencer5f016e22007-07-11 17:01:13 +00002935 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002936 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00002937
Reid Spencer5f016e22007-07-11 17:01:13 +00002938 // If the operand has type "type", the result has type "pointer to type".
2939 return Context.getPointerType(op->getType());
2940}
2941
Chris Lattner22caddc2008-11-23 09:13:29 +00002942QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
2943 UsualUnaryConversions(Op);
2944 QualType Ty = Op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002945
Chris Lattner22caddc2008-11-23 09:13:29 +00002946 // Note that per both C89 and C99, this is always legal, even if ptype is an
2947 // incomplete type or void. It would be possible to warn about dereferencing
2948 // a void pointer, but it's completely well-defined, and such a warning is
2949 // unlikely to catch any mistakes.
2950 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff08f19672008-01-13 17:10:08 +00002951 return PT->getPointeeType();
Chris Lattner22caddc2008-11-23 09:13:29 +00002952
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002953 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00002954 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002955 return QualType();
2956}
2957
2958static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2959 tok::TokenKind Kind) {
2960 BinaryOperator::Opcode Opc;
2961 switch (Kind) {
2962 default: assert(0 && "Unknown binop!");
2963 case tok::star: Opc = BinaryOperator::Mul; break;
2964 case tok::slash: Opc = BinaryOperator::Div; break;
2965 case tok::percent: Opc = BinaryOperator::Rem; break;
2966 case tok::plus: Opc = BinaryOperator::Add; break;
2967 case tok::minus: Opc = BinaryOperator::Sub; break;
2968 case tok::lessless: Opc = BinaryOperator::Shl; break;
2969 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2970 case tok::lessequal: Opc = BinaryOperator::LE; break;
2971 case tok::less: Opc = BinaryOperator::LT; break;
2972 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2973 case tok::greater: Opc = BinaryOperator::GT; break;
2974 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2975 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2976 case tok::amp: Opc = BinaryOperator::And; break;
2977 case tok::caret: Opc = BinaryOperator::Xor; break;
2978 case tok::pipe: Opc = BinaryOperator::Or; break;
2979 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2980 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2981 case tok::equal: Opc = BinaryOperator::Assign; break;
2982 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2983 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2984 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2985 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2986 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2987 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2988 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2989 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2990 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2991 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2992 case tok::comma: Opc = BinaryOperator::Comma; break;
2993 }
2994 return Opc;
2995}
2996
2997static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2998 tok::TokenKind Kind) {
2999 UnaryOperator::Opcode Opc;
3000 switch (Kind) {
3001 default: assert(0 && "Unknown unary op!");
3002 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3003 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3004 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3005 case tok::star: Opc = UnaryOperator::Deref; break;
3006 case tok::plus: Opc = UnaryOperator::Plus; break;
3007 case tok::minus: Opc = UnaryOperator::Minus; break;
3008 case tok::tilde: Opc = UnaryOperator::Not; break;
3009 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003010 case tok::kw___real: Opc = UnaryOperator::Real; break;
3011 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3012 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3013 }
3014 return Opc;
3015}
3016
Douglas Gregoreaebc752008-11-06 23:29:22 +00003017/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3018/// operator @p Opc at location @c TokLoc. This routine only supports
3019/// built-in operations; ActOnBinOp handles overloaded operators.
3020Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3021 unsigned Op,
3022 Expr *lhs, Expr *rhs) {
3023 QualType ResultTy; // Result type of the binary operator.
3024 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3025 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3026
3027 switch (Opc) {
3028 default:
3029 assert(0 && "Unknown binary expr!");
3030 case BinaryOperator::Assign:
3031 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3032 break;
3033 case BinaryOperator::Mul:
3034 case BinaryOperator::Div:
3035 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3036 break;
3037 case BinaryOperator::Rem:
3038 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3039 break;
3040 case BinaryOperator::Add:
3041 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3042 break;
3043 case BinaryOperator::Sub:
3044 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3045 break;
3046 case BinaryOperator::Shl:
3047 case BinaryOperator::Shr:
3048 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3049 break;
3050 case BinaryOperator::LE:
3051 case BinaryOperator::LT:
3052 case BinaryOperator::GE:
3053 case BinaryOperator::GT:
3054 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3055 break;
3056 case BinaryOperator::EQ:
3057 case BinaryOperator::NE:
3058 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3059 break;
3060 case BinaryOperator::And:
3061 case BinaryOperator::Xor:
3062 case BinaryOperator::Or:
3063 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3064 break;
3065 case BinaryOperator::LAnd:
3066 case BinaryOperator::LOr:
3067 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3068 break;
3069 case BinaryOperator::MulAssign:
3070 case BinaryOperator::DivAssign:
3071 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3072 if (!CompTy.isNull())
3073 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3074 break;
3075 case BinaryOperator::RemAssign:
3076 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3077 if (!CompTy.isNull())
3078 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3079 break;
3080 case BinaryOperator::AddAssign:
3081 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3082 if (!CompTy.isNull())
3083 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3084 break;
3085 case BinaryOperator::SubAssign:
3086 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3087 if (!CompTy.isNull())
3088 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3089 break;
3090 case BinaryOperator::ShlAssign:
3091 case BinaryOperator::ShrAssign:
3092 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3093 if (!CompTy.isNull())
3094 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3095 break;
3096 case BinaryOperator::AndAssign:
3097 case BinaryOperator::XorAssign:
3098 case BinaryOperator::OrAssign:
3099 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3100 if (!CompTy.isNull())
3101 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3102 break;
3103 case BinaryOperator::Comma:
3104 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3105 break;
3106 }
3107 if (ResultTy.isNull())
3108 return true;
3109 if (CompTy.isNull())
3110 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
3111 else
3112 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
3113}
3114
Reid Spencer5f016e22007-07-11 17:01:13 +00003115// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003116Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3117 tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00003118 ExprTy *LHS, ExprTy *RHS) {
3119 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3120 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
3121
Steve Narofff69936d2007-09-16 03:34:24 +00003122 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3123 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003124
Douglas Gregor898574e2008-12-05 23:32:09 +00003125 // If either expression is type-dependent, just build the AST.
3126 // FIXME: We'll need to perform some caching of the result of name
3127 // lookup for operator+.
3128 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3129 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3130 return new CompoundAssignOperator(lhs, rhs, Opc, Context.DependentTy,
3131 Context.DependentTy, TokLoc);
3132 else
3133 return new BinaryOperator(lhs, rhs, Opc, Context.DependentTy, TokLoc);
3134 }
3135
Douglas Gregoreaebc752008-11-06 23:29:22 +00003136 if (getLangOptions().CPlusPlus &&
3137 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3138 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003139 // If this is one of the assignment operators, we only perform
3140 // overload resolution if the left-hand side is a class or
3141 // enumeration type (C++ [expr.ass]p3).
3142 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3143 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3144 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3145 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003146
3147 // Determine which overloaded operator we're dealing with.
3148 static const OverloadedOperatorKind OverOps[] = {
3149 OO_Star, OO_Slash, OO_Percent,
3150 OO_Plus, OO_Minus,
3151 OO_LessLess, OO_GreaterGreater,
3152 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3153 OO_EqualEqual, OO_ExclaimEqual,
3154 OO_Amp,
3155 OO_Caret,
3156 OO_Pipe,
3157 OO_AmpAmp,
3158 OO_PipePipe,
3159 OO_Equal, OO_StarEqual,
3160 OO_SlashEqual, OO_PercentEqual,
3161 OO_PlusEqual, OO_MinusEqual,
3162 OO_LessLessEqual, OO_GreaterGreaterEqual,
3163 OO_AmpEqual, OO_CaretEqual,
3164 OO_PipeEqual,
3165 OO_Comma
3166 };
3167 OverloadedOperatorKind OverOp = OverOps[Opc];
3168
Douglas Gregor96176b32008-11-18 23:14:02 +00003169 // Add the appropriate overloaded operators (C++ [over.match.oper])
3170 // to the candidate set.
Douglas Gregor74253732008-11-19 15:42:04 +00003171 OverloadCandidateSet CandidateSet;
Douglas Gregoreaebc752008-11-06 23:29:22 +00003172 Expr *Args[2] = { lhs, rhs };
Douglas Gregor96176b32008-11-18 23:14:02 +00003173 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregoreaebc752008-11-06 23:29:22 +00003174
3175 // Perform overload resolution.
3176 OverloadCandidateSet::iterator Best;
3177 switch (BestViableFunction(CandidateSet, Best)) {
3178 case OR_Success: {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003179 // We found a built-in operator or an overloaded operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003180 FunctionDecl *FnDecl = Best->Function;
3181
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003182 if (FnDecl) {
3183 // We matched an overloaded operator. Build a call to that
3184 // operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003185
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003186 // Convert the arguments.
Douglas Gregor96176b32008-11-18 23:14:02 +00003187 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3188 if (PerformObjectArgumentInitialization(lhs, Method) ||
3189 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3190 "passing"))
3191 return true;
3192 } else {
3193 // Convert the arguments.
3194 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3195 "passing") ||
3196 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3197 "passing"))
3198 return true;
3199 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003200
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003201 // Determine the result type
3202 QualType ResultTy
3203 = FnDecl->getType()->getAsFunctionType()->getResultType();
3204 ResultTy = ResultTy.getNonReferenceType();
3205
3206 // Build the actual expression node.
Douglas Gregorb4609802008-11-14 16:09:21 +00003207 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3208 SourceLocation());
3209 UsualUnaryConversions(FnExpr);
3210
Douglas Gregorb4609802008-11-14 16:09:21 +00003211 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003212 } else {
3213 // We matched a built-in operator. Convert the arguments, then
3214 // break out so that we will build the appropriate built-in
3215 // operator node.
3216 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
3217 "passing") ||
3218 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
3219 "passing"))
3220 return true;
3221
3222 break;
3223 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003224 }
3225
3226 case OR_No_Viable_Function:
3227 // No viable function; fall through to handling this as a
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003228 // built-in operator, which will produce an error message for us.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003229 break;
3230
3231 case OR_Ambiguous:
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003232 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3233 << BinaryOperator::getOpcodeStr(Opc)
3234 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003235 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3236 return true;
3237 }
3238
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003239 // Either we found no viable overloaded operator or we matched a
3240 // built-in operator. In either case, fall through to trying to
3241 // build a built-in operation.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003242 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003243
Douglas Gregoreaebc752008-11-06 23:29:22 +00003244 // Build a built-in binary operation.
3245 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00003246}
3247
3248// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor74253732008-11-19 15:42:04 +00003249Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3250 tok::TokenKind Op, ExprTy *input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003251 Expr *Input = (Expr*)input;
3252 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor74253732008-11-19 15:42:04 +00003253
3254 if (getLangOptions().CPlusPlus &&
3255 (Input->getType()->isRecordType()
3256 || Input->getType()->isEnumeralType())) {
3257 // Determine which overloaded operator we're dealing with.
3258 static const OverloadedOperatorKind OverOps[] = {
3259 OO_None, OO_None,
3260 OO_PlusPlus, OO_MinusMinus,
3261 OO_Amp, OO_Star,
3262 OO_Plus, OO_Minus,
3263 OO_Tilde, OO_Exclaim,
3264 OO_None, OO_None,
3265 OO_None,
3266 OO_None
3267 };
3268 OverloadedOperatorKind OverOp = OverOps[Opc];
3269
3270 // Add the appropriate overloaded operators (C++ [over.match.oper])
3271 // to the candidate set.
3272 OverloadCandidateSet CandidateSet;
3273 if (OverOp != OO_None)
3274 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3275
3276 // Perform overload resolution.
3277 OverloadCandidateSet::iterator Best;
3278 switch (BestViableFunction(CandidateSet, Best)) {
3279 case OR_Success: {
3280 // We found a built-in operator or an overloaded operator.
3281 FunctionDecl *FnDecl = Best->Function;
3282
3283 if (FnDecl) {
3284 // We matched an overloaded operator. Build a call to that
3285 // operator.
3286
3287 // Convert the arguments.
3288 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3289 if (PerformObjectArgumentInitialization(Input, Method))
3290 return true;
3291 } else {
3292 // Convert the arguments.
3293 if (PerformCopyInitialization(Input,
3294 FnDecl->getParamDecl(0)->getType(),
3295 "passing"))
3296 return true;
3297 }
3298
3299 // Determine the result type
3300 QualType ResultTy
3301 = FnDecl->getType()->getAsFunctionType()->getResultType();
3302 ResultTy = ResultTy.getNonReferenceType();
3303
3304 // Build the actual expression node.
3305 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3306 SourceLocation());
3307 UsualUnaryConversions(FnExpr);
3308
3309 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3310 } else {
3311 // We matched a built-in operator. Convert the arguments, then
3312 // break out so that we will build the appropriate built-in
3313 // operator node.
3314 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0],
3315 "passing"))
3316 return true;
3317
3318 break;
3319 }
3320 }
3321
3322 case OR_No_Viable_Function:
3323 // No viable function; fall through to handling this as a
3324 // built-in operator, which will produce an error message for us.
3325 break;
3326
3327 case OR_Ambiguous:
3328 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3329 << UnaryOperator::getOpcodeStr(Opc)
3330 << Input->getSourceRange();
3331 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3332 return true;
3333 }
3334
3335 // Either we found no viable overloaded operator or we matched a
3336 // built-in operator. In either case, fall through to trying to
3337 // build a built-in operation.
3338 }
3339
Reid Spencer5f016e22007-07-11 17:01:13 +00003340 QualType resultType;
3341 switch (Opc) {
3342 default:
3343 assert(0 && "Unimplemented unary expr!");
3344 case UnaryOperator::PreInc:
3345 case UnaryOperator::PreDec:
3346 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
3347 break;
3348 case UnaryOperator::AddrOf:
3349 resultType = CheckAddressOfOperand(Input, OpLoc);
3350 break;
3351 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00003352 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003353 resultType = CheckIndirectionOperand(Input, OpLoc);
3354 break;
3355 case UnaryOperator::Plus:
3356 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003357 UsualUnaryConversions(Input);
3358 resultType = Input->getType();
Douglas Gregor74253732008-11-19 15:42:04 +00003359 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3360 break;
3361 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3362 resultType->isEnumeralType())
3363 break;
3364 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3365 Opc == UnaryOperator::Plus &&
3366 resultType->isPointerType())
3367 break;
3368
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003369 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattnerd1625842008-11-24 06:25:27 +00003370 << resultType << Input->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003371 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003372 UsualUnaryConversions(Input);
3373 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00003374 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3375 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3376 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003377 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003378 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00003379 else if (!resultType->isIntegerType())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003380 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattnerd1625842008-11-24 06:25:27 +00003381 << resultType << Input->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003382 break;
3383 case UnaryOperator::LNot: // logical negation
3384 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003385 DefaultFunctionArrayConversion(Input);
3386 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003387 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003388 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattnerd1625842008-11-24 06:25:27 +00003389 << resultType << Input->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003390 // LNot always has type int. C99 6.5.3.3p5.
3391 resultType = Context.IntTy;
3392 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00003393 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00003394 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00003395 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00003396 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003397 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00003398 resultType = Input->getType();
3399 break;
3400 }
3401 if (resultType.isNull())
3402 return true;
3403 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3404}
3405
Steve Naroff1b273c42007-09-16 14:56:35 +00003406/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3407Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00003408 SourceLocation LabLoc,
3409 IdentifierInfo *LabelII) {
3410 // Look up the record for this label identifier.
3411 LabelStmt *&LabelDecl = LabelMap[LabelII];
3412
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00003413 // If we haven't seen this label yet, create a forward reference. It
3414 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00003415 if (LabelDecl == 0)
3416 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3417
3418 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00003419 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3420 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00003421}
3422
Steve Naroff1b273c42007-09-16 14:56:35 +00003423Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003424 SourceLocation RPLoc) { // "({..})"
3425 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3426 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3427 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3428
3429 // FIXME: there are a variety of strange constraints to enforce here, for
3430 // example, it is not possible to goto into a stmt expression apparently.
3431 // More semantic analysis is needed.
3432
3433 // FIXME: the last statement in the compount stmt has its value used. We
3434 // should not warn about it being unused.
3435
3436 // If there are sub stmts in the compound stmt, take the type of the last one
3437 // as the type of the stmtexpr.
3438 QualType Ty = Context.VoidTy;
3439
Chris Lattner611b2ec2008-07-26 19:51:01 +00003440 if (!Compound->body_empty()) {
3441 Stmt *LastStmt = Compound->body_back();
3442 // If LastStmt is a label, skip down through into the body.
3443 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3444 LastStmt = Label->getSubStmt();
3445
3446 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003447 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00003448 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003449
3450 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3451}
Steve Naroffd34e9152007-08-01 22:05:33 +00003452
Steve Naroff1b273c42007-09-16 14:56:35 +00003453Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003454 SourceLocation TypeLoc,
3455 TypeTy *argty,
3456 OffsetOfComponent *CompPtr,
3457 unsigned NumComponents,
3458 SourceLocation RPLoc) {
3459 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3460 assert(!ArgTy.isNull() && "Missing type argument!");
3461
3462 // We must have at least one component that refers to the type, and the first
3463 // one is known to be a field designator. Verify that the ArgTy represents
3464 // a struct/union/class.
3465 if (!ArgTy->isRecordType())
Chris Lattnerd1625842008-11-24 06:25:27 +00003466 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003467
3468 // Otherwise, create a compound literal expression as the base, and
3469 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00003470 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003471
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003472 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3473 // GCC extension, diagnose them.
3474 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003475 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3476 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003477
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003478 for (unsigned i = 0; i != NumComponents; ++i) {
3479 const OffsetOfComponent &OC = CompPtr[i];
3480 if (OC.isBrackets) {
3481 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003482 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003483 if (!AT) {
3484 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00003485 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003486 }
3487
Chris Lattner704fe352007-08-30 17:59:59 +00003488 // FIXME: C++: Verify that operator[] isn't overloaded.
3489
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003490 // C99 6.5.2.1p1
3491 Expr *Idx = static_cast<Expr*>(OC.U.E);
3492 if (!Idx->getType()->isIntegerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003493 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3494 << Idx->getSourceRange();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003495
3496 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3497 continue;
3498 }
3499
3500 const RecordType *RC = Res->getType()->getAsRecordType();
3501 if (!RC) {
3502 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00003503 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003504 }
3505
3506 // Get the decl corresponding to this.
3507 RecordDecl *RD = RC->getDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003508 FieldDecl *MemberDecl = 0;
3509 DeclContext::lookup_result Lookup = RD->lookup(Context, OC.U.IdentInfo);
3510 if (Lookup.first != Lookup.second)
3511 MemberDecl = dyn_cast<FieldDecl>(*Lookup.first);
3512
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003513 if (!MemberDecl)
Chris Lattner3c73c412008-11-19 08:23:25 +00003514 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3515 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner704fe352007-08-30 17:59:59 +00003516
3517 // FIXME: C++: Verify that MemberDecl isn't a static field.
3518 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00003519 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3520 // matter here.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003521 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3522 MemberDecl->getType().getNonReferenceType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003523 }
3524
3525 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3526 BuiltinLoc);
3527}
3528
3529
Steve Naroff1b273c42007-09-16 14:56:35 +00003530Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00003531 TypeTy *arg1, TypeTy *arg2,
3532 SourceLocation RPLoc) {
3533 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3534 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3535
3536 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3537
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003538 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00003539}
3540
Steve Naroff1b273c42007-09-16 14:56:35 +00003541Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00003542 ExprTy *expr1, ExprTy *expr2,
3543 SourceLocation RPLoc) {
3544 Expr *CondExpr = static_cast<Expr*>(cond);
3545 Expr *LHSExpr = static_cast<Expr*>(expr1);
3546 Expr *RHSExpr = static_cast<Expr*>(expr2);
3547
3548 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3549
3550 // The conditional expression is required to be a constant expression.
3551 llvm::APSInt condEval(32);
3552 SourceLocation ExpLoc;
3553 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003554 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3555 << CondExpr->getSourceRange();
Steve Naroffd04fdd52007-08-03 21:21:27 +00003556
3557 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3558 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3559 RHSExpr->getType();
3560 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3561}
3562
Steve Naroff4eb206b2008-09-03 18:15:37 +00003563//===----------------------------------------------------------------------===//
3564// Clang Extensions.
3565//===----------------------------------------------------------------------===//
3566
3567/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00003568void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00003569 // Analyze block parameters.
3570 BlockSemaInfo *BSI = new BlockSemaInfo();
3571
3572 // Add BSI to CurBlock.
3573 BSI->PrevBlockInfo = CurBlock;
3574 CurBlock = BSI;
3575
3576 BSI->ReturnType = 0;
3577 BSI->TheScope = BlockScope;
3578
Steve Naroff090276f2008-10-10 01:28:17 +00003579 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00003580 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00003581}
3582
3583void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00003584 // Analyze arguments to block.
3585 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3586 "Not a function declarator!");
3587 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3588
Steve Naroff090276f2008-10-10 01:28:17 +00003589 CurBlock->hasPrototype = FTI.hasPrototype;
3590 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003591
3592 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3593 // no arguments, not a function that takes a single void argument.
3594 if (FTI.hasPrototype &&
3595 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3596 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3597 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3598 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00003599 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003600 } else if (FTI.hasPrototype) {
3601 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00003602 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3603 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003604 }
Steve Naroff090276f2008-10-10 01:28:17 +00003605 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3606
3607 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3608 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3609 // If this has an identifier, add it to the scope stack.
3610 if ((*AI)->getIdentifier())
3611 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003612}
3613
3614/// ActOnBlockError - If there is an error parsing a block, this callback
3615/// is invoked to pop the information about the block from the action impl.
3616void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3617 // Ensure that CurBlock is deleted.
3618 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3619
3620 // Pop off CurBlock, handle nested blocks.
3621 CurBlock = CurBlock->PrevBlockInfo;
3622
3623 // FIXME: Delete the ParmVarDecl objects as well???
3624
3625}
3626
3627/// ActOnBlockStmtExpr - This is called when the body of a block statement
3628/// literal was successfully completed. ^(int x){...}
3629Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3630 Scope *CurScope) {
3631 // Ensure that CurBlock is deleted.
3632 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3633 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3634
Steve Naroff090276f2008-10-10 01:28:17 +00003635 PopDeclContext();
3636
Steve Naroff4eb206b2008-09-03 18:15:37 +00003637 // Pop off CurBlock, handle nested blocks.
3638 CurBlock = CurBlock->PrevBlockInfo;
3639
3640 QualType RetTy = Context.VoidTy;
3641 if (BSI->ReturnType)
3642 RetTy = QualType(BSI->ReturnType, 0);
3643
3644 llvm::SmallVector<QualType, 8> ArgTypes;
3645 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3646 ArgTypes.push_back(BSI->Params[i]->getType());
3647
3648 QualType BlockTy;
3649 if (!BSI->hasPrototype)
3650 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3651 else
3652 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003653 BSI->isVariadic, 0);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003654
3655 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00003656
Steve Naroff1c90bfc2008-10-08 18:44:00 +00003657 BSI->TheDecl->setBody(Body.take());
3658 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003659}
3660
Nate Begeman67295d02008-01-30 20:50:20 +00003661/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00003662/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00003663/// The number of arguments has already been validated to match the number of
3664/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003665static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3666 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00003667 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00003668 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00003669 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3670 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00003671
3672 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00003673 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00003674 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003675 return true;
3676}
3677
3678Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3679 SourceLocation *CommaLocs,
3680 SourceLocation BuiltinLoc,
3681 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003682 // __builtin_overload requires at least 2 arguments
3683 if (NumArgs < 2)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003684 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3685 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003686
Nate Begemane2ce1d92008-01-17 17:46:27 +00003687 // The first argument is required to be a constant expression. It tells us
3688 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003689 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003690 Expr *NParamsExpr = Args[0];
3691 llvm::APSInt constEval(32);
3692 SourceLocation ExpLoc;
3693 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003694 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3695 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003696
3697 // Verify that the number of parameters is > 0
3698 unsigned NumParams = constEval.getZExtValue();
3699 if (NumParams == 0)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003700 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3701 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003702 // Verify that we have at least 1 + NumParams arguments to the builtin.
3703 if ((NumParams + 1) > NumArgs)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003704 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3705 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003706
3707 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00003708 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003709 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003710 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3711 // UsualUnaryConversions will convert the function DeclRefExpr into a
3712 // pointer to function.
3713 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00003714 const FunctionTypeProto *FnType = 0;
3715 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3716 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003717
3718 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3719 // parameters, and the number of parameters must match the value passed to
3720 // the builtin.
3721 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003722 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
3723 << Fn->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003724
3725 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00003726 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00003727 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003728 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003729 if (OE)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003730 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
3731 << OE->getFn()->getSourceRange();
Nate Begeman796ef3d2008-01-31 05:38:29 +00003732 // Remember our match, and continue processing the remaining arguments
3733 // to catch any errors.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003734 OE = new OverloadExpr(Args, NumArgs, i,
3735 FnType->getResultType().getNonReferenceType(),
Nate Begeman796ef3d2008-01-31 05:38:29 +00003736 BuiltinLoc, RParenLoc);
3737 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003738 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00003739 // Return the newly created OverloadExpr node, if we succeded in matching
3740 // exactly one of the candidate functions.
3741 if (OE)
3742 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003743
3744 // If we didn't find a matching function Expr in the __builtin_overload list
3745 // the return an error.
3746 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00003747 for (unsigned i = 0; i != NumParams; ++i) {
3748 if (i != 0) typeNames += ", ";
3749 typeNames += Args[i+1]->getType().getAsString();
3750 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003751
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003752 return Diag(BuiltinLoc, diag::err_overload_no_match)
3753 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003754}
3755
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003756Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3757 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00003758 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003759 Expr *E = static_cast<Expr*>(expr);
3760 QualType T = QualType::getFromOpaquePtr(type);
3761
3762 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003763
3764 // Get the va_list type
3765 QualType VaListType = Context.getBuiltinVaListType();
3766 // Deal with implicit array decay; for example, on x86-64,
3767 // va_list is an array, but it's supposed to decay to
3768 // a pointer for va_arg.
3769 if (VaListType->isArrayType())
3770 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00003771 // Make sure the input expression also decays appropriately.
3772 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003773
3774 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003775 return Diag(E->getLocStart(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003776 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00003777 << E->getType() << E->getSourceRange();
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003778
3779 // FIXME: Warn if a non-POD type is passed in.
3780
Douglas Gregor9d293df2008-10-28 00:22:11 +00003781 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003782}
3783
Douglas Gregor2d8b2732008-11-29 04:51:27 +00003784Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
3785 // The type of __null will be int or long, depending on the size of
3786 // pointers on the target.
3787 QualType Ty;
3788 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
3789 Ty = Context.IntTy;
3790 else
3791 Ty = Context.LongTy;
3792
3793 return new GNUNullExpr(Ty, TokenLoc);
3794}
3795
Chris Lattner5cf216b2008-01-04 18:04:52 +00003796bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3797 SourceLocation Loc,
3798 QualType DstType, QualType SrcType,
3799 Expr *SrcExpr, const char *Flavor) {
3800 // Decode the result (notice that AST's are still created for extensions).
3801 bool isInvalid = false;
3802 unsigned DiagKind;
3803 switch (ConvTy) {
3804 default: assert(0 && "Unknown conversion type");
3805 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003806 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00003807 DiagKind = diag::ext_typecheck_convert_pointer_int;
3808 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003809 case IntToPointer:
3810 DiagKind = diag::ext_typecheck_convert_int_pointer;
3811 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003812 case IncompatiblePointer:
3813 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3814 break;
3815 case FunctionVoidPointer:
3816 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3817 break;
3818 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00003819 // If the qualifiers lost were because we were applying the
3820 // (deprecated) C++ conversion from a string literal to a char*
3821 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3822 // Ideally, this check would be performed in
3823 // CheckPointerTypesForAssignment. However, that would require a
3824 // bit of refactoring (so that the second argument is an
3825 // expression, rather than a type), which should be done as part
3826 // of a larger effort to fix CheckPointerTypesForAssignment for
3827 // C++ semantics.
3828 if (getLangOptions().CPlusPlus &&
3829 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3830 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003831 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3832 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003833 case IntToBlockPointer:
3834 DiagKind = diag::err_int_to_block_pointer;
3835 break;
3836 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00003837 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003838 break;
Steve Naroff39579072008-10-14 22:18:38 +00003839 case IncompatibleObjCQualifiedId:
3840 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3841 // it can give a more specific diagnostic.
3842 DiagKind = diag::warn_incompatible_qualified_id;
3843 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003844 case Incompatible:
3845 DiagKind = diag::err_typecheck_convert_incompatible;
3846 isInvalid = true;
3847 break;
3848 }
3849
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003850 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
3851 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00003852 return isInvalid;
3853}
Anders Carlssone21555e2008-11-30 19:50:32 +00003854
3855bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
3856{
3857 Expr::EvalResult EvalResult;
3858
3859 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
3860 EvalResult.HasSideEffects) {
3861 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
3862
3863 if (EvalResult.Diag) {
3864 // We only show the note if it's not the usual "invalid subexpression"
3865 // or if it's actually in a subexpression.
3866 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
3867 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
3868 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3869 }
3870
3871 return true;
3872 }
3873
3874 if (EvalResult.Diag) {
3875 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
3876 E->getSourceRange();
3877
3878 // Print the reason it's not a constant.
3879 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
3880 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3881 }
3882
3883 if (Result)
3884 *Result = EvalResult.Val.getInt();
3885 return false;
3886}