blob: 6a98a5bc7e968f7b7ca1a41b0e7b312b06613a73 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Chris Lattner299b8842008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattner299b8842008-07-25 21:10:04 +000033/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
34void Sema::DefaultFunctionArrayConversion(Expr *&E) {
35 QualType Ty = E->getType();
36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
37
Chris Lattner299b8842008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000040 else if (Ty->isArrayType()) {
41 // In C90 mode, arrays only promote to pointers if the array expression is
42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
43 // type 'array of type' is converted to an expression that has type 'pointer
44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
45 // that has type 'array of type' ...". The relevant change is "an lvalue"
46 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000047 //
48 // C++ 4.2p1:
49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
50 // T" can be converted to an rvalue of type "pointer to T".
51 //
52 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
53 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattner299b8842008-07-25 21:10:04 +000056}
57
58/// UsualUnaryConversions - Performs various conversions that are common to most
59/// operators (C99 6.3). The conversions of array and function types are
60/// sometimes surpressed. For example, the array->pointer conversion doesn't
61/// apply if the array is an argument to the sizeof or address (&) operators.
62/// In these instances, this routine should *not* be called.
63Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
64 QualType Ty = Expr->getType();
65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
66
Chris Lattner299b8842008-07-25 21:10:04 +000067 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
68 ImpCastExprToType(Expr, Context.IntTy);
69 else
70 DefaultFunctionArrayConversion(Expr);
71
72 return Expr;
73}
74
Chris Lattner9305c3d2008-07-25 22:25:12 +000075/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
76/// do not have a prototype. Arguments that have type float are promoted to
77/// double. All other argument types are converted by UsualUnaryConversions().
78void Sema::DefaultArgumentPromotion(Expr *&Expr) {
79 QualType Ty = Expr->getType();
80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
81
82 // If this is a 'float' (CVR qualified or typedef) promote to double.
83 if (const BuiltinType *BT = Ty->getAsBuiltinType())
84 if (BT->getKind() == BuiltinType::Float)
85 return ImpCastExprToType(Expr, Context.DoubleTy);
86
87 UsualUnaryConversions(Expr);
88}
89
Chris Lattner299b8842008-07-25 21:10:04 +000090/// UsualArithmeticConversions - Performs various conversions that are common to
91/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
92/// routine returns the first non-arithmetic type found. The client is
93/// responsible for emitting appropriate error diagnostics.
94/// FIXME: verify the conversion rules for "complex int" are consistent with
95/// GCC.
96QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
97 bool isCompAssign) {
98 if (!isCompAssign) {
99 UsualUnaryConversions(lhsExpr);
100 UsualUnaryConversions(rhsExpr);
101 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000102
Chris Lattner299b8842008-07-25 21:10:04 +0000103 // For conversion purposes, we ignore any qualifiers.
104 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000105 QualType lhs =
106 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
107 QualType rhs =
108 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000109
110 // If both types are identical, no conversion is needed.
111 if (lhs == rhs)
112 return lhs;
113
114 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
115 // The caller can deal with this (e.g. pointer + int).
116 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
117 return lhs;
118
119 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
120 if (!isCompAssign) {
121 ImpCastExprToType(lhsExpr, destType);
122 ImpCastExprToType(rhsExpr, destType);
123 }
124 return destType;
125}
126
127QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
128 // Perform the usual unary conversions. We do this early so that
129 // integral promotions to "int" can allow us to exit early, in the
130 // lhs == rhs check. Also, for conversion purposes, we ignore any
131 // qualifiers. For example, "const float" and "float" are
132 // equivalent.
Douglas Gregor3d4492e2008-11-13 20:12:29 +0000133 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
134 else lhs = lhs.getUnqualifiedType();
135 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
136 else rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000137
Chris Lattner299b8842008-07-25 21:10:04 +0000138 // If both types are identical, no conversion is needed.
139 if (lhs == rhs)
140 return lhs;
141
142 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
143 // The caller can deal with this (e.g. pointer + int).
144 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
145 return lhs;
146
147 // At this point, we have two different arithmetic types.
148
149 // Handle complex types first (C99 6.3.1.8p1).
150 if (lhs->isComplexType() || rhs->isComplexType()) {
151 // if we have an integer operand, the result is the complex type.
152 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
153 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000154 return lhs;
155 }
156 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
157 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000158 return rhs;
159 }
160 // This handles complex/complex, complex/float, or float/complex.
161 // When both operands are complex, the shorter operand is converted to the
162 // type of the longer, and that is the type of the result. This corresponds
163 // to what is done when combining two real floating-point operands.
164 // The fun begins when size promotion occur across type domains.
165 // From H&S 6.3.4: When one operand is complex and the other is a real
166 // floating-point type, the less precise type is converted, within it's
167 // real or complex domain, to the precision of the other type. For example,
168 // when combining a "long double" with a "double _Complex", the
169 // "double _Complex" is promoted to "long double _Complex".
170 int result = Context.getFloatingTypeOrder(lhs, rhs);
171
172 if (result > 0) { // The left side is bigger, convert rhs.
173 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000174 } else if (result < 0) { // The right side is bigger, convert lhs.
175 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000176 }
177 // At this point, lhs and rhs have the same rank/size. Now, make sure the
178 // domains match. This is a requirement for our implementation, C99
179 // does not require this promotion.
180 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
181 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000182 return rhs;
183 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000184 return lhs;
185 }
186 }
187 return lhs; // The domain/size match exactly.
188 }
189 // Now handle "real" floating types (i.e. float, double, long double).
190 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
191 // if we have an integer operand, the result is the real floating type.
192 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
193 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000194 return lhs;
195 }
196 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
197 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000198 return rhs;
199 }
200 // We have two real floating types, float/complex combos were handled above.
201 // Convert the smaller operand to the bigger result.
202 int result = Context.getFloatingTypeOrder(lhs, rhs);
203
204 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000205 return lhs;
206 }
207 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000208 return rhs;
209 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000210 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000211 }
212 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
213 // Handle GCC complex int extension.
214 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
215 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
216
217 if (lhsComplexInt && rhsComplexInt) {
218 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
219 rhsComplexInt->getElementType()) >= 0) {
220 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000221 return lhs;
222 }
Chris Lattner299b8842008-07-25 21:10:04 +0000223 return rhs;
224 } else if (lhsComplexInt && rhs->isIntegerType()) {
225 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000226 return lhs;
227 } else if (rhsComplexInt && lhs->isIntegerType()) {
228 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000229 return rhs;
230 }
231 }
232 // Finally, we have two differing integer types.
233 // The rules for this case are in C99 6.3.1.8
234 int compare = Context.getIntegerTypeOrder(lhs, rhs);
235 bool lhsSigned = lhs->isSignedIntegerType(),
236 rhsSigned = rhs->isSignedIntegerType();
237 QualType destType;
238 if (lhsSigned == rhsSigned) {
239 // Same signedness; use the higher-ranked type
240 destType = compare >= 0 ? lhs : rhs;
241 } else if (compare != (lhsSigned ? 1 : -1)) {
242 // The unsigned type has greater than or equal rank to the
243 // signed type, so use the unsigned type
244 destType = lhsSigned ? rhs : lhs;
245 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
246 // The two types are different widths; if we are here, that
247 // means the signed type is larger than the unsigned type, so
248 // use the signed type.
249 destType = lhsSigned ? lhs : rhs;
250 } else {
251 // The signed type is higher-ranked than the unsigned type,
252 // but isn't actually any bigger (like unsigned int and long
253 // on most 32-bit systems). Use the unsigned type corresponding
254 // to the signed type.
255 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
256 }
Chris Lattner299b8842008-07-25 21:10:04 +0000257 return destType;
258}
259
260//===----------------------------------------------------------------------===//
261// Semantic Analysis for various Expression Types
262//===----------------------------------------------------------------------===//
263
264
Steve Naroff87d58b42007-09-16 03:34:24 +0000265/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000266/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
267/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
268/// multiple tokens. However, the common case is that StringToks points to one
269/// string.
270///
271Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000272Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000273 assert(NumStringToks && "Must have at least one string!");
274
275 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
276 if (Literal.hadError)
277 return ExprResult(true);
278
279 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
280 for (unsigned i = 0; i != NumStringToks; ++i)
281 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000282
283 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000284 if (Literal.Pascal && Literal.GetStringLength() > 256)
285 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
286 SourceRange(StringToks[0].getLocation(),
287 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000288
Chris Lattnera6dcce32008-02-11 00:02:17 +0000289 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000290 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000291 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000292
293 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
294 if (getLangOptions().CPlusPlus)
295 StrTy.addConst();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000296
297 // Get an array type for the string, according to C99 6.4.5. This includes
298 // the nul terminator character as well as the string length for pascal
299 // strings.
300 StrTy = Context.getConstantArrayType(StrTy,
301 llvm::APInt(32, Literal.GetStringLength()+1),
302 ArrayType::Normal, 0);
303
Chris Lattner4b009652007-07-25 00:24:17 +0000304 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
305 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000306 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000307 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000308 StringToks[NumStringToks-1].getLocation());
309}
310
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000311/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
312/// CurBlock to VD should cause it to be snapshotted (as we do for auto
313/// variables defined outside the block) or false if this is not needed (e.g.
314/// for values inside the block or for globals).
315///
316/// FIXME: This will create BlockDeclRefExprs for global variables,
317/// function references, etc which is suboptimal :) and breaks
318/// things like "integer constant expression" tests.
319static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
320 ValueDecl *VD) {
321 // If the value is defined inside the block, we couldn't snapshot it even if
322 // we wanted to.
323 if (CurBlock->TheDecl == VD->getDeclContext())
324 return false;
325
326 // If this is an enum constant or function, it is constant, don't snapshot.
327 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
328 return false;
329
330 // If this is a reference to an extern, static, or global variable, no need to
331 // snapshot it.
332 // FIXME: What about 'const' variables in C++?
333 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
334 return Var->hasLocalStorage();
335
336 return true;
337}
338
339
340
Steve Naroff0acc9c92007-09-15 18:49:24 +0000341/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000342/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000343/// identifier is used in a function call context.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000344/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the
345/// class or namespace that the identifier must be a member of.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000346Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000347 IdentifierInfo &II,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000348 bool HasTrailingLParen,
349 const CXXScopeSpec *SS) {
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000350 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
351}
352
353/// ActOnDeclarationNameExpr - The parser has read some kind of name
354/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
355/// performs lookup on that name and returns an expression that refers
356/// to that name. This routine isn't directly called from the parser,
357/// because the parser doesn't know about DeclarationName. Rather,
358/// this routine is called by ActOnIdentifierExpr,
359/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
360/// which form the DeclarationName from the corresponding syntactic
361/// forms.
362///
363/// HasTrailingLParen indicates whether this identifier is used in a
364/// function call context. LookupCtx is only used for a C++
365/// qualified-id (foo::bar) to indicate the class or namespace that
366/// the identifier must be a member of.
367Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
368 DeclarationName Name,
369 bool HasTrailingLParen,
370 const CXXScopeSpec *SS) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000371 // Could be enum-constant, value decl, instance variable, etc.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000372 Decl *D;
373 if (SS && !SS->isEmpty()) {
374 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
375 if (DC == 0)
376 return true;
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000377 D = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000378 } else
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000379 D = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000380
381 // If this reference is in an Objective-C method, then ivar lookup happens as
382 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000383 IdentifierInfo *II = Name.getAsIdentifierInfo();
384 if (II && getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000385 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000386 // There are two cases to handle here. 1) scoped lookup could have failed,
387 // in which case we should look for an ivar. 2) scoped lookup could have
388 // found a decl, but that decl is outside the current method (i.e. a global
389 // variable). In these two cases, we do a lookup for an ivar with this
390 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000391 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000392 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000393 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000394 // FIXME: This should use a new expr for a direct reference, don't turn
395 // this into Self->ivar, just return a BareIVarExpr or something.
396 IdentifierInfo &II = Context.Idents.get("self");
397 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
398 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
399 static_cast<Expr*>(SelfExpr.Val), true, true);
400 }
401 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000402 // Needed to implement property "super.method" notation.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000403 if (SD == 0 && II == SuperID) {
Steve Naroff6f786252008-06-02 23:03:37 +0000404 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000405 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000406 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000407 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000408 }
Chris Lattner4b009652007-07-25 00:24:17 +0000409 if (D == 0) {
410 // Otherwise, this could be an implicitly declared function reference (legal
411 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000412 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000413 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000414 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000415 else {
416 // If this name wasn't predeclared and if this is not a function call,
417 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000418 if (SS && !SS->isEmpty())
419 return Diag(Loc, diag::err_typecheck_no_member,
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000420 Name.getAsString(), SS->getRange());
421 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
422 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
423 return Diag(Loc, diag::err_undeclared_use, Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000424 else
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000425 return Diag(Loc, diag::err_undeclared_var_use, Name.getAsString());
Chris Lattner4b009652007-07-25 00:24:17 +0000426 }
427 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000428
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000429 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
430 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
431 if (MD->isStatic())
432 // "invalid use of member 'x' in static member function"
433 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
434 FD->getName());
435 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
436 // "invalid use of nonstatic data member 'x'"
437 return Diag(Loc, diag::err_invalid_non_static_member_use,
438 FD->getName());
439
440 if (FD->isInvalidDecl())
441 return true;
442
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +0000443 // FIXME: Handle 'mutable'.
444 return new DeclRefExpr(FD,
445 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000446 }
447
448 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
449 }
Chris Lattner4b009652007-07-25 00:24:17 +0000450 if (isa<TypedefDecl>(D))
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000451 return Diag(Loc, diag::err_unexpected_typedef, Name.getAsString());
Ted Kremenek42730c52008-01-07 19:49:32 +0000452 if (isa<ObjCInterfaceDecl>(D))
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000453 return Diag(Loc, diag::err_unexpected_interface, Name.getAsString());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000454 if (isa<NamespaceDecl>(D))
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000455 return Diag(Loc, diag::err_unexpected_namespace, Name.getAsString());
Chris Lattner4b009652007-07-25 00:24:17 +0000456
Steve Naroffd6163f32008-09-05 22:11:13 +0000457 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000458 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
459 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
460
Steve Naroffd6163f32008-09-05 22:11:13 +0000461 ValueDecl *VD = cast<ValueDecl>(D);
462
463 // check if referencing an identifier with __attribute__((deprecated)).
464 if (VD->getAttr<DeprecatedAttr>())
465 Diag(Loc, diag::warn_deprecated, VD->getName());
466
467 // Only create DeclRefExpr's for valid Decl's.
468 if (VD->isInvalidDecl())
469 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000470
471 // If the identifier reference is inside a block, and it refers to a value
472 // that is outside the block, create a BlockDeclRefExpr instead of a
473 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
474 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000475 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000476 // We do not do this for things like enum constants, global variables, etc,
477 // as they do not get snapshotted.
478 //
479 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000480 // The BlocksAttr indicates the variable is bound by-reference.
481 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000482 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
483 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000484
485 // Variable will be bound by-copy, make it const within the closure.
486 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000487 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
488 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000489 }
490 // If this reference is not in a block or if the referenced variable is
491 // within the block, create a normal DeclRefExpr.
Douglas Gregor3fb675a2008-10-22 04:14:44 +0000492 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Chris Lattner4b009652007-07-25 00:24:17 +0000493}
494
Chris Lattner69909292008-08-10 01:53:14 +0000495Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000496 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000497 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000498
499 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000500 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000501 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
502 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
503 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000504 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000505
506 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000507 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000508 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000509
Chris Lattner7e637512008-01-12 08:14:25 +0000510 // Pre-defined identifiers are of type char[x], where x is the length of the
511 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000512 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000513 if (getCurFunctionDecl())
514 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000515 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000516 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000517
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000518 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000519 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000520 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000521 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000522}
523
Steve Naroff87d58b42007-09-16 03:34:24 +0000524Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000525 llvm::SmallString<16> CharBuffer;
526 CharBuffer.resize(Tok.getLength());
527 const char *ThisTokBegin = &CharBuffer[0];
528 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
529
530 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
531 Tok.getLocation(), PP);
532 if (Literal.hadError())
533 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000534
535 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
536
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000537 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
538 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000539}
540
Steve Naroff87d58b42007-09-16 03:34:24 +0000541Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000542 // fast path for a single digit (which is quite common). A single digit
543 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
544 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000545 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000546
Chris Lattner8cd0e932008-03-05 18:54:05 +0000547 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000548 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000549 Context.IntTy,
550 Tok.getLocation()));
551 }
552 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000553 // Add padding so that NumericLiteralParser can overread by one character.
554 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000555 const char *ThisTokBegin = &IntegerBuffer[0];
556
557 // Get the spelling of the token, which eliminates trigraphs, etc.
558 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000559
Chris Lattner4b009652007-07-25 00:24:17 +0000560 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
561 Tok.getLocation(), PP);
562 if (Literal.hadError)
563 return ExprResult(true);
564
Chris Lattner1de66eb2007-08-26 03:42:43 +0000565 Expr *Res;
566
567 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000568 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000569 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000570 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000571 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000572 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000573 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000574 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000575
576 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
577
Ted Kremenekddedbe22007-11-29 00:56:49 +0000578 // isExact will be set by GetFloatValue().
579 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000580 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000581 Ty, Tok.getLocation());
582
Chris Lattner1de66eb2007-08-26 03:42:43 +0000583 } else if (!Literal.isIntegerLiteral()) {
584 return ExprResult(true);
585 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000586 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000587
Neil Booth7421e9c2007-08-29 22:00:19 +0000588 // long long is a C99 feature.
589 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000590 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000591 Diag(Tok.getLocation(), diag::ext_longlong);
592
Chris Lattner4b009652007-07-25 00:24:17 +0000593 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000594 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000595
596 if (Literal.GetIntegerValue(ResultVal)) {
597 // If this value didn't fit into uintmax_t, warn and force to ull.
598 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000599 Ty = Context.UnsignedLongLongTy;
600 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000601 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000602 } else {
603 // If this value fits into a ULL, try to figure out what else it fits into
604 // according to the rules of C99 6.4.4.1p5.
605
606 // Octal, Hexadecimal, and integers with a U suffix are allowed to
607 // be an unsigned int.
608 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
609
610 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000611 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000612 if (!Literal.isLong && !Literal.isLongLong) {
613 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000614 unsigned IntSize = Context.Target.getIntWidth();
615
Chris Lattner4b009652007-07-25 00:24:17 +0000616 // Does it fit in a unsigned int?
617 if (ResultVal.isIntN(IntSize)) {
618 // Does it fit in a signed int?
619 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000620 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000621 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000622 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000623 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000624 }
Chris Lattner4b009652007-07-25 00:24:17 +0000625 }
626
627 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000628 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000629 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000630
631 // Does it fit in a unsigned long?
632 if (ResultVal.isIntN(LongSize)) {
633 // Does it fit in a signed long?
634 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000635 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000636 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000637 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000638 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000639 }
Chris Lattner4b009652007-07-25 00:24:17 +0000640 }
641
642 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000643 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000644 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000645
646 // Does it fit in a unsigned long long?
647 if (ResultVal.isIntN(LongLongSize)) {
648 // Does it fit in a signed long long?
649 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000650 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000651 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000652 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000653 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000654 }
655 }
656
657 // If we still couldn't decide a type, we probably have something that
658 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000659 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000660 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000661 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000662 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000663 }
Chris Lattnere4068872008-05-09 05:59:00 +0000664
665 if (ResultVal.getBitWidth() != Width)
666 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000667 }
668
Chris Lattner48d7f382008-04-02 04:24:33 +0000669 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000670 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000671
672 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
673 if (Literal.isImaginary)
674 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
675
676 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000677}
678
Steve Naroff87d58b42007-09-16 03:34:24 +0000679Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000680 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000681 Expr *E = (Expr *)Val;
682 assert((E != 0) && "ActOnParenExpr() missing expr");
683 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000684}
685
686/// The UsualUnaryConversions() function is *not* called by this routine.
687/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000688bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
689 SourceLocation OpLoc,
690 const SourceRange &ExprRange,
691 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000692 // C99 6.5.3.4p1:
693 if (isa<FunctionType>(exprType) && isSizeof)
694 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000695 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000696 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000697 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
698 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000699 else if (exprType->isIncompleteType()) {
700 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
701 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000702 exprType.getAsString(), ExprRange);
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000703 return true; // error
Chris Lattner4b009652007-07-25 00:24:17 +0000704 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000705
706 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000707}
708
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000709/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
710/// the same for @c alignof and @c __alignof
711/// Note that the ArgRange is invalid if isType is false.
712Action::ExprResult
713Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
714 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +0000715 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000716 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000717
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000718 QualType ArgTy;
719 SourceRange Range;
720 if (isType) {
721 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
722 Range = ArgRange;
723 } else {
724 // Get the end location.
725 Expr *ArgEx = (Expr *)TyOrEx;
726 Range = ArgEx->getSourceRange();
727 ArgTy = ArgEx->getType();
728 }
729
730 // Verify that the operand is valid.
731 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +0000732 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000733
734 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
735 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
736 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +0000737}
738
Chris Lattner5110ad52007-08-24 21:41:10 +0000739QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000740 DefaultFunctionArrayConversion(V);
741
Chris Lattnera16e42d2007-08-26 05:39:26 +0000742 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000743 if (const ComplexType *CT = V->getType()->getAsComplexType())
744 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000745
746 // Otherwise they pass through real integer and floating point types here.
747 if (V->getType()->isArithmeticType())
748 return V->getType();
749
750 // Reject anything else.
751 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
752 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000753}
754
755
Chris Lattner4b009652007-07-25 00:24:17 +0000756
Steve Naroff87d58b42007-09-16 03:34:24 +0000757Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000758 tok::TokenKind Kind,
759 ExprTy *Input) {
760 UnaryOperator::Opcode Opc;
761 switch (Kind) {
762 default: assert(0 && "Unknown unary op!");
763 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
764 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
765 }
766 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
767 if (result.isNull())
768 return true;
769 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
770}
771
772Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000773ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000774 ExprTy *Idx, SourceLocation RLoc) {
775 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
776
777 // Perform default conversions.
778 DefaultFunctionArrayConversion(LHSExp);
779 DefaultFunctionArrayConversion(RHSExp);
780
781 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
782
783 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000784 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000785 // in the subscript position. As a result, we need to derive the array base
786 // and index from the expression types.
787 Expr *BaseExpr, *IndexExpr;
788 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000789 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000790 BaseExpr = LHSExp;
791 IndexExpr = RHSExp;
792 // FIXME: need to deal with const...
793 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000794 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000795 // Handle the uncommon case of "123[Ptr]".
796 BaseExpr = RHSExp;
797 IndexExpr = LHSExp;
798 // FIXME: need to deal with const...
799 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000800 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
801 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000802 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000803
804 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000805 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
806 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000807 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000808 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000809 // FIXME: need to deal with const...
810 ResultType = VTy->getElementType();
811 } else {
812 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
813 RHSExp->getSourceRange());
814 }
815 // C99 6.5.2.1p1
816 if (!IndexExpr->getType()->isIntegerType())
817 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
818 IndexExpr->getSourceRange());
819
820 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
821 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000822 // void (*)(int)) and pointers to incomplete types. Functions are not
823 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000824 if (!ResultType->isObjectType())
825 return Diag(BaseExpr->getLocStart(),
826 diag::err_typecheck_subscript_not_object,
827 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
828
829 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
830}
831
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000832QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000833CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000834 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000835 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000836
837 // This flag determines whether or not the component is to be treated as a
838 // special name, or a regular GLSL-style component access.
839 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000840
841 // The vector accessor can't exceed the number of elements.
842 const char *compStr = CompName.getName();
843 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000844 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000845 baseType.getAsString(), SourceRange(CompLoc));
846 return QualType();
847 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000848
849 // Check that we've found one of the special components, or that the component
850 // names must come from the same set.
851 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
852 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
853 SpecialComponent = true;
854 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000855 do
856 compStr++;
857 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
858 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
859 do
860 compStr++;
861 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
862 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
863 do
864 compStr++;
865 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
866 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000867
Nate Begemanc8e51f82008-05-09 06:41:27 +0000868 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000869 // We didn't get to the end of the string. This means the component names
870 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000871 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000872 std::string(compStr,compStr+1), SourceRange(CompLoc));
873 return QualType();
874 }
875 // Each component accessor can't exceed the vector type.
876 compStr = CompName.getName();
877 while (*compStr) {
878 if (vecType->isAccessorWithinNumElements(*compStr))
879 compStr++;
880 else
881 break;
882 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000883 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000884 // We didn't get to the end of the string. This means a component accessor
885 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000886 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000887 baseType.getAsString(), SourceRange(CompLoc));
888 return QualType();
889 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000890
891 // If we have a special component name, verify that the current vector length
892 // is an even number, since all special component names return exactly half
893 // the elements.
894 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Daniel Dunbar45a91802008-09-30 17:22:47 +0000895 Diag(OpLoc, diag::err_ext_vector_component_requires_even,
896 baseType.getAsString(), SourceRange(CompLoc));
Nate Begemanc8e51f82008-05-09 06:41:27 +0000897 return QualType();
898 }
899
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000900 // The component accessor looks fine - now we need to compute the actual type.
901 // The vector type is implied by the component accessor. For example,
902 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000903 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
904 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
905 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000906 if (CompSize == 1)
907 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000908
Nate Begemanaf6ed502008-04-18 23:10:10 +0000909 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000910 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000911 // diagostics look bad. We want extended vector types to appear built-in.
912 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
913 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
914 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000915 }
916 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000917}
918
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000919/// constructSetterName - Return the setter name for the given
920/// identifier, i.e. "set" + Name where the initial character of Name
921/// has been capitalized.
922// FIXME: Merge with same routine in Parser. But where should this
923// live?
924static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
925 const IdentifierInfo *Name) {
926 unsigned N = Name->getLength();
927 char *SelectorName = new char[3 + N];
928 memcpy(SelectorName, "set", 3);
929 memcpy(&SelectorName[3], Name->getName(), N);
930 SelectorName[3] = toupper(SelectorName[3]);
931
932 IdentifierInfo *Setter =
933 &Idents.get(SelectorName, &SelectorName[3 + N]);
934 delete[] SelectorName;
935 return Setter;
936}
937
Chris Lattner4b009652007-07-25 00:24:17 +0000938Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000939ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000940 tok::TokenKind OpKind, SourceLocation MemberLoc,
941 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000942 Expr *BaseExpr = static_cast<Expr *>(Base);
943 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000944
945 // Perform default conversions.
946 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000947
Steve Naroff2cb66382007-07-26 03:11:44 +0000948 QualType BaseType = BaseExpr->getType();
949 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000950
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000951 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
952 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000953 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000954 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000955 BaseType = PT->getPointeeType();
956 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000957 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
958 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000959 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000960
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000961 // Handle field access to simple records. This also handles access to fields
962 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000963 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000964 RecordDecl *RDecl = RTy->getDecl();
965 if (RTy->isIncompleteType())
966 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
967 BaseExpr->getSourceRange());
968 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000969 FieldDecl *MemberDecl = RDecl->getMember(&Member);
970 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000971 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
972 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000973
974 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000975 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000976 QualType MemberType = MemberDecl->getType();
977 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000978 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000979 if (CXXFieldDecl *CXXMember = dyn_cast<CXXFieldDecl>(MemberDecl)) {
980 if (CXXMember->isMutable())
981 combinedQualifiers &= ~QualType::Const;
982 }
Eli Friedman76b49832008-02-06 22:48:16 +0000983 MemberType = MemberType.getQualifiedType(combinedQualifiers);
984
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000985 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000986 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000987 }
988
Chris Lattnere9d71612008-07-21 04:59:05 +0000989 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
990 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000991 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
992 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000993 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000994 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000995 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000996 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000997 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000998 }
999
Chris Lattnere9d71612008-07-21 04:59:05 +00001000 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1001 // pointer to a (potentially qualified) interface type.
1002 const PointerType *PTy;
1003 const ObjCInterfaceType *IFTy;
1004 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1005 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1006 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001007
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001008 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001009 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1010 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1011
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001012 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001013 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1014 E = IFTy->qual_end(); I != E; ++I)
1015 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1016 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001017
1018 // If that failed, look for an "implicit" property by seeing if the nullary
1019 // selector is implemented.
1020
1021 // FIXME: The logic for looking up nullary and unary selectors should be
1022 // shared with the code in ActOnInstanceMessage.
1023
1024 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1025 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1026
1027 // If this reference is in an @implementation, check for 'private' methods.
1028 if (!Getter)
1029 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1030 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1031 if (ObjCImplementationDecl *ImpDecl =
1032 ObjCImplementations[ClassDecl->getIdentifier()])
1033 Getter = ImpDecl->getInstanceMethod(Sel);
1034
Steve Naroff04151f32008-10-22 19:16:27 +00001035 // Look through local category implementations associated with the class.
1036 if (!Getter) {
1037 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1038 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1039 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1040 }
1041 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001042 if (Getter) {
1043 // If we found a getter then this may be a valid dot-reference, we
1044 // need to also look for the matching setter.
1045 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1046 &Member);
1047 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1048 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1049
1050 if (!Setter) {
1051 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1052 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1053 if (ObjCImplementationDecl *ImpDecl =
1054 ObjCImplementations[ClassDecl->getIdentifier()])
1055 Setter = ImpDecl->getInstanceMethod(SetterSel);
1056 }
1057
1058 // FIXME: There are some issues here. First, we are not
1059 // diagnosing accesses to read-only properties because we do not
1060 // know if this is a getter or setter yet. Second, we are
1061 // checking that the type of the setter matches the type we
1062 // expect.
1063 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1064 MemberLoc, BaseExpr);
1065 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001066 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001067 // Handle properties on qualified "id" protocols.
1068 const ObjCQualifiedIdType *QIdTy;
1069 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1070 // Check protocols on qualified interfaces.
1071 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1072 E = QIdTy->qual_end(); I != E; ++I)
1073 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1074 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1075 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001076 // Handle 'field access' to vectors, such as 'V.xx'.
1077 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1078 // Component access limited to variables (reject vec4.rg.g).
1079 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1080 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +00001081 return Diag(MemberLoc, diag::err_ext_vector_component_access,
1082 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001083 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1084 if (ret.isNull())
1085 return true;
1086 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1087 }
1088
Chris Lattner7d5a8762008-07-21 05:35:34 +00001089 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1090 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001091}
1092
Steve Naroff87d58b42007-09-16 03:34:24 +00001093/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001094/// This provides the location of the left/right parens and a list of comma
1095/// locations.
1096Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001097ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001098 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001099 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1100 Expr *Fn = static_cast<Expr *>(fn);
1101 Expr **Args = reinterpret_cast<Expr**>(args);
1102 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001103 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001104 OverloadedFunctionDecl *Ovl = NULL;
1105
1106 // If we're directly calling a function or a set of overloaded
1107 // functions, get the appropriate declaration.
1108 {
1109 DeclRefExpr *DRExpr = NULL;
1110 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1111 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1112 else
1113 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1114
1115 if (DRExpr) {
1116 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1117 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1118 }
1119 }
1120
1121 // If we have a set of overloaded functions, perform overload
1122 // resolution to pick the function.
1123 if (Ovl) {
1124 OverloadCandidateSet CandidateSet;
1125 OverloadCandidateSet::iterator Best;
1126 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
1127 switch (BestViableFunction(CandidateSet, Best)) {
1128 case OR_Success:
1129 {
1130 // Success! Let the remainder of this function build a call to
1131 // the function selected by overload resolution.
1132 FDecl = Best->Function;
1133 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1134 Fn->getSourceRange().getBegin());
1135 delete Fn;
1136 Fn = NewFn;
1137 }
1138 break;
1139
1140 case OR_No_Viable_Function:
1141 if (CandidateSet.empty())
1142 Diag(Fn->getSourceRange().getBegin(),
1143 diag::err_ovl_no_viable_function_in_call, Ovl->getName(),
1144 Fn->getSourceRange());
1145 else {
1146 Diag(Fn->getSourceRange().getBegin(),
1147 diag::err_ovl_no_viable_function_in_call_with_cands,
1148 Ovl->getName(), Fn->getSourceRange());
1149 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1150 }
1151 return true;
1152
1153 case OR_Ambiguous:
1154 Diag(Fn->getSourceRange().getBegin(),
1155 diag::err_ovl_ambiguous_call, Ovl->getName(),
1156 Fn->getSourceRange());
1157 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1158 return true;
1159 }
1160 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001161
1162 // Promote the function operand.
1163 UsualUnaryConversions(Fn);
1164
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001165 // Make the call expr early, before semantic checks. This guarantees cleanup
1166 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001167 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001168 Context.BoolTy, RParenLoc));
Steve Naroffd6163f32008-09-05 22:11:13 +00001169 const FunctionType *FuncT;
1170 if (!Fn->getType()->isBlockPointerType()) {
1171 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1172 // have type pointer to function".
1173 const PointerType *PT = Fn->getType()->getAsPointerType();
1174 if (PT == 0)
1175 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1176 Fn->getSourceRange());
1177 FuncT = PT->getPointeeType()->getAsFunctionType();
1178 } else { // This is a block call.
1179 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1180 getAsFunctionType();
1181 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001182 if (FuncT == 0)
Chris Lattner61000b12008-08-14 04:33:24 +00001183 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1184 Fn->getSourceRange());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001185
1186 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001187 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001188
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001189 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001190 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1191 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001192 unsigned NumArgsInProto = Proto->getNumArgs();
1193 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001194
Chris Lattner3e254fb2008-04-08 04:40:51 +00001195 // If too few arguments are available (and we don't have default
1196 // arguments for the remaining parameters), don't make the call.
1197 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +00001198 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001199 // Use default arguments for missing arguments
1200 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +00001201 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001202 } else
Steve Naroffd6163f32008-09-05 22:11:13 +00001203 return Diag(RParenLoc,
1204 !Fn->getType()->isBlockPointerType()
1205 ? diag::err_typecheck_call_too_few_args
1206 : diag::err_typecheck_block_too_few_args,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001207 Fn->getSourceRange());
1208 }
1209
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001210 // If too many are passed and not variadic, error on the extras and drop
1211 // them.
1212 if (NumArgs > NumArgsInProto) {
1213 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001214 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffd6163f32008-09-05 22:11:13 +00001215 !Fn->getType()->isBlockPointerType()
1216 ? diag::err_typecheck_call_too_many_args
1217 : diag::err_typecheck_block_too_many_args,
1218 Fn->getSourceRange(),
Chris Lattner4b009652007-07-25 00:24:17 +00001219 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001220 Args[NumArgs-1]->getLocEnd()));
1221 // This deletes the extra arguments.
1222 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001223 }
1224 NumArgsToCheck = NumArgsInProto;
1225 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001226
Chris Lattner4b009652007-07-25 00:24:17 +00001227 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001228 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001229 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001230
1231 Expr *Arg;
1232 if (i < NumArgs)
1233 Arg = Args[i];
1234 else
1235 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001236 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001237
Douglas Gregor81c29152008-10-29 00:13:59 +00001238 // Pass the argument.
1239 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner005ed752008-01-04 18:04:52 +00001240 return true;
Douglas Gregor81c29152008-10-29 00:13:59 +00001241
1242 TheCall->setArg(i, Arg);
Chris Lattner4b009652007-07-25 00:24:17 +00001243 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001244
1245 // If this is a variadic call, handle args passed through "...".
1246 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001247 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001248 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1249 Expr *Arg = Args[i];
1250 DefaultArgumentPromotion(Arg);
1251 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001252 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001253 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001254 } else {
1255 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1256
Steve Naroffdb65e052007-08-28 23:30:39 +00001257 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001258 for (unsigned i = 0; i != NumArgs; i++) {
1259 Expr *Arg = Args[i];
1260 DefaultArgumentPromotion(Arg);
1261 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001262 }
Chris Lattner4b009652007-07-25 00:24:17 +00001263 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001264
Chris Lattner2e64c072007-08-10 20:18:51 +00001265 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001266 if (FDecl)
1267 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001268
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001269 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001270}
1271
1272Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001273ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001274 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001275 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001276 QualType literalType = QualType::getFromOpaquePtr(Ty);
1277 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001278 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001279 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001280
Eli Friedman8c2173d2008-05-20 05:22:08 +00001281 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001282 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001283 return Diag(LParenLoc,
1284 diag::err_variable_object_no_init,
1285 SourceRange(LParenLoc,
1286 literalExpr->getSourceRange().getEnd()));
1287 } else if (literalType->isIncompleteType()) {
1288 return Diag(LParenLoc,
1289 diag::err_typecheck_decl_incomplete_type,
1290 literalType.getAsString(),
1291 SourceRange(LParenLoc,
1292 literalExpr->getSourceRange().getEnd()));
1293 }
1294
Douglas Gregor6428e762008-11-05 15:29:30 +00001295 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
1296 "temporary"))
Steve Naroff92590f92008-01-09 20:58:06 +00001297 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001298
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001299 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001300 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001301 if (CheckForConstantInitializer(literalExpr, literalType))
1302 return true;
1303 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001304 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1305 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001306}
1307
1308Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001309ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001310 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001311 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001312 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001313
Steve Naroff0acc9c92007-09-15 18:49:24 +00001314 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001315 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001316
Chris Lattner71ca8c82008-10-26 23:43:26 +00001317 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1318 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001319 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1320 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001321}
1322
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001323/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001324bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001325 UsualUnaryConversions(castExpr);
1326
1327 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1328 // type needs to be scalar.
1329 if (castType->isVoidType()) {
1330 // Cast to void allows any expr type.
1331 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1332 // GCC struct/union extension: allow cast to self.
1333 if (Context.getCanonicalType(castType) !=
1334 Context.getCanonicalType(castExpr->getType()) ||
1335 (!castType->isStructureType() && !castType->isUnionType())) {
1336 // Reject any other conversions to non-scalar types.
1337 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1338 castType.getAsString(), castExpr->getSourceRange());
1339 }
1340
1341 // accept this, but emit an ext-warn.
1342 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1343 castType.getAsString(), castExpr->getSourceRange());
1344 } else if (!castExpr->getType()->isScalarType() &&
1345 !castExpr->getType()->isVectorType()) {
1346 return Diag(castExpr->getLocStart(),
1347 diag::err_typecheck_expect_scalar_operand,
1348 castExpr->getType().getAsString(),castExpr->getSourceRange());
1349 } else if (castExpr->getType()->isVectorType()) {
1350 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1351 return true;
1352 } else if (castType->isVectorType()) {
1353 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1354 return true;
1355 }
1356 return false;
1357}
1358
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001359bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001360 assert(VectorTy->isVectorType() && "Not a vector type!");
1361
1362 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001363 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001364 return Diag(R.getBegin(),
1365 Ty->isVectorType() ?
1366 diag::err_invalid_conversion_between_vectors :
1367 diag::err_invalid_conversion_between_vector_and_integer,
1368 VectorTy.getAsString().c_str(),
1369 Ty.getAsString().c_str(), R);
1370 } else
1371 return Diag(R.getBegin(),
1372 diag::err_invalid_conversion_between_vector_and_scalar,
1373 VectorTy.getAsString().c_str(),
1374 Ty.getAsString().c_str(), R);
1375
1376 return false;
1377}
1378
Chris Lattner4b009652007-07-25 00:24:17 +00001379Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001380ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001381 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001382 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001383
1384 Expr *castExpr = static_cast<Expr*>(Op);
1385 QualType castType = QualType::getFromOpaquePtr(Ty);
1386
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001387 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1388 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00001389 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001390}
1391
Chris Lattner98a425c2007-11-26 01:40:58 +00001392/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1393/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001394inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1395 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1396 UsualUnaryConversions(cond);
1397 UsualUnaryConversions(lex);
1398 UsualUnaryConversions(rex);
1399 QualType condT = cond->getType();
1400 QualType lexT = lex->getType();
1401 QualType rexT = rex->getType();
1402
1403 // first, check the condition.
1404 if (!condT->isScalarType()) { // C99 6.5.15p2
1405 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1406 condT.getAsString());
1407 return QualType();
1408 }
Chris Lattner992ae932008-01-06 22:42:25 +00001409
1410 // Now check the two expressions.
1411
1412 // If both operands have arithmetic type, do the usual arithmetic conversions
1413 // to find a common type: C99 6.5.15p3,5.
1414 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001415 UsualArithmeticConversions(lex, rex);
1416 return lex->getType();
1417 }
Chris Lattner992ae932008-01-06 22:42:25 +00001418
1419 // If both operands are the same structure or union type, the result is that
1420 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001421 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001422 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001423 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001424 // "If both the operands have structure or union type, the result has
1425 // that type." This implies that CV qualifiers are dropped.
1426 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001427 }
Chris Lattner992ae932008-01-06 22:42:25 +00001428
1429 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001430 // The following || allows only one side to be void (a GCC-ism).
1431 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001432 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001433 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1434 rex->getSourceRange());
1435 if (!rexT->isVoidType())
1436 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001437 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001438 ImpCastExprToType(lex, Context.VoidTy);
1439 ImpCastExprToType(rex, Context.VoidTy);
1440 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001441 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001442 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1443 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001444 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1445 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001446 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001447 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001448 return lexT;
1449 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001450 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1451 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001452 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001453 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001454 return rexT;
1455 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001456 // Handle the case where both operands are pointers before we handle null
1457 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001458 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1459 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1460 // get the "pointed to" types
1461 QualType lhptee = LHSPT->getPointeeType();
1462 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001463
Chris Lattner71225142007-07-31 21:27:01 +00001464 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1465 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001466 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001467 // Figure out necessary qualifiers (C99 6.5.15p6)
1468 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001469 QualType destType = Context.getPointerType(destPointee);
1470 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1471 ImpCastExprToType(rex, destType); // promote to void*
1472 return destType;
1473 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001474 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001475 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001476 QualType destType = Context.getPointerType(destPointee);
1477 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1478 ImpCastExprToType(rex, destType); // promote to void*
1479 return destType;
1480 }
Chris Lattner4b009652007-07-25 00:24:17 +00001481
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001482 QualType compositeType = lexT;
1483
1484 // If either type is an Objective-C object type then check
1485 // compatibility according to Objective-C.
1486 if (Context.isObjCObjectPointerType(lexT) ||
1487 Context.isObjCObjectPointerType(rexT)) {
1488 // If both operands are interfaces and either operand can be
1489 // assigned to the other, use that type as the composite
1490 // type. This allows
1491 // xxx ? (A*) a : (B*) b
1492 // where B is a subclass of A.
1493 //
1494 // Additionally, as for assignment, if either type is 'id'
1495 // allow silent coercion. Finally, if the types are
1496 // incompatible then make sure to use 'id' as the composite
1497 // type so the result is acceptable for sending messages to.
1498
1499 // FIXME: This code should not be localized to here. Also this
1500 // should use a compatible check instead of abusing the
1501 // canAssignObjCInterfaces code.
1502 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1503 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1504 if (LHSIface && RHSIface &&
1505 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1506 compositeType = lexT;
1507 } else if (LHSIface && RHSIface &&
1508 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1509 compositeType = rexT;
1510 } else if (Context.isObjCIdType(lhptee) ||
1511 Context.isObjCIdType(rhptee)) {
1512 // FIXME: This code looks wrong, because isObjCIdType checks
1513 // the struct but getObjCIdType returns the pointer to
1514 // struct. This is horrible and should be fixed.
1515 compositeType = Context.getObjCIdType();
1516 } else {
1517 QualType incompatTy = Context.getObjCIdType();
1518 ImpCastExprToType(lex, incompatTy);
1519 ImpCastExprToType(rex, incompatTy);
1520 return incompatTy;
1521 }
1522 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1523 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001524 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001525 lexT.getAsString(), rexT.getAsString(),
1526 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001527 // In this situation, we assume void* type. No especially good
1528 // reason, but this is what gcc does, and we do have to pick
1529 // to get a consistent AST.
1530 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001531 ImpCastExprToType(lex, incompatTy);
1532 ImpCastExprToType(rex, incompatTy);
1533 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001534 }
1535 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001536 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1537 // differently qualified versions of compatible types, the result type is
1538 // a pointer to an appropriately qualified version of the *composite*
1539 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001540 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001541 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001542 ImpCastExprToType(lex, compositeType);
1543 ImpCastExprToType(rex, compositeType);
1544 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001545 }
Chris Lattner4b009652007-07-25 00:24:17 +00001546 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001547 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1548 // evaluates to "struct objc_object *" (and is handled above when comparing
1549 // id with statically typed objects).
1550 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1551 // GCC allows qualified id and any Objective-C type to devolve to
1552 // id. Currently localizing to here until clear this should be
1553 // part of ObjCQualifiedIdTypesAreCompatible.
1554 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1555 (lexT->isObjCQualifiedIdType() &&
1556 Context.isObjCObjectPointerType(rexT)) ||
1557 (rexT->isObjCQualifiedIdType() &&
1558 Context.isObjCObjectPointerType(lexT))) {
1559 // FIXME: This is not the correct composite type. This only
1560 // happens to work because id can more or less be used anywhere,
1561 // however this may change the type of method sends.
1562 // FIXME: gcc adds some type-checking of the arguments and emits
1563 // (confusing) incompatible comparison warnings in some
1564 // cases. Investigate.
1565 QualType compositeType = Context.getObjCIdType();
1566 ImpCastExprToType(lex, compositeType);
1567 ImpCastExprToType(rex, compositeType);
1568 return compositeType;
1569 }
1570 }
1571
Steve Naroff3eac7692008-09-10 19:17:48 +00001572 // Selection between block pointer types is ok as long as they are the same.
1573 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1574 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1575 return lexT;
1576
Chris Lattner992ae932008-01-06 22:42:25 +00001577 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001578 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1579 lexT.getAsString(), rexT.getAsString(),
1580 lex->getSourceRange(), rex->getSourceRange());
1581 return QualType();
1582}
1583
Steve Naroff87d58b42007-09-16 03:34:24 +00001584/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001585/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001586Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001587 SourceLocation ColonLoc,
1588 ExprTy *Cond, ExprTy *LHS,
1589 ExprTy *RHS) {
1590 Expr *CondExpr = (Expr *) Cond;
1591 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001592
1593 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1594 // was the condition.
1595 bool isLHSNull = LHSExpr == 0;
1596 if (isLHSNull)
1597 LHSExpr = CondExpr;
1598
Chris Lattner4b009652007-07-25 00:24:17 +00001599 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1600 RHSExpr, QuestionLoc);
1601 if (result.isNull())
1602 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001603 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1604 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001605}
1606
Chris Lattner4b009652007-07-25 00:24:17 +00001607
1608// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1609// being closely modeled after the C99 spec:-). The odd characteristic of this
1610// routine is it effectively iqnores the qualifiers on the top level pointee.
1611// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1612// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001613Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001614Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1615 QualType lhptee, rhptee;
1616
1617 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001618 lhptee = lhsType->getAsPointerType()->getPointeeType();
1619 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001620
1621 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001622 lhptee = Context.getCanonicalType(lhptee);
1623 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001624
Chris Lattner005ed752008-01-04 18:04:52 +00001625 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001626
1627 // C99 6.5.16.1p1: This following citation is common to constraints
1628 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1629 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001630 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001631 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001632 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001633
1634 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1635 // incomplete type and the other is a pointer to a qualified or unqualified
1636 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001637 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001638 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001639 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001640
1641 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001642 assert(rhptee->isFunctionType());
1643 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001644 }
1645
1646 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001647 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001648 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001649
1650 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001651 assert(lhptee->isFunctionType());
1652 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001653 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001654
1655 // Check for ObjC interfaces
1656 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1657 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1658 if (LHSIface && RHSIface &&
1659 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1660 return ConvTy;
1661
1662 // ID acts sort of like void* for ObjC interfaces
1663 if (LHSIface && Context.isObjCIdType(rhptee))
1664 return ConvTy;
1665 if (RHSIface && Context.isObjCIdType(lhptee))
1666 return ConvTy;
1667
Chris Lattner4b009652007-07-25 00:24:17 +00001668 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1669 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001670 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1671 rhptee.getUnqualifiedType()))
1672 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001673 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001674}
1675
Steve Naroff3454b6c2008-09-04 15:10:53 +00001676/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1677/// block pointer types are compatible or whether a block and normal pointer
1678/// are compatible. It is more restrict than comparing two function pointer
1679// types.
1680Sema::AssignConvertType
1681Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1682 QualType rhsType) {
1683 QualType lhptee, rhptee;
1684
1685 // get the "pointed to" type (ignoring qualifiers at the top level)
1686 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1687 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1688
1689 // make sure we operate on the canonical type
1690 lhptee = Context.getCanonicalType(lhptee);
1691 rhptee = Context.getCanonicalType(rhptee);
1692
1693 AssignConvertType ConvTy = Compatible;
1694
1695 // For blocks we enforce that qualifiers are identical.
1696 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1697 ConvTy = CompatiblePointerDiscardsQualifiers;
1698
1699 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1700 return IncompatibleBlockPointer;
1701 return ConvTy;
1702}
1703
Chris Lattner4b009652007-07-25 00:24:17 +00001704/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1705/// has code to accommodate several GCC extensions when type checking
1706/// pointers. Here are some objectionable examples that GCC considers warnings:
1707///
1708/// int a, *pint;
1709/// short *pshort;
1710/// struct foo *pfoo;
1711///
1712/// pint = pshort; // warning: assignment from incompatible pointer type
1713/// a = pint; // warning: assignment makes integer from pointer without a cast
1714/// pint = a; // warning: assignment makes pointer from integer without a cast
1715/// pint = pfoo; // warning: assignment from incompatible pointer type
1716///
1717/// As a result, the code for dealing with pointers is more complex than the
1718/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001719///
Chris Lattner005ed752008-01-04 18:04:52 +00001720Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001721Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001722 // Get canonical types. We're not formatting these types, just comparing
1723 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001724 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1725 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001726
1727 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001728 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001729
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001730 // If the left-hand side is a reference type, then we are in a
1731 // (rare!) case where we've allowed the use of references in C,
1732 // e.g., as a parameter type in a built-in function. In this case,
1733 // just make sure that the type referenced is compatible with the
1734 // right-hand side type. The caller is responsible for adjusting
1735 // lhsType so that the resulting expression does not have reference
1736 // type.
1737 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
1738 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001739 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001740 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001741 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001742
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001743 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1744 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001745 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001746 // Relax integer conversions like we do for pointers below.
1747 if (rhsType->isIntegerType())
1748 return IntToPointer;
1749 if (lhsType->isIntegerType())
1750 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00001751 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001752 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001753
Nate Begemanc5f0f652008-07-14 18:02:46 +00001754 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001755 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001756 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1757 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001758 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001759
Nate Begemanc5f0f652008-07-14 18:02:46 +00001760 // If we are allowing lax vector conversions, and LHS and RHS are both
1761 // vectors, the total size only needs to be the same. This is a bitcast;
1762 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001763 if (getLangOptions().LaxVectorConversions &&
1764 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001765 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1766 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001767 }
1768 return Incompatible;
1769 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001770
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001771 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001772 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001773
Chris Lattner390564e2008-04-07 06:49:41 +00001774 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001775 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001776 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001777
Chris Lattner390564e2008-04-07 06:49:41 +00001778 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001779 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001780
Steve Naroffa982c712008-09-29 18:10:17 +00001781 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00001782 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff3454b6c2008-09-04 15:10:53 +00001783 return BlockVoidPointer;
Steve Naroffa982c712008-09-29 18:10:17 +00001784
1785 // Treat block pointers as objects.
1786 if (getLangOptions().ObjC1 &&
1787 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1788 return Compatible;
1789 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001790 return Incompatible;
1791 }
1792
1793 if (isa<BlockPointerType>(lhsType)) {
1794 if (rhsType->isIntegerType())
1795 return IntToPointer;
1796
Steve Naroffa982c712008-09-29 18:10:17 +00001797 // Treat block pointers as objects.
1798 if (getLangOptions().ObjC1 &&
1799 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1800 return Compatible;
1801
Steve Naroff3454b6c2008-09-04 15:10:53 +00001802 if (rhsType->isBlockPointerType())
1803 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1804
1805 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1806 if (RHSPT->getPointeeType()->isVoidType())
1807 return BlockVoidPointer;
1808 }
Chris Lattner1853da22008-01-04 23:18:45 +00001809 return Incompatible;
1810 }
1811
Chris Lattner390564e2008-04-07 06:49:41 +00001812 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001813 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001814 if (lhsType == Context.BoolTy)
1815 return Compatible;
1816
1817 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001818 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001819
Chris Lattner390564e2008-04-07 06:49:41 +00001820 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001821 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001822
1823 if (isa<BlockPointerType>(lhsType) &&
1824 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1825 return BlockVoidPointer;
Chris Lattner1853da22008-01-04 23:18:45 +00001826 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001827 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001828
Chris Lattner1853da22008-01-04 23:18:45 +00001829 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001830 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001831 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001832 }
1833 return Incompatible;
1834}
1835
Chris Lattner005ed752008-01-04 18:04:52 +00001836Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001837Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001838 if (getLangOptions().CPlusPlus) {
1839 if (!lhsType->isRecordType()) {
1840 // C++ 5.17p3: If the left operand is not of class type, the
1841 // expression is implicitly converted (C++ 4) to the
1842 // cv-unqualified type of the left operand.
Douglas Gregorbb461502008-10-24 04:54:22 +00001843 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001844 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00001845 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001846 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001847 }
1848
1849 // FIXME: Currently, we fall through and treat C++ classes like C
1850 // structures.
1851 }
1852
Steve Naroffcdee22d2007-11-27 17:58:44 +00001853 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1854 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00001855 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1856 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001857 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001858 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001859 return Compatible;
1860 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001861
1862 // We don't allow conversion of non-null-pointer constants to integers.
1863 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1864 return IntToBlockPointer;
1865
Chris Lattner5f505bf2007-10-16 02:55:40 +00001866 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001867 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001868 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001869 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001870 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001871 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00001872 if (!lhsType->isReferenceType())
1873 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001874
Chris Lattner005ed752008-01-04 18:04:52 +00001875 Sema::AssignConvertType result =
1876 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001877
1878 // C99 6.5.16.1p2: The value of the right operand is converted to the
1879 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001880 // CheckAssignmentConstraints allows the left-hand side to be a reference,
1881 // so that we can use references in built-in functions even in C.
1882 // The getNonReferenceType() call makes sure that the resulting expression
1883 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00001884 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001885 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001886 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001887}
1888
Chris Lattner005ed752008-01-04 18:04:52 +00001889Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001890Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1891 return CheckAssignmentConstraints(lhsType, rhsType);
1892}
1893
Chris Lattner1eafdea2008-11-18 01:30:42 +00001894QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
1895 Diag(Loc, diag::err_typecheck_invalid_operands,
Chris Lattner4b009652007-07-25 00:24:17 +00001896 lex->getType().getAsString(), rex->getType().getAsString(),
1897 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001898 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001899}
1900
Chris Lattner1eafdea2008-11-18 01:30:42 +00001901inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00001902 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001903 // For conversion purposes, we ignore any qualifiers.
1904 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001905 QualType lhsType =
1906 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1907 QualType rhsType =
1908 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001909
Nate Begemanc5f0f652008-07-14 18:02:46 +00001910 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001911 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001912 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001913
Nate Begemanc5f0f652008-07-14 18:02:46 +00001914 // Handle the case of a vector & extvector type of the same size and element
1915 // type. It would be nice if we only had one vector type someday.
1916 if (getLangOptions().LaxVectorConversions)
1917 if (const VectorType *LV = lhsType->getAsVectorType())
1918 if (const VectorType *RV = rhsType->getAsVectorType())
1919 if (LV->getElementType() == RV->getElementType() &&
1920 LV->getNumElements() == RV->getNumElements())
1921 return lhsType->isExtVectorType() ? lhsType : rhsType;
1922
1923 // If the lhs is an extended vector and the rhs is a scalar of the same type
1924 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001925 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001926 QualType eltType = V->getElementType();
1927
1928 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1929 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1930 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001931 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001932 return lhsType;
1933 }
1934 }
1935
Nate Begemanc5f0f652008-07-14 18:02:46 +00001936 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001937 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001938 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001939 QualType eltType = V->getElementType();
1940
1941 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1942 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1943 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001944 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001945 return rhsType;
1946 }
1947 }
1948
Chris Lattner4b009652007-07-25 00:24:17 +00001949 // You cannot convert between vector values of different size.
Chris Lattner1eafdea2008-11-18 01:30:42 +00001950 Diag(Loc, diag::err_typecheck_vector_not_convertable,
Chris Lattner4b009652007-07-25 00:24:17 +00001951 lex->getType().getAsString(), rex->getType().getAsString(),
1952 lex->getSourceRange(), rex->getSourceRange());
1953 return QualType();
1954}
1955
1956inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00001957 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001958{
1959 QualType lhsType = lex->getType(), rhsType = rex->getType();
1960
1961 if (lhsType->isVectorType() || rhsType->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00001962 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001963
Steve Naroff8f708362007-08-24 19:07:16 +00001964 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001965
Chris Lattner4b009652007-07-25 00:24:17 +00001966 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001967 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00001968 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001969}
1970
1971inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00001972 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001973{
1974 QualType lhsType = lex->getType(), rhsType = rex->getType();
1975
Steve Naroff8f708362007-08-24 19:07:16 +00001976 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001977
Chris Lattner4b009652007-07-25 00:24:17 +00001978 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001979 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00001980 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001981}
1982
1983inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00001984 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001985{
1986 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00001987 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001988
Steve Naroff8f708362007-08-24 19:07:16 +00001989 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001990
Chris Lattner4b009652007-07-25 00:24:17 +00001991 // handle the common case first (both operands are arithmetic).
1992 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001993 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001994
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001995 // Put any potential pointer into PExp
1996 Expr* PExp = lex, *IExp = rex;
1997 if (IExp->getType()->isPointerType())
1998 std::swap(PExp, IExp);
1999
2000 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2001 if (IExp->getType()->isIntegerType()) {
2002 // Check for arithmetic on pointers to incomplete types
2003 if (!PTy->getPointeeType()->isObjectType()) {
2004 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner1eafdea2008-11-18 01:30:42 +00002005 Diag(Loc, diag::ext_gnu_void_ptr,
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002006 lex->getSourceRange(), rex->getSourceRange());
2007 } else {
Chris Lattner1eafdea2008-11-18 01:30:42 +00002008 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type,
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002009 lex->getType().getAsString(), lex->getSourceRange());
2010 return QualType();
2011 }
2012 }
2013 return PExp->getType();
2014 }
2015 }
2016
Chris Lattner1eafdea2008-11-18 01:30:42 +00002017 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002018}
2019
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002020// C99 6.5.6
2021QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002022 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002023 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002024 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002025
Steve Naroff8f708362007-08-24 19:07:16 +00002026 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002027
Chris Lattnerf6da2912007-12-09 21:53:25 +00002028 // Enforce type constraints: C99 6.5.6p3.
2029
2030 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002031 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002032 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002033
2034 // Either ptr - int or ptr - ptr.
2035 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002036 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002037
Chris Lattnerf6da2912007-12-09 21:53:25 +00002038 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002039 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002040 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002041 if (lpointee->isVoidType()) {
Chris Lattner1eafdea2008-11-18 01:30:42 +00002042 Diag(Loc, diag::ext_gnu_void_ptr,
Chris Lattnerf6da2912007-12-09 21:53:25 +00002043 lex->getSourceRange(), rex->getSourceRange());
2044 } else {
Chris Lattner1eafdea2008-11-18 01:30:42 +00002045 Diag(Loc, diag::err_typecheck_sub_ptr_object,
Chris Lattnerf6da2912007-12-09 21:53:25 +00002046 lex->getType().getAsString(), lex->getSourceRange());
2047 return QualType();
2048 }
2049 }
2050
2051 // The result type of a pointer-int computation is the pointer type.
2052 if (rex->getType()->isIntegerType())
2053 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002054
Chris Lattnerf6da2912007-12-09 21:53:25 +00002055 // Handle pointer-pointer subtractions.
2056 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002057 QualType rpointee = RHSPTy->getPointeeType();
2058
Chris Lattnerf6da2912007-12-09 21:53:25 +00002059 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002060 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002061 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002062 if (rpointee->isVoidType()) {
2063 if (!lpointee->isVoidType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002064 Diag(Loc, diag::ext_gnu_void_ptr,
Chris Lattnerf6da2912007-12-09 21:53:25 +00002065 lex->getSourceRange(), rex->getSourceRange());
2066 } else {
Chris Lattner1eafdea2008-11-18 01:30:42 +00002067 Diag(Loc, diag::err_typecheck_sub_ptr_object,
Chris Lattnerf6da2912007-12-09 21:53:25 +00002068 rex->getType().getAsString(), rex->getSourceRange());
2069 return QualType();
2070 }
2071 }
2072
2073 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002074 if (!Context.typesAreCompatible(
2075 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2076 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner1eafdea2008-11-18 01:30:42 +00002077 Diag(Loc, diag::err_typecheck_sub_ptr_compatible,
Chris Lattnerf6da2912007-12-09 21:53:25 +00002078 lex->getType().getAsString(), rex->getType().getAsString(),
2079 lex->getSourceRange(), rex->getSourceRange());
2080 return QualType();
2081 }
2082
2083 return Context.getPointerDiffType();
2084 }
2085 }
2086
Chris Lattner1eafdea2008-11-18 01:30:42 +00002087 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002088}
2089
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002090// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002091QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002092 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002093 // C99 6.5.7p2: Each of the operands shall have integer type.
2094 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002095 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002096
Chris Lattner2c8bff72007-12-12 05:47:28 +00002097 // Shifts don't perform usual arithmetic conversions, they just do integer
2098 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002099 if (!isCompAssign)
2100 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002101 UsualUnaryConversions(rex);
2102
2103 // "The type of the result is that of the promoted left operand."
2104 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002105}
2106
Eli Friedman0d9549b2008-08-22 00:56:42 +00002107static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2108 ASTContext& Context) {
2109 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2110 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2111 // ID acts sort of like void* for ObjC interfaces
2112 if (LHSIface && Context.isObjCIdType(RHS))
2113 return true;
2114 if (RHSIface && Context.isObjCIdType(LHS))
2115 return true;
2116 if (!LHSIface || !RHSIface)
2117 return false;
2118 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2119 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2120}
2121
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002122// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002123QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002124 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002125 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002126 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002127
Chris Lattner254f3bc2007-08-26 01:18:55 +00002128 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002129 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2130 UsualArithmeticConversions(lex, rex);
2131 else {
2132 UsualUnaryConversions(lex);
2133 UsualUnaryConversions(rex);
2134 }
Chris Lattner4b009652007-07-25 00:24:17 +00002135 QualType lType = lex->getType();
2136 QualType rType = rex->getType();
2137
Ted Kremenek486509e2007-10-29 17:13:39 +00002138 // For non-floating point types, check for self-comparisons of the form
2139 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2140 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002141 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002142 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2143 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002144 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002145 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002146 }
2147
Chris Lattner254f3bc2007-08-26 01:18:55 +00002148 if (isRelational) {
2149 if (lType->isRealType() && rType->isRealType())
2150 return Context.IntTy;
2151 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002152 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002153 if (lType->isFloatingType()) {
2154 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002155 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002156 }
2157
Chris Lattner254f3bc2007-08-26 01:18:55 +00002158 if (lType->isArithmeticType() && rType->isArithmeticType())
2159 return Context.IntTy;
2160 }
Chris Lattner4b009652007-07-25 00:24:17 +00002161
Chris Lattner22be8422007-08-26 01:10:14 +00002162 bool LHSIsNull = lex->isNullPointerConstant(Context);
2163 bool RHSIsNull = rex->isNullPointerConstant(Context);
2164
Chris Lattner254f3bc2007-08-26 01:18:55 +00002165 // All of the following pointer related warnings are GCC extensions, except
2166 // when handling null pointer constants. One day, we can consider making them
2167 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002168 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002169 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002170 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002171 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002172 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002173
Steve Naroff3b435622007-11-13 14:57:38 +00002174 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002175 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2176 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002177 RCanPointeeTy.getUnqualifiedType()) &&
2178 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner1eafdea2008-11-18 01:30:42 +00002179 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers,
Steve Naroff4462cb02007-08-16 21:48:38 +00002180 lType.getAsString(), rType.getAsString(),
2181 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002182 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002183 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002184 return Context.IntTy;
2185 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002186 // Handle block pointer types.
2187 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2188 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2189 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2190
2191 if (!LHSIsNull && !RHSIsNull &&
2192 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner1eafdea2008-11-18 01:30:42 +00002193 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks,
Steve Naroff3454b6c2008-09-04 15:10:53 +00002194 lType.getAsString(), rType.getAsString(),
2195 lex->getSourceRange(), rex->getSourceRange());
2196 }
2197 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2198 return Context.IntTy;
2199 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002200 // Allow block pointers to be compared with null pointer constants.
2201 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2202 (lType->isPointerType() && rType->isBlockPointerType())) {
2203 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner1eafdea2008-11-18 01:30:42 +00002204 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks,
Steve Narofff85d66c2008-09-28 01:11:11 +00002205 lType.getAsString(), rType.getAsString(),
2206 lex->getSourceRange(), rex->getSourceRange());
2207 }
2208 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2209 return Context.IntTy;
2210 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002211
Steve Naroff936c4362008-06-03 14:04:54 +00002212 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002213 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002214 const PointerType *LPT = lType->getAsPointerType();
2215 const PointerType *RPT = rType->getAsPointerType();
2216 bool LPtrToVoid = LPT ?
2217 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2218 bool RPtrToVoid = RPT ?
2219 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2220
2221 if (!LPtrToVoid && !RPtrToVoid &&
2222 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner1eafdea2008-11-18 01:30:42 +00002223 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers,
Steve Naroff3d081ae2008-10-27 10:33:19 +00002224 lType.getAsString(), rType.getAsString(),
2225 lex->getSourceRange(), rex->getSourceRange());
2226 ImpCastExprToType(rex, lType);
2227 return Context.IntTy;
2228 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002229 ImpCastExprToType(rex, lType);
Steve Naroff792800d2008-10-22 22:40:28 +00002230 return Context.IntTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002231 }
Steve Naroff936c4362008-06-03 14:04:54 +00002232 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2233 ImpCastExprToType(rex, lType);
2234 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002235 } else {
2236 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner1eafdea2008-11-18 01:30:42 +00002237 Diag(Loc, diag::warn_incompatible_qualified_id_operands,
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002238 lType.getAsString(), rType.getAsString(),
Steve Naroff19608432008-10-14 22:18:38 +00002239 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002240 ImpCastExprToType(rex, lType);
Steve Naroff792800d2008-10-22 22:40:28 +00002241 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002242 }
Steve Naroff936c4362008-06-03 14:04:54 +00002243 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002244 }
Steve Naroff936c4362008-06-03 14:04:54 +00002245 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2246 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002247 if (!RHSIsNull)
Chris Lattner1eafdea2008-11-18 01:30:42 +00002248 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer,
Steve Naroff4462cb02007-08-16 21:48:38 +00002249 lType.getAsString(), rType.getAsString(),
2250 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002251 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002252 return Context.IntTy;
2253 }
Steve Naroff936c4362008-06-03 14:04:54 +00002254 if (lType->isIntegerType() &&
2255 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002256 if (!LHSIsNull)
Chris Lattner1eafdea2008-11-18 01:30:42 +00002257 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer,
Steve Naroff4462cb02007-08-16 21:48:38 +00002258 lType.getAsString(), rType.getAsString(),
2259 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002260 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002261 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002262 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002263 // Handle block pointers.
2264 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2265 if (!RHSIsNull)
Chris Lattner1eafdea2008-11-18 01:30:42 +00002266 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer,
Steve Naroff4fea7b62008-09-04 16:56:14 +00002267 lType.getAsString(), rType.getAsString(),
2268 lex->getSourceRange(), rex->getSourceRange());
2269 ImpCastExprToType(rex, lType); // promote the integer to pointer
2270 return Context.IntTy;
2271 }
2272 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2273 if (!LHSIsNull)
Chris Lattner1eafdea2008-11-18 01:30:42 +00002274 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer,
Steve Naroff4fea7b62008-09-04 16:56:14 +00002275 lType.getAsString(), rType.getAsString(),
2276 lex->getSourceRange(), rex->getSourceRange());
2277 ImpCastExprToType(lex, rType); // promote the integer to pointer
2278 return Context.IntTy;
2279 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002280 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002281}
2282
Nate Begemanc5f0f652008-07-14 18:02:46 +00002283/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2284/// operates on extended vector types. Instead of producing an IntTy result,
2285/// like a scalar comparison, a vector comparison produces a vector of integer
2286/// types.
2287QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002288 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002289 bool isRelational) {
2290 // Check to make sure we're operating on vectors of the same type and width,
2291 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002292 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002293 if (vType.isNull())
2294 return vType;
2295
2296 QualType lType = lex->getType();
2297 QualType rType = rex->getType();
2298
2299 // For non-floating point types, check for self-comparisons of the form
2300 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2301 // often indicate logic errors in the program.
2302 if (!lType->isFloatingType()) {
2303 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2304 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2305 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002306 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002307 }
2308
2309 // Check for comparisons of floating point operands using != and ==.
2310 if (!isRelational && lType->isFloatingType()) {
2311 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002312 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002313 }
2314
2315 // Return the type for the comparison, which is the same as vector type for
2316 // integer vectors, or an integer type of identical size and number of
2317 // elements for floating point vectors.
2318 if (lType->isIntegerType())
2319 return lType;
2320
2321 const VectorType *VTy = lType->getAsVectorType();
2322
2323 // FIXME: need to deal with non-32b int / non-64b long long
2324 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2325 if (TypeSize == 32) {
2326 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2327 }
2328 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2329 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2330}
2331
Chris Lattner4b009652007-07-25 00:24:17 +00002332inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002333 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002334{
2335 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002336 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002337
Steve Naroff8f708362007-08-24 19:07:16 +00002338 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002339
2340 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002341 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002342 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002343}
2344
2345inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00002346 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00002347{
2348 UsualUnaryConversions(lex);
2349 UsualUnaryConversions(rex);
2350
Eli Friedmanbea3f842008-05-13 20:16:47 +00002351 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002352 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002353 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002354}
2355
Chris Lattner4c2642c2008-11-18 01:22:49 +00002356/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2357/// emit an error and return true. If so, return false.
2358static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2359 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2360 if (IsLV == Expr::MLV_Valid)
2361 return false;
2362
2363 unsigned Diag = 0;
2364 bool NeedType = false;
2365 switch (IsLV) { // C99 6.5.16p2
2366 default: assert(0 && "Unknown result from isModifiableLvalue!");
2367 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00002368 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002369 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2370 NeedType = true;
2371 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002372 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002373 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2374 NeedType = true;
2375 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00002376 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002377 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2378 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002379 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002380 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2381 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002382 case Expr::MLV_IncompleteType:
2383 case Expr::MLV_IncompleteVoidType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002384 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2385 NeedType = true;
2386 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002387 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002388 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2389 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00002390 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002391 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2392 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002393 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002394
Chris Lattner4c2642c2008-11-18 01:22:49 +00002395 if (NeedType)
Chris Lattnerda189c62008-11-18 01:26:17 +00002396 S.Diag(Loc, Diag, E->getType().getAsString(), E->getSourceRange());
Chris Lattner4c2642c2008-11-18 01:22:49 +00002397 else
2398 S.Diag(Loc, Diag, E->getSourceRange());
2399 return true;
2400}
2401
2402
2403
2404// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00002405QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
2406 SourceLocation Loc,
2407 QualType CompoundType) {
2408 // Verify that LHS is a modifiable lvalue, and emit error if not.
2409 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00002410 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00002411
2412 QualType LHSType = LHS->getType();
2413 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00002414
Chris Lattner005ed752008-01-04 18:04:52 +00002415 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002416 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00002417 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002418 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner34c85082008-08-21 18:04:13 +00002419
2420 // If the RHS is a unary plus or minus, check to see if they = and + are
2421 // right next to each other. If so, the user may have typo'd "x =+ 4"
2422 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002423 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00002424 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2425 RHSCheck = ICE->getSubExpr();
2426 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2427 if ((UO->getOpcode() == UnaryOperator::Plus ||
2428 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00002429 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00002430 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002431 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2432 Diag(Loc, diag::warn_not_compound_assign,
Chris Lattner34c85082008-08-21 18:04:13 +00002433 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2434 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2435 }
2436 } else {
2437 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00002438 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00002439 }
Chris Lattner005ed752008-01-04 18:04:52 +00002440
Chris Lattner1eafdea2008-11-18 01:30:42 +00002441 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
2442 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00002443 return QualType();
2444
Chris Lattner4b009652007-07-25 00:24:17 +00002445 // C99 6.5.16p3: The type of an assignment expression is the type of the
2446 // left operand unless the left operand has qualified type, in which case
2447 // it is the unqualified version of the type of the left operand.
2448 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2449 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002450 // C++ 5.17p1: the type of the assignment expression is that of its left
2451 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002452 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002453}
2454
Chris Lattner1eafdea2008-11-18 01:30:42 +00002455// C99 6.5.17
2456QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
2457 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00002458
2459 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002460 DefaultFunctionArrayConversion(RHS);
2461 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002462}
2463
2464/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2465/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2466QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2467 QualType resType = op->getType();
2468 assert(!resType.isNull() && "no type for increment/decrement expression");
2469
Steve Naroffd30e1932007-08-24 17:20:07 +00002470 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00002471 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002472 if (pt->getPointeeType()->isVoidType()) {
2473 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2474 } else if (!pt->getPointeeType()->isObjectType()) {
2475 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00002476 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2477 resType.getAsString(), op->getSourceRange());
2478 return QualType();
2479 }
Steve Naroffd30e1932007-08-24 17:20:07 +00002480 } else if (!resType->isRealType()) {
2481 if (resType->isComplexType())
2482 // C99 does not support ++/-- on complex types.
2483 Diag(OpLoc, diag::ext_integer_increment_complex,
2484 resType.getAsString(), op->getSourceRange());
2485 else {
2486 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2487 resType.getAsString(), op->getSourceRange());
2488 return QualType();
2489 }
Chris Lattner4b009652007-07-25 00:24:17 +00002490 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002491 // At this point, we know we have a real, complex or pointer type.
2492 // Now make sure the operand is a modifiable lvalue.
Chris Lattnerda189c62008-11-18 01:26:17 +00002493 if (CheckForModifiableLvalue(op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00002494 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002495 return resType;
2496}
2497
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002498/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002499/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002500/// where the declaration is needed for type checking. We only need to
2501/// handle cases when the expression references a function designator
2502/// or is an lvalue. Here are some examples:
2503/// - &(x) => x
2504/// - &*****f => f for f a function designator.
2505/// - &s.xx => s
2506/// - &s.zz[1].yy -> s, if zz is an array
2507/// - *(x + 1) -> x, if x is an array
2508/// - &"123"[2] -> 0
2509/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002510static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002511 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002512 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002513 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002514 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002515 // Fields cannot be declared with a 'register' storage class.
2516 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002517 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002518 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002519 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002520 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002521 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002522
Douglas Gregord2baafd2008-10-21 16:13:35 +00002523 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002524 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002525 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002526 return 0;
2527 else
2528 return VD;
2529 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002530 case Stmt::UnaryOperatorClass: {
2531 UnaryOperator *UO = cast<UnaryOperator>(E);
2532
2533 switch(UO->getOpcode()) {
2534 case UnaryOperator::Deref: {
2535 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002536 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2537 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2538 if (!VD || VD->getType()->isPointerType())
2539 return 0;
2540 return VD;
2541 }
2542 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002543 }
2544 case UnaryOperator::Real:
2545 case UnaryOperator::Imag:
2546 case UnaryOperator::Extension:
2547 return getPrimaryDecl(UO->getSubExpr());
2548 default:
2549 return 0;
2550 }
2551 }
2552 case Stmt::BinaryOperatorClass: {
2553 BinaryOperator *BO = cast<BinaryOperator>(E);
2554
2555 // Handle cases involving pointer arithmetic. The result of an
2556 // Assign or AddAssign is not an lvalue so they can be ignored.
2557
2558 // (x + n) or (n + x) => x
2559 if (BO->getOpcode() == BinaryOperator::Add) {
2560 if (BO->getLHS()->getType()->isPointerType()) {
2561 return getPrimaryDecl(BO->getLHS());
2562 } else if (BO->getRHS()->getType()->isPointerType()) {
2563 return getPrimaryDecl(BO->getRHS());
2564 }
2565 }
2566
2567 return 0;
2568 }
Chris Lattner4b009652007-07-25 00:24:17 +00002569 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002570 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002571 case Stmt::ImplicitCastExprClass:
2572 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002573 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002574 default:
2575 return 0;
2576 }
2577}
2578
2579/// CheckAddressOfOperand - The operand of & must be either a function
2580/// designator or an lvalue designating an object. If it is an lvalue, the
2581/// object cannot be declared with storage class register or be a bit field.
2582/// Note: The usual conversions are *not* applied to the operand of the &
2583/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00002584/// In C++, the operand might be an overloaded function name, in which case
2585/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00002586QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002587 if (getLangOptions().C99) {
2588 // Implement C99-only parts of addressof rules.
2589 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2590 if (uOp->getOpcode() == UnaryOperator::Deref)
2591 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2592 // (assuming the deref expression is valid).
2593 return uOp->getSubExpr()->getType();
2594 }
2595 // Technically, there should be a check for array subscript
2596 // expressions here, but the result of one is always an lvalue anyway.
2597 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002598 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002599 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002600
2601 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002602 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2603 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002604 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2605 op->getSourceRange());
2606 return QualType();
2607 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002608 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2609 if (MemExpr->getMemberDecl()->isBitField()) {
2610 Diag(OpLoc, diag::err_typecheck_address_of,
2611 std::string("bit-field"), op->getSourceRange());
2612 return QualType();
2613 }
2614 // Check for Apple extension for accessing vector components.
2615 } else if (isa<ArraySubscriptExpr>(op) &&
2616 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2617 Diag(OpLoc, diag::err_typecheck_address_of,
2618 std::string("vector"), op->getSourceRange());
2619 return QualType();
2620 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002621 // We have an lvalue with a decl. Make sure the decl is not declared
2622 // with the register storage-class specifier.
2623 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2624 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002625 Diag(OpLoc, diag::err_typecheck_address_of,
2626 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002627 return QualType();
2628 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00002629 } else if (isa<OverloadedFunctionDecl>(dcl))
2630 return Context.OverloadTy;
2631 else
Chris Lattner4b009652007-07-25 00:24:17 +00002632 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002633 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002634
Chris Lattner4b009652007-07-25 00:24:17 +00002635 // If the operand has type "type", the result has type "pointer to type".
2636 return Context.getPointerType(op->getType());
2637}
2638
2639QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2640 UsualUnaryConversions(op);
2641 QualType qType = op->getType();
2642
Chris Lattner7931f4a2007-07-31 16:53:04 +00002643 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002644 // Note that per both C89 and C99, this is always legal, even
2645 // if ptype is an incomplete type or void.
2646 // It would be possible to warn about dereferencing a
2647 // void pointer, but it's completely well-defined,
2648 // and such a warning is unlikely to catch any mistakes.
2649 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002650 }
2651 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2652 qType.getAsString(), op->getSourceRange());
2653 return QualType();
2654}
2655
2656static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2657 tok::TokenKind Kind) {
2658 BinaryOperator::Opcode Opc;
2659 switch (Kind) {
2660 default: assert(0 && "Unknown binop!");
2661 case tok::star: Opc = BinaryOperator::Mul; break;
2662 case tok::slash: Opc = BinaryOperator::Div; break;
2663 case tok::percent: Opc = BinaryOperator::Rem; break;
2664 case tok::plus: Opc = BinaryOperator::Add; break;
2665 case tok::minus: Opc = BinaryOperator::Sub; break;
2666 case tok::lessless: Opc = BinaryOperator::Shl; break;
2667 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2668 case tok::lessequal: Opc = BinaryOperator::LE; break;
2669 case tok::less: Opc = BinaryOperator::LT; break;
2670 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2671 case tok::greater: Opc = BinaryOperator::GT; break;
2672 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2673 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2674 case tok::amp: Opc = BinaryOperator::And; break;
2675 case tok::caret: Opc = BinaryOperator::Xor; break;
2676 case tok::pipe: Opc = BinaryOperator::Or; break;
2677 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2678 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2679 case tok::equal: Opc = BinaryOperator::Assign; break;
2680 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2681 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2682 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2683 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2684 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2685 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2686 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2687 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2688 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2689 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2690 case tok::comma: Opc = BinaryOperator::Comma; break;
2691 }
2692 return Opc;
2693}
2694
2695static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2696 tok::TokenKind Kind) {
2697 UnaryOperator::Opcode Opc;
2698 switch (Kind) {
2699 default: assert(0 && "Unknown unary op!");
2700 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2701 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2702 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2703 case tok::star: Opc = UnaryOperator::Deref; break;
2704 case tok::plus: Opc = UnaryOperator::Plus; break;
2705 case tok::minus: Opc = UnaryOperator::Minus; break;
2706 case tok::tilde: Opc = UnaryOperator::Not; break;
2707 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002708 case tok::kw___real: Opc = UnaryOperator::Real; break;
2709 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2710 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2711 }
2712 return Opc;
2713}
2714
Douglas Gregord7f915e2008-11-06 23:29:22 +00002715/// CreateBuiltinBinOp - Creates a new built-in binary operation with
2716/// operator @p Opc at location @c TokLoc. This routine only supports
2717/// built-in operations; ActOnBinOp handles overloaded operators.
2718Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
2719 unsigned Op,
2720 Expr *lhs, Expr *rhs) {
2721 QualType ResultTy; // Result type of the binary operator.
2722 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2723 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
2724
2725 switch (Opc) {
2726 default:
2727 assert(0 && "Unknown binary expr!");
2728 case BinaryOperator::Assign:
2729 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
2730 break;
2731 case BinaryOperator::Mul:
2732 case BinaryOperator::Div:
2733 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
2734 break;
2735 case BinaryOperator::Rem:
2736 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
2737 break;
2738 case BinaryOperator::Add:
2739 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
2740 break;
2741 case BinaryOperator::Sub:
2742 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
2743 break;
2744 case BinaryOperator::Shl:
2745 case BinaryOperator::Shr:
2746 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
2747 break;
2748 case BinaryOperator::LE:
2749 case BinaryOperator::LT:
2750 case BinaryOperator::GE:
2751 case BinaryOperator::GT:
2752 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
2753 break;
2754 case BinaryOperator::EQ:
2755 case BinaryOperator::NE:
2756 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
2757 break;
2758 case BinaryOperator::And:
2759 case BinaryOperator::Xor:
2760 case BinaryOperator::Or:
2761 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
2762 break;
2763 case BinaryOperator::LAnd:
2764 case BinaryOperator::LOr:
2765 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
2766 break;
2767 case BinaryOperator::MulAssign:
2768 case BinaryOperator::DivAssign:
2769 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
2770 if (!CompTy.isNull())
2771 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2772 break;
2773 case BinaryOperator::RemAssign:
2774 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
2775 if (!CompTy.isNull())
2776 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2777 break;
2778 case BinaryOperator::AddAssign:
2779 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
2780 if (!CompTy.isNull())
2781 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2782 break;
2783 case BinaryOperator::SubAssign:
2784 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
2785 if (!CompTy.isNull())
2786 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2787 break;
2788 case BinaryOperator::ShlAssign:
2789 case BinaryOperator::ShrAssign:
2790 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
2791 if (!CompTy.isNull())
2792 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2793 break;
2794 case BinaryOperator::AndAssign:
2795 case BinaryOperator::XorAssign:
2796 case BinaryOperator::OrAssign:
2797 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
2798 if (!CompTy.isNull())
2799 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2800 break;
2801 case BinaryOperator::Comma:
2802 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
2803 break;
2804 }
2805 if (ResultTy.isNull())
2806 return true;
2807 if (CompTy.isNull())
2808 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
2809 else
2810 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
2811}
2812
Chris Lattner4b009652007-07-25 00:24:17 +00002813// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002814Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
2815 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002816 ExprTy *LHS, ExprTy *RHS) {
2817 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2818 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2819
Steve Naroff87d58b42007-09-16 03:34:24 +00002820 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2821 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002822
Douglas Gregord7f915e2008-11-06 23:29:22 +00002823 if (getLangOptions().CPlusPlus &&
2824 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
2825 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002826 // If this is one of the assignment operators, we only perform
2827 // overload resolution if the left-hand side is a class or
2828 // enumeration type (C++ [expr.ass]p3).
2829 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
2830 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
2831 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
2832 }
2833
Douglas Gregord7f915e2008-11-06 23:29:22 +00002834 // C++ [over.binary]p1:
2835 // A binary operator shall be implemented either by a non-static
2836 // member function (9.3) with one parameter or by a non-member
2837 // function with two parameters. Thus, for any binary operator
2838 // @, x@y can be interpreted as either x.operator@(y) or
2839 // operator@(x,y). If both forms of the operator function have
2840 // been declared, the rules in 13.3.1.2 determines which, if
2841 // any, interpretation is used.
2842 OverloadCandidateSet CandidateSet;
2843
2844 // Determine which overloaded operator we're dealing with.
2845 static const OverloadedOperatorKind OverOps[] = {
2846 OO_Star, OO_Slash, OO_Percent,
2847 OO_Plus, OO_Minus,
2848 OO_LessLess, OO_GreaterGreater,
2849 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2850 OO_EqualEqual, OO_ExclaimEqual,
2851 OO_Amp,
2852 OO_Caret,
2853 OO_Pipe,
2854 OO_AmpAmp,
2855 OO_PipePipe,
2856 OO_Equal, OO_StarEqual,
2857 OO_SlashEqual, OO_PercentEqual,
2858 OO_PlusEqual, OO_MinusEqual,
2859 OO_LessLessEqual, OO_GreaterGreaterEqual,
2860 OO_AmpEqual, OO_CaretEqual,
2861 OO_PipeEqual,
2862 OO_Comma
2863 };
2864 OverloadedOperatorKind OverOp = OverOps[Opc];
2865
2866 // Lookup this operator.
Douglas Gregor96a32dd2008-11-18 14:39:36 +00002867 Decl *D = LookupDecl(Context.DeclarationNames.getCXXOperatorName(OverOp),
Douglas Gregord7f915e2008-11-06 23:29:22 +00002868 Decl::IDNS_Ordinary, S);
2869
2870 // Add any overloaded operators we find to the overload set.
2871 Expr *Args[2] = { lhs, rhs };
2872 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
2873 AddOverloadCandidate(FD, Args, 2, CandidateSet);
2874 else if (OverloadedFunctionDecl *Ovl
2875 = dyn_cast_or_null<OverloadedFunctionDecl>(D))
2876 AddOverloadCandidates(Ovl, Args, 2, CandidateSet);
2877
Douglas Gregor70d26122008-11-12 17:17:38 +00002878 // Add builtin overload candidates (C++ [over.built]).
2879 AddBuiltinBinaryOperatorCandidates(OverOp, Args, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00002880
2881 // Perform overload resolution.
2882 OverloadCandidateSet::iterator Best;
2883 switch (BestViableFunction(CandidateSet, Best)) {
2884 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00002885 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002886 FunctionDecl *FnDecl = Best->Function;
2887
Douglas Gregor70d26122008-11-12 17:17:38 +00002888 if (FnDecl) {
2889 // We matched an overloaded operator. Build a call to that
2890 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002891
Douglas Gregor70d26122008-11-12 17:17:38 +00002892 // Convert the arguments.
2893 // FIXME: Conversion will be different for member operators.
2894 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
2895 "passing") ||
2896 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
2897 "passing"))
2898 return true;
Douglas Gregord7f915e2008-11-06 23:29:22 +00002899
Douglas Gregor70d26122008-11-12 17:17:38 +00002900 // Determine the result type
2901 QualType ResultTy
2902 = FnDecl->getType()->getAsFunctionType()->getResultType();
2903 ResultTy = ResultTy.getNonReferenceType();
2904
2905 // Build the actual expression node.
Douglas Gregor65fedaf2008-11-14 16:09:21 +00002906 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
2907 SourceLocation());
2908 UsualUnaryConversions(FnExpr);
2909
2910 Expr *Args[2] = { lhs, rhs };
2911 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregor70d26122008-11-12 17:17:38 +00002912 } else {
2913 // We matched a built-in operator. Convert the arguments, then
2914 // break out so that we will build the appropriate built-in
2915 // operator node.
2916 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
2917 "passing") ||
2918 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
2919 "passing"))
2920 return true;
2921
2922 break;
2923 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00002924 }
2925
2926 case OR_No_Viable_Function:
2927 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00002928 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002929 break;
2930
2931 case OR_Ambiguous:
2932 Diag(TokLoc,
2933 diag::err_ovl_ambiguous_oper,
2934 BinaryOperator::getOpcodeStr(Opc),
2935 lhs->getSourceRange(), rhs->getSourceRange());
2936 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2937 return true;
2938 }
2939
Douglas Gregor70d26122008-11-12 17:17:38 +00002940 // Either we found no viable overloaded operator or we matched a
2941 // built-in operator. In either case, fall through to trying to
2942 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002943 }
2944
Chris Lattner4b009652007-07-25 00:24:17 +00002945
Douglas Gregord7f915e2008-11-06 23:29:22 +00002946 // Build a built-in binary operation.
2947 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00002948}
2949
2950// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002951Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002952 ExprTy *input) {
2953 Expr *Input = (Expr*)input;
2954 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2955 QualType resultType;
2956 switch (Opc) {
2957 default:
2958 assert(0 && "Unimplemented unary expr!");
2959 case UnaryOperator::PreInc:
2960 case UnaryOperator::PreDec:
2961 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2962 break;
2963 case UnaryOperator::AddrOf:
2964 resultType = CheckAddressOfOperand(Input, OpLoc);
2965 break;
2966 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002967 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002968 resultType = CheckIndirectionOperand(Input, OpLoc);
2969 break;
2970 case UnaryOperator::Plus:
2971 case UnaryOperator::Minus:
2972 UsualUnaryConversions(Input);
2973 resultType = Input->getType();
2974 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2975 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2976 resultType.getAsString());
2977 break;
2978 case UnaryOperator::Not: // bitwise complement
2979 UsualUnaryConversions(Input);
2980 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002981 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2982 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2983 // C99 does not support '~' for complex conjugation.
2984 Diag(OpLoc, diag::ext_integer_complement_complex,
2985 resultType.getAsString(), Input->getSourceRange());
2986 else if (!resultType->isIntegerType())
2987 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2988 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002989 break;
2990 case UnaryOperator::LNot: // logical negation
2991 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2992 DefaultFunctionArrayConversion(Input);
2993 resultType = Input->getType();
2994 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2995 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2996 resultType.getAsString());
2997 // LNot always has type int. C99 6.5.3.3p5.
2998 resultType = Context.IntTy;
2999 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003000 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003001 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003002 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003003 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003004 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003005 resultType = Input->getType();
3006 break;
3007 }
3008 if (resultType.isNull())
3009 return true;
3010 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3011}
3012
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003013/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3014Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003015 SourceLocation LabLoc,
3016 IdentifierInfo *LabelII) {
3017 // Look up the record for this label identifier.
3018 LabelStmt *&LabelDecl = LabelMap[LabelII];
3019
Daniel Dunbar879788d2008-08-04 16:51:22 +00003020 // If we haven't seen this label yet, create a forward reference. It
3021 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003022 if (LabelDecl == 0)
3023 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3024
3025 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003026 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3027 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003028}
3029
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003030Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003031 SourceLocation RPLoc) { // "({..})"
3032 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3033 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3034 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3035
3036 // FIXME: there are a variety of strange constraints to enforce here, for
3037 // example, it is not possible to goto into a stmt expression apparently.
3038 // More semantic analysis is needed.
3039
3040 // FIXME: the last statement in the compount stmt has its value used. We
3041 // should not warn about it being unused.
3042
3043 // If there are sub stmts in the compound stmt, take the type of the last one
3044 // as the type of the stmtexpr.
3045 QualType Ty = Context.VoidTy;
3046
Chris Lattner200964f2008-07-26 19:51:01 +00003047 if (!Compound->body_empty()) {
3048 Stmt *LastStmt = Compound->body_back();
3049 // If LastStmt is a label, skip down through into the body.
3050 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3051 LastStmt = Label->getSubStmt();
3052
3053 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003054 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003055 }
Chris Lattner4b009652007-07-25 00:24:17 +00003056
3057 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3058}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003059
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003060Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003061 SourceLocation TypeLoc,
3062 TypeTy *argty,
3063 OffsetOfComponent *CompPtr,
3064 unsigned NumComponents,
3065 SourceLocation RPLoc) {
3066 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3067 assert(!ArgTy.isNull() && "Missing type argument!");
3068
3069 // We must have at least one component that refers to the type, and the first
3070 // one is known to be a field designator. Verify that the ArgTy represents
3071 // a struct/union/class.
3072 if (!ArgTy->isRecordType())
3073 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
3074
3075 // Otherwise, create a compound literal expression as the base, and
3076 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003077 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003078
Chris Lattnerb37522e2007-08-31 21:49:13 +00003079 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3080 // GCC extension, diagnose them.
3081 if (NumComponents != 1)
3082 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
3083 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
3084
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003085 for (unsigned i = 0; i != NumComponents; ++i) {
3086 const OffsetOfComponent &OC = CompPtr[i];
3087 if (OC.isBrackets) {
3088 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003089 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003090 if (!AT) {
3091 delete Res;
3092 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
3093 Res->getType().getAsString());
3094 }
3095
Chris Lattner2af6a802007-08-30 17:59:59 +00003096 // FIXME: C++: Verify that operator[] isn't overloaded.
3097
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003098 // C99 6.5.2.1p1
3099 Expr *Idx = static_cast<Expr*>(OC.U.E);
3100 if (!Idx->getType()->isIntegerType())
3101 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
3102 Idx->getSourceRange());
3103
3104 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3105 continue;
3106 }
3107
3108 const RecordType *RC = Res->getType()->getAsRecordType();
3109 if (!RC) {
3110 delete Res;
3111 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
3112 Res->getType().getAsString());
3113 }
3114
3115 // Get the decl corresponding to this.
3116 RecordDecl *RD = RC->getDecl();
3117 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
3118 if (!MemberDecl)
3119 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
3120 OC.U.IdentInfo->getName(),
3121 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00003122
3123 // FIXME: C++: Verify that MemberDecl isn't a static field.
3124 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003125 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3126 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003127 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3128 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003129 }
3130
3131 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3132 BuiltinLoc);
3133}
3134
3135
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003136Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003137 TypeTy *arg1, TypeTy *arg2,
3138 SourceLocation RPLoc) {
3139 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3140 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3141
3142 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3143
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003144 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003145}
3146
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003147Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003148 ExprTy *expr1, ExprTy *expr2,
3149 SourceLocation RPLoc) {
3150 Expr *CondExpr = static_cast<Expr*>(cond);
3151 Expr *LHSExpr = static_cast<Expr*>(expr1);
3152 Expr *RHSExpr = static_cast<Expr*>(expr2);
3153
3154 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3155
3156 // The conditional expression is required to be a constant expression.
3157 llvm::APSInt condEval(32);
3158 SourceLocation ExpLoc;
3159 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
3160 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
3161 CondExpr->getSourceRange());
3162
3163 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3164 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3165 RHSExpr->getType();
3166 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3167}
3168
Steve Naroff52a81c02008-09-03 18:15:37 +00003169//===----------------------------------------------------------------------===//
3170// Clang Extensions.
3171//===----------------------------------------------------------------------===//
3172
3173/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003174void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003175 // Analyze block parameters.
3176 BlockSemaInfo *BSI = new BlockSemaInfo();
3177
3178 // Add BSI to CurBlock.
3179 BSI->PrevBlockInfo = CurBlock;
3180 CurBlock = BSI;
3181
3182 BSI->ReturnType = 0;
3183 BSI->TheScope = BlockScope;
3184
Steve Naroff52059382008-10-10 01:28:17 +00003185 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
3186 PushDeclContext(BSI->TheDecl);
3187}
3188
3189void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003190 // Analyze arguments to block.
3191 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3192 "Not a function declarator!");
3193 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3194
Steve Naroff52059382008-10-10 01:28:17 +00003195 CurBlock->hasPrototype = FTI.hasPrototype;
3196 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003197
3198 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3199 // no arguments, not a function that takes a single void argument.
3200 if (FTI.hasPrototype &&
3201 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3202 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3203 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3204 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003205 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003206 } else if (FTI.hasPrototype) {
3207 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003208 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3209 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003210 }
Steve Naroff52059382008-10-10 01:28:17 +00003211 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3212
3213 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3214 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3215 // If this has an identifier, add it to the scope stack.
3216 if ((*AI)->getIdentifier())
3217 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003218}
3219
3220/// ActOnBlockError - If there is an error parsing a block, this callback
3221/// is invoked to pop the information about the block from the action impl.
3222void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3223 // Ensure that CurBlock is deleted.
3224 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3225
3226 // Pop off CurBlock, handle nested blocks.
3227 CurBlock = CurBlock->PrevBlockInfo;
3228
3229 // FIXME: Delete the ParmVarDecl objects as well???
3230
3231}
3232
3233/// ActOnBlockStmtExpr - This is called when the body of a block statement
3234/// literal was successfully completed. ^(int x){...}
3235Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3236 Scope *CurScope) {
3237 // Ensure that CurBlock is deleted.
3238 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3239 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3240
Steve Naroff52059382008-10-10 01:28:17 +00003241 PopDeclContext();
3242
Steve Naroff52a81c02008-09-03 18:15:37 +00003243 // Pop off CurBlock, handle nested blocks.
3244 CurBlock = CurBlock->PrevBlockInfo;
3245
3246 QualType RetTy = Context.VoidTy;
3247 if (BSI->ReturnType)
3248 RetTy = QualType(BSI->ReturnType, 0);
3249
3250 llvm::SmallVector<QualType, 8> ArgTypes;
3251 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3252 ArgTypes.push_back(BSI->Params[i]->getType());
3253
3254 QualType BlockTy;
3255 if (!BSI->hasPrototype)
3256 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3257 else
3258 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003259 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003260
3261 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003262
Steve Naroff95029d92008-10-08 18:44:00 +00003263 BSI->TheDecl->setBody(Body.take());
3264 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003265}
3266
Nate Begemanbd881ef2008-01-30 20:50:20 +00003267/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003268/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003269/// The number of arguments has already been validated to match the number of
3270/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003271static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3272 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003273 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003274 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003275 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3276 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003277
3278 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003279 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003280 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003281 return true;
3282}
3283
3284Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3285 SourceLocation *CommaLocs,
3286 SourceLocation BuiltinLoc,
3287 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003288 // __builtin_overload requires at least 2 arguments
3289 if (NumArgs < 2)
3290 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3291 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003292
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003293 // The first argument is required to be a constant expression. It tells us
3294 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003295 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003296 Expr *NParamsExpr = Args[0];
3297 llvm::APSInt constEval(32);
3298 SourceLocation ExpLoc;
3299 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
3300 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3301 NParamsExpr->getSourceRange());
3302
3303 // Verify that the number of parameters is > 0
3304 unsigned NumParams = constEval.getZExtValue();
3305 if (NumParams == 0)
3306 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3307 NParamsExpr->getSourceRange());
3308 // Verify that we have at least 1 + NumParams arguments to the builtin.
3309 if ((NumParams + 1) > NumArgs)
3310 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3311 SourceRange(BuiltinLoc, RParenLoc));
3312
3313 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003314 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003315 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003316 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3317 // UsualUnaryConversions will convert the function DeclRefExpr into a
3318 // pointer to function.
3319 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003320 const FunctionTypeProto *FnType = 0;
3321 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3322 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003323
3324 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3325 // parameters, and the number of parameters must match the value passed to
3326 // the builtin.
3327 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00003328 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
3329 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003330
3331 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003332 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003333 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003334 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003335 if (OE)
3336 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
3337 OE->getFn()->getSourceRange());
3338 // Remember our match, and continue processing the remaining arguments
3339 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003340 OE = new OverloadExpr(Args, NumArgs, i,
3341 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003342 BuiltinLoc, RParenLoc);
3343 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003344 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003345 // Return the newly created OverloadExpr node, if we succeded in matching
3346 // exactly one of the candidate functions.
3347 if (OE)
3348 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003349
3350 // If we didn't find a matching function Expr in the __builtin_overload list
3351 // the return an error.
3352 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003353 for (unsigned i = 0; i != NumParams; ++i) {
3354 if (i != 0) typeNames += ", ";
3355 typeNames += Args[i+1]->getType().getAsString();
3356 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003357
3358 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3359 SourceRange(BuiltinLoc, RParenLoc));
3360}
3361
Anders Carlsson36760332007-10-15 20:28:48 +00003362Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3363 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003364 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003365 Expr *E = static_cast<Expr*>(expr);
3366 QualType T = QualType::getFromOpaquePtr(type);
3367
3368 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003369
3370 // Get the va_list type
3371 QualType VaListType = Context.getBuiltinVaListType();
3372 // Deal with implicit array decay; for example, on x86-64,
3373 // va_list is an array, but it's supposed to decay to
3374 // a pointer for va_arg.
3375 if (VaListType->isArrayType())
3376 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003377 // Make sure the input expression also decays appropriately.
3378 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003379
3380 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003381 return Diag(E->getLocStart(),
3382 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3383 E->getType().getAsString(),
3384 E->getSourceRange());
3385
3386 // FIXME: Warn if a non-POD type is passed in.
3387
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003388 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003389}
3390
Chris Lattner005ed752008-01-04 18:04:52 +00003391bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3392 SourceLocation Loc,
3393 QualType DstType, QualType SrcType,
3394 Expr *SrcExpr, const char *Flavor) {
3395 // Decode the result (notice that AST's are still created for extensions).
3396 bool isInvalid = false;
3397 unsigned DiagKind;
3398 switch (ConvTy) {
3399 default: assert(0 && "Unknown conversion type");
3400 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003401 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003402 DiagKind = diag::ext_typecheck_convert_pointer_int;
3403 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003404 case IntToPointer:
3405 DiagKind = diag::ext_typecheck_convert_int_pointer;
3406 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003407 case IncompatiblePointer:
3408 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3409 break;
3410 case FunctionVoidPointer:
3411 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3412 break;
3413 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003414 // If the qualifiers lost were because we were applying the
3415 // (deprecated) C++ conversion from a string literal to a char*
3416 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3417 // Ideally, this check would be performed in
3418 // CheckPointerTypesForAssignment. However, that would require a
3419 // bit of refactoring (so that the second argument is an
3420 // expression, rather than a type), which should be done as part
3421 // of a larger effort to fix CheckPointerTypesForAssignment for
3422 // C++ semantics.
3423 if (getLangOptions().CPlusPlus &&
3424 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3425 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003426 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3427 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003428 case IntToBlockPointer:
3429 DiagKind = diag::err_int_to_block_pointer;
3430 break;
3431 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003432 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003433 break;
3434 case BlockVoidPointer:
3435 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3436 break;
Steve Naroff19608432008-10-14 22:18:38 +00003437 case IncompatibleObjCQualifiedId:
3438 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3439 // it can give a more specific diagnostic.
3440 DiagKind = diag::warn_incompatible_qualified_id;
3441 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003442 case Incompatible:
3443 DiagKind = diag::err_typecheck_convert_incompatible;
3444 isInvalid = true;
3445 break;
3446 }
3447
3448 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3449 SrcExpr->getSourceRange());
3450 return isInvalid;
3451}