blob: 21bf990fba1773febcd65f15402b3eb3d6e40ffa [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.
133 if (lhs->isPromotableIntegerType())
134 lhs = Context.IntTy;
135 else
136 lhs = Context.getCanonicalType(lhs).getUnqualifiedType();
137
138 if (rhs->isPromotableIntegerType())
139 rhs = Context.IntTy;
140 else
141 rhs = Context.getCanonicalType(rhs).getUnqualifiedType();
142
Chris Lattner299b8842008-07-25 21:10:04 +0000143 // If both types are identical, no conversion is needed.
144 if (lhs == rhs)
145 return lhs;
146
147 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
148 // The caller can deal with this (e.g. pointer + int).
149 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
150 return lhs;
151
152 // At this point, we have two different arithmetic types.
153
154 // Handle complex types first (C99 6.3.1.8p1).
155 if (lhs->isComplexType() || rhs->isComplexType()) {
156 // if we have an integer operand, the result is the complex type.
157 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
158 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000159 return lhs;
160 }
161 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
162 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000163 return rhs;
164 }
165 // This handles complex/complex, complex/float, or float/complex.
166 // When both operands are complex, the shorter operand is converted to the
167 // type of the longer, and that is the type of the result. This corresponds
168 // to what is done when combining two real floating-point operands.
169 // The fun begins when size promotion occur across type domains.
170 // From H&S 6.3.4: When one operand is complex and the other is a real
171 // floating-point type, the less precise type is converted, within it's
172 // real or complex domain, to the precision of the other type. For example,
173 // when combining a "long double" with a "double _Complex", the
174 // "double _Complex" is promoted to "long double _Complex".
175 int result = Context.getFloatingTypeOrder(lhs, rhs);
176
177 if (result > 0) { // The left side is bigger, convert rhs.
178 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000179 } else if (result < 0) { // The right side is bigger, convert lhs.
180 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000181 }
182 // At this point, lhs and rhs have the same rank/size. Now, make sure the
183 // domains match. This is a requirement for our implementation, C99
184 // does not require this promotion.
185 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
186 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000187 return rhs;
188 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000189 return lhs;
190 }
191 }
192 return lhs; // The domain/size match exactly.
193 }
194 // Now handle "real" floating types (i.e. float, double, long double).
195 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
196 // if we have an integer operand, the result is the real floating type.
197 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
198 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000199 return lhs;
200 }
201 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
202 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000203 return rhs;
204 }
205 // We have two real floating types, float/complex combos were handled above.
206 // Convert the smaller operand to the bigger result.
207 int result = Context.getFloatingTypeOrder(lhs, rhs);
208
209 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000210 return lhs;
211 }
212 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000213 return rhs;
214 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000215 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000216 }
217 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
218 // Handle GCC complex int extension.
219 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
220 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
221
222 if (lhsComplexInt && rhsComplexInt) {
223 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
224 rhsComplexInt->getElementType()) >= 0) {
225 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000226 return lhs;
227 }
Chris Lattner299b8842008-07-25 21:10:04 +0000228 return rhs;
229 } else if (lhsComplexInt && rhs->isIntegerType()) {
230 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000231 return lhs;
232 } else if (rhsComplexInt && lhs->isIntegerType()) {
233 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000234 return rhs;
235 }
236 }
237 // Finally, we have two differing integer types.
238 // The rules for this case are in C99 6.3.1.8
239 int compare = Context.getIntegerTypeOrder(lhs, rhs);
240 bool lhsSigned = lhs->isSignedIntegerType(),
241 rhsSigned = rhs->isSignedIntegerType();
242 QualType destType;
243 if (lhsSigned == rhsSigned) {
244 // Same signedness; use the higher-ranked type
245 destType = compare >= 0 ? lhs : rhs;
246 } else if (compare != (lhsSigned ? 1 : -1)) {
247 // The unsigned type has greater than or equal rank to the
248 // signed type, so use the unsigned type
249 destType = lhsSigned ? rhs : lhs;
250 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
251 // The two types are different widths; if we are here, that
252 // means the signed type is larger than the unsigned type, so
253 // use the signed type.
254 destType = lhsSigned ? lhs : rhs;
255 } else {
256 // The signed type is higher-ranked than the unsigned type,
257 // but isn't actually any bigger (like unsigned int and long
258 // on most 32-bit systems). Use the unsigned type corresponding
259 // to the signed type.
260 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
261 }
Chris Lattner299b8842008-07-25 21:10:04 +0000262 return destType;
263}
264
265//===----------------------------------------------------------------------===//
266// Semantic Analysis for various Expression Types
267//===----------------------------------------------------------------------===//
268
269
Steve Naroff87d58b42007-09-16 03:34:24 +0000270/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000271/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
272/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
273/// multiple tokens. However, the common case is that StringToks points to one
274/// string.
275///
276Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000277Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000278 assert(NumStringToks && "Must have at least one string!");
279
280 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
281 if (Literal.hadError)
282 return ExprResult(true);
283
284 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
285 for (unsigned i = 0; i != NumStringToks; ++i)
286 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000287
288 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000289 if (Literal.Pascal && Literal.GetStringLength() > 256)
290 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
291 SourceRange(StringToks[0].getLocation(),
292 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000293
Chris Lattnera6dcce32008-02-11 00:02:17 +0000294 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000295 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000296 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000297
298 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
299 if (getLangOptions().CPlusPlus)
300 StrTy.addConst();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000301
302 // Get an array type for the string, according to C99 6.4.5. This includes
303 // the nul terminator character as well as the string length for pascal
304 // strings.
305 StrTy = Context.getConstantArrayType(StrTy,
306 llvm::APInt(32, Literal.GetStringLength()+1),
307 ArrayType::Normal, 0);
308
Chris Lattner4b009652007-07-25 00:24:17 +0000309 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
310 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000311 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000312 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000313 StringToks[NumStringToks-1].getLocation());
314}
315
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000316/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
317/// CurBlock to VD should cause it to be snapshotted (as we do for auto
318/// variables defined outside the block) or false if this is not needed (e.g.
319/// for values inside the block or for globals).
320///
321/// FIXME: This will create BlockDeclRefExprs for global variables,
322/// function references, etc which is suboptimal :) and breaks
323/// things like "integer constant expression" tests.
324static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
325 ValueDecl *VD) {
326 // If the value is defined inside the block, we couldn't snapshot it even if
327 // we wanted to.
328 if (CurBlock->TheDecl == VD->getDeclContext())
329 return false;
330
331 // If this is an enum constant or function, it is constant, don't snapshot.
332 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
333 return false;
334
335 // If this is a reference to an extern, static, or global variable, no need to
336 // snapshot it.
337 // FIXME: What about 'const' variables in C++?
338 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
339 return Var->hasLocalStorage();
340
341 return true;
342}
343
344
345
Steve Naroff0acc9c92007-09-15 18:49:24 +0000346/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000347/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000348/// identifier is used in a function call context.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000349/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the
350/// class or namespace that the identifier must be a member of.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000351Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000352 IdentifierInfo &II,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000353 bool HasTrailingLParen,
354 const CXXScopeSpec *SS) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000355 // Could be enum-constant, value decl, instance variable, etc.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000356 Decl *D;
357 if (SS && !SS->isEmpty()) {
358 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
359 if (DC == 0)
360 return true;
361 D = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC);
362 } else
363 D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000364
365 // If this reference is in an Objective-C method, then ivar lookup happens as
366 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000367 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000368 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000369 // There are two cases to handle here. 1) scoped lookup could have failed,
370 // in which case we should look for an ivar. 2) scoped lookup could have
371 // found a decl, but that decl is outside the current method (i.e. a global
372 // variable). In these two cases, we do a lookup for an ivar with this
373 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000374 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000375 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattnered94f762008-07-21 04:44:44 +0000376 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000377 // FIXME: This should use a new expr for a direct reference, don't turn
378 // this into Self->ivar, just return a BareIVarExpr or something.
379 IdentifierInfo &II = Context.Idents.get("self");
380 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
381 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
382 static_cast<Expr*>(SelfExpr.Val), true, true);
383 }
384 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000385 // Needed to implement property "super.method" notation.
Daniel Dunbar4837ae72008-08-14 22:04:54 +0000386 if (SD == 0 && &II == SuperID) {
Steve Naroff6f786252008-06-02 23:03:37 +0000387 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000388 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000389 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000390 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000391 }
Chris Lattner4b009652007-07-25 00:24:17 +0000392 if (D == 0) {
393 // Otherwise, this could be an implicitly declared function reference (legal
394 // in C90, extension in C99).
395 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000396 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000397 D = ImplicitlyDefineFunction(Loc, II, S);
398 else {
399 // If this name wasn't predeclared and if this is not a function call,
400 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000401 if (SS && !SS->isEmpty())
402 return Diag(Loc, diag::err_typecheck_no_member,
403 II.getName(), SS->getRange());
404 else
405 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000406 }
407 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000408
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000409 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
410 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
411 if (MD->isStatic())
412 // "invalid use of member 'x' in static member function"
413 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
414 FD->getName());
415 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
416 // "invalid use of nonstatic data member 'x'"
417 return Diag(Loc, diag::err_invalid_non_static_member_use,
418 FD->getName());
419
420 if (FD->isInvalidDecl())
421 return true;
422
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +0000423 // FIXME: Handle 'mutable'.
424 return new DeclRefExpr(FD,
425 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000426 }
427
428 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
429 }
Chris Lattner4b009652007-07-25 00:24:17 +0000430 if (isa<TypedefDecl>(D))
431 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000432 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000433 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000434 if (isa<NamespaceDecl>(D))
435 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000436
Steve Naroffd6163f32008-09-05 22:11:13 +0000437 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000438 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
439 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
440
Steve Naroffd6163f32008-09-05 22:11:13 +0000441 ValueDecl *VD = cast<ValueDecl>(D);
442
443 // check if referencing an identifier with __attribute__((deprecated)).
444 if (VD->getAttr<DeprecatedAttr>())
445 Diag(Loc, diag::warn_deprecated, VD->getName());
446
447 // Only create DeclRefExpr's for valid Decl's.
448 if (VD->isInvalidDecl())
449 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000450
451 // If the identifier reference is inside a block, and it refers to a value
452 // that is outside the block, create a BlockDeclRefExpr instead of a
453 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
454 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000455 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000456 // We do not do this for things like enum constants, global variables, etc,
457 // as they do not get snapshotted.
458 //
459 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000460 // The BlocksAttr indicates the variable is bound by-reference.
461 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000462 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
463 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000464
465 // Variable will be bound by-copy, make it const within the closure.
466 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000467 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
468 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000469 }
470 // If this reference is not in a block or if the referenced variable is
471 // within the block, create a normal DeclRefExpr.
Douglas Gregor3fb675a2008-10-22 04:14:44 +0000472 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Chris Lattner4b009652007-07-25 00:24:17 +0000473}
474
Chris Lattner69909292008-08-10 01:53:14 +0000475Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000476 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000477 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000478
479 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000480 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000481 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
482 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
483 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000484 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000485
486 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000487 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000488 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000489
Chris Lattner7e637512008-01-12 08:14:25 +0000490 // Pre-defined identifiers are of type char[x], where x is the length of the
491 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000492 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000493 if (getCurFunctionDecl())
494 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000495 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000496 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000497
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000498 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000499 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000500 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000501 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000502}
503
Steve Naroff87d58b42007-09-16 03:34:24 +0000504Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000505 llvm::SmallString<16> CharBuffer;
506 CharBuffer.resize(Tok.getLength());
507 const char *ThisTokBegin = &CharBuffer[0];
508 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
509
510 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
511 Tok.getLocation(), PP);
512 if (Literal.hadError())
513 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000514
515 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
516
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000517 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
518 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000519}
520
Steve Naroff87d58b42007-09-16 03:34:24 +0000521Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000522 // fast path for a single digit (which is quite common). A single digit
523 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
524 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000525 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000526
Chris Lattner8cd0e932008-03-05 18:54:05 +0000527 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000528 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000529 Context.IntTy,
530 Tok.getLocation()));
531 }
532 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000533 // Add padding so that NumericLiteralParser can overread by one character.
534 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000535 const char *ThisTokBegin = &IntegerBuffer[0];
536
537 // Get the spelling of the token, which eliminates trigraphs, etc.
538 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000539
Chris Lattner4b009652007-07-25 00:24:17 +0000540 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
541 Tok.getLocation(), PP);
542 if (Literal.hadError)
543 return ExprResult(true);
544
Chris Lattner1de66eb2007-08-26 03:42:43 +0000545 Expr *Res;
546
547 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000548 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000549 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000550 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000551 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000552 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000553 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000554 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000555
556 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
557
Ted Kremenekddedbe22007-11-29 00:56:49 +0000558 // isExact will be set by GetFloatValue().
559 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000560 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000561 Ty, Tok.getLocation());
562
Chris Lattner1de66eb2007-08-26 03:42:43 +0000563 } else if (!Literal.isIntegerLiteral()) {
564 return ExprResult(true);
565 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000566 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000567
Neil Booth7421e9c2007-08-29 22:00:19 +0000568 // long long is a C99 feature.
569 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000570 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000571 Diag(Tok.getLocation(), diag::ext_longlong);
572
Chris Lattner4b009652007-07-25 00:24:17 +0000573 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000574 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000575
576 if (Literal.GetIntegerValue(ResultVal)) {
577 // If this value didn't fit into uintmax_t, warn and force to ull.
578 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000579 Ty = Context.UnsignedLongLongTy;
580 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000581 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000582 } else {
583 // If this value fits into a ULL, try to figure out what else it fits into
584 // according to the rules of C99 6.4.4.1p5.
585
586 // Octal, Hexadecimal, and integers with a U suffix are allowed to
587 // be an unsigned int.
588 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
589
590 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000591 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000592 if (!Literal.isLong && !Literal.isLongLong) {
593 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000594 unsigned IntSize = Context.Target.getIntWidth();
595
Chris Lattner4b009652007-07-25 00:24:17 +0000596 // Does it fit in a unsigned int?
597 if (ResultVal.isIntN(IntSize)) {
598 // Does it fit in a signed int?
599 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000600 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000601 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000602 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000603 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000604 }
Chris Lattner4b009652007-07-25 00:24:17 +0000605 }
606
607 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000608 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000609 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000610
611 // Does it fit in a unsigned long?
612 if (ResultVal.isIntN(LongSize)) {
613 // Does it fit in a signed long?
614 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000615 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000616 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000617 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000618 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000619 }
Chris Lattner4b009652007-07-25 00:24:17 +0000620 }
621
622 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000623 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000624 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000625
626 // Does it fit in a unsigned long long?
627 if (ResultVal.isIntN(LongLongSize)) {
628 // Does it fit in a signed long long?
629 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000630 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000631 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000632 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000633 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000634 }
635 }
636
637 // If we still couldn't decide a type, we probably have something that
638 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000639 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000640 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000641 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000642 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000643 }
Chris Lattnere4068872008-05-09 05:59:00 +0000644
645 if (ResultVal.getBitWidth() != Width)
646 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000647 }
648
Chris Lattner48d7f382008-04-02 04:24:33 +0000649 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000650 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000651
652 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
653 if (Literal.isImaginary)
654 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
655
656 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000657}
658
Steve Naroff87d58b42007-09-16 03:34:24 +0000659Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000660 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000661 Expr *E = (Expr *)Val;
662 assert((E != 0) && "ActOnParenExpr() missing expr");
663 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000664}
665
666/// The UsualUnaryConversions() function is *not* called by this routine.
667/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000668bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
669 SourceLocation OpLoc,
670 const SourceRange &ExprRange,
671 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000672 // C99 6.5.3.4p1:
673 if (isa<FunctionType>(exprType) && isSizeof)
674 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000675 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000676 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000677 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
678 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000679 else if (exprType->isIncompleteType()) {
680 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
681 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000682 exprType.getAsString(), ExprRange);
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000683 return true; // error
Chris Lattner4b009652007-07-25 00:24:17 +0000684 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000685
686 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000687}
688
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000689/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
690/// the same for @c alignof and @c __alignof
691/// Note that the ArgRange is invalid if isType is false.
692Action::ExprResult
693Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
694 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +0000695 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000696 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000697
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000698 QualType ArgTy;
699 SourceRange Range;
700 if (isType) {
701 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
702 Range = ArgRange;
703 } else {
704 // Get the end location.
705 Expr *ArgEx = (Expr *)TyOrEx;
706 Range = ArgEx->getSourceRange();
707 ArgTy = ArgEx->getType();
708 }
709
710 // Verify that the operand is valid.
711 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +0000712 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000713
714 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
715 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
716 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +0000717}
718
Chris Lattner5110ad52007-08-24 21:41:10 +0000719QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000720 DefaultFunctionArrayConversion(V);
721
Chris Lattnera16e42d2007-08-26 05:39:26 +0000722 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000723 if (const ComplexType *CT = V->getType()->getAsComplexType())
724 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000725
726 // Otherwise they pass through real integer and floating point types here.
727 if (V->getType()->isArithmeticType())
728 return V->getType();
729
730 // Reject anything else.
731 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
732 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000733}
734
735
Chris Lattner4b009652007-07-25 00:24:17 +0000736
Steve Naroff87d58b42007-09-16 03:34:24 +0000737Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000738 tok::TokenKind Kind,
739 ExprTy *Input) {
740 UnaryOperator::Opcode Opc;
741 switch (Kind) {
742 default: assert(0 && "Unknown unary op!");
743 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
744 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
745 }
746 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
747 if (result.isNull())
748 return true;
749 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
750}
751
752Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000753ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000754 ExprTy *Idx, SourceLocation RLoc) {
755 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
756
757 // Perform default conversions.
758 DefaultFunctionArrayConversion(LHSExp);
759 DefaultFunctionArrayConversion(RHSExp);
760
761 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
762
763 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000764 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000765 // in the subscript position. As a result, we need to derive the array base
766 // and index from the expression types.
767 Expr *BaseExpr, *IndexExpr;
768 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000769 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000770 BaseExpr = LHSExp;
771 IndexExpr = RHSExp;
772 // FIXME: need to deal with const...
773 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000774 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000775 // Handle the uncommon case of "123[Ptr]".
776 BaseExpr = RHSExp;
777 IndexExpr = LHSExp;
778 // FIXME: need to deal with const...
779 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000780 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
781 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000782 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000783
784 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000785 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
786 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000787 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000788 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000789 // FIXME: need to deal with const...
790 ResultType = VTy->getElementType();
791 } else {
792 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
793 RHSExp->getSourceRange());
794 }
795 // C99 6.5.2.1p1
796 if (!IndexExpr->getType()->isIntegerType())
797 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
798 IndexExpr->getSourceRange());
799
800 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
801 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000802 // void (*)(int)) and pointers to incomplete types. Functions are not
803 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000804 if (!ResultType->isObjectType())
805 return Diag(BaseExpr->getLocStart(),
806 diag::err_typecheck_subscript_not_object,
807 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
808
809 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
810}
811
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000812QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000813CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000814 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000815 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000816
817 // This flag determines whether or not the component is to be treated as a
818 // special name, or a regular GLSL-style component access.
819 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000820
821 // The vector accessor can't exceed the number of elements.
822 const char *compStr = CompName.getName();
823 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000824 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000825 baseType.getAsString(), SourceRange(CompLoc));
826 return QualType();
827 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000828
829 // Check that we've found one of the special components, or that the component
830 // names must come from the same set.
831 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
832 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
833 SpecialComponent = true;
834 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000835 do
836 compStr++;
837 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
838 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
839 do
840 compStr++;
841 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
842 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
843 do
844 compStr++;
845 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
846 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000847
Nate Begemanc8e51f82008-05-09 06:41:27 +0000848 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000849 // We didn't get to the end of the string. This means the component names
850 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000851 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000852 std::string(compStr,compStr+1), SourceRange(CompLoc));
853 return QualType();
854 }
855 // Each component accessor can't exceed the vector type.
856 compStr = CompName.getName();
857 while (*compStr) {
858 if (vecType->isAccessorWithinNumElements(*compStr))
859 compStr++;
860 else
861 break;
862 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000863 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000864 // We didn't get to the end of the string. This means a component accessor
865 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000866 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000867 baseType.getAsString(), SourceRange(CompLoc));
868 return QualType();
869 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000870
871 // If we have a special component name, verify that the current vector length
872 // is an even number, since all special component names return exactly half
873 // the elements.
874 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Daniel Dunbar45a91802008-09-30 17:22:47 +0000875 Diag(OpLoc, diag::err_ext_vector_component_requires_even,
876 baseType.getAsString(), SourceRange(CompLoc));
Nate Begemanc8e51f82008-05-09 06:41:27 +0000877 return QualType();
878 }
879
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000880 // The component accessor looks fine - now we need to compute the actual type.
881 // The vector type is implied by the component accessor. For example,
882 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000883 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
884 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
885 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000886 if (CompSize == 1)
887 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000888
Nate Begemanaf6ed502008-04-18 23:10:10 +0000889 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000890 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000891 // diagostics look bad. We want extended vector types to appear built-in.
892 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
893 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
894 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000895 }
896 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000897}
898
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000899/// constructSetterName - Return the setter name for the given
900/// identifier, i.e. "set" + Name where the initial character of Name
901/// has been capitalized.
902// FIXME: Merge with same routine in Parser. But where should this
903// live?
904static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
905 const IdentifierInfo *Name) {
906 unsigned N = Name->getLength();
907 char *SelectorName = new char[3 + N];
908 memcpy(SelectorName, "set", 3);
909 memcpy(&SelectorName[3], Name->getName(), N);
910 SelectorName[3] = toupper(SelectorName[3]);
911
912 IdentifierInfo *Setter =
913 &Idents.get(SelectorName, &SelectorName[3 + N]);
914 delete[] SelectorName;
915 return Setter;
916}
917
Chris Lattner4b009652007-07-25 00:24:17 +0000918Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000919ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000920 tok::TokenKind OpKind, SourceLocation MemberLoc,
921 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000922 Expr *BaseExpr = static_cast<Expr *>(Base);
923 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000924
925 // Perform default conversions.
926 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000927
Steve Naroff2cb66382007-07-26 03:11:44 +0000928 QualType BaseType = BaseExpr->getType();
929 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000930
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000931 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
932 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000933 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000934 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000935 BaseType = PT->getPointeeType();
936 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000937 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
938 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000939 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000940
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000941 // Handle field access to simple records. This also handles access to fields
942 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000943 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000944 RecordDecl *RDecl = RTy->getDecl();
945 if (RTy->isIncompleteType())
946 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
947 BaseExpr->getSourceRange());
948 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000949 FieldDecl *MemberDecl = RDecl->getMember(&Member);
950 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000951 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
952 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000953
954 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000955 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000956 QualType MemberType = MemberDecl->getType();
957 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000958 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000959 MemberType = MemberType.getQualifiedType(combinedQualifiers);
960
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000961 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000962 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000963 }
964
Chris Lattnere9d71612008-07-21 04:59:05 +0000965 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
966 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000967 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
968 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000969 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000970 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000971 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000972 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000973 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000974 }
975
Chris Lattnere9d71612008-07-21 04:59:05 +0000976 // Handle Objective-C property access, which is "Obj.property" where Obj is a
977 // pointer to a (potentially qualified) interface type.
978 const PointerType *PTy;
979 const ObjCInterfaceType *IFTy;
980 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
981 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
982 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +0000983
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000984 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +0000985 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
986 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
987
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000988 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000989 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
990 E = IFTy->qual_end(); I != E; ++I)
991 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
992 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000993
994 // If that failed, look for an "implicit" property by seeing if the nullary
995 // selector is implemented.
996
997 // FIXME: The logic for looking up nullary and unary selectors should be
998 // shared with the code in ActOnInstanceMessage.
999
1000 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1001 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1002
1003 // If this reference is in an @implementation, check for 'private' methods.
1004 if (!Getter)
1005 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1006 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1007 if (ObjCImplementationDecl *ImpDecl =
1008 ObjCImplementations[ClassDecl->getIdentifier()])
1009 Getter = ImpDecl->getInstanceMethod(Sel);
1010
Steve Naroff04151f32008-10-22 19:16:27 +00001011 // Look through local category implementations associated with the class.
1012 if (!Getter) {
1013 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1014 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1015 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1016 }
1017 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001018 if (Getter) {
1019 // If we found a getter then this may be a valid dot-reference, we
1020 // need to also look for the matching setter.
1021 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1022 &Member);
1023 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1024 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1025
1026 if (!Setter) {
1027 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1028 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1029 if (ObjCImplementationDecl *ImpDecl =
1030 ObjCImplementations[ClassDecl->getIdentifier()])
1031 Setter = ImpDecl->getInstanceMethod(SetterSel);
1032 }
1033
1034 // FIXME: There are some issues here. First, we are not
1035 // diagnosing accesses to read-only properties because we do not
1036 // know if this is a getter or setter yet. Second, we are
1037 // checking that the type of the setter matches the type we
1038 // expect.
1039 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1040 MemberLoc, BaseExpr);
1041 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001042 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001043 // Handle properties on qualified "id" protocols.
1044 const ObjCQualifiedIdType *QIdTy;
1045 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1046 // Check protocols on qualified interfaces.
1047 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1048 E = QIdTy->qual_end(); I != E; ++I)
1049 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1050 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1051 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001052 // Handle 'field access' to vectors, such as 'V.xx'.
1053 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1054 // Component access limited to variables (reject vec4.rg.g).
1055 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1056 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +00001057 return Diag(MemberLoc, diag::err_ext_vector_component_access,
1058 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001059 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1060 if (ret.isNull())
1061 return true;
1062 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1063 }
1064
Chris Lattner7d5a8762008-07-21 05:35:34 +00001065 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1066 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001067}
1068
Steve Naroff87d58b42007-09-16 03:34:24 +00001069/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001070/// This provides the location of the left/right parens and a list of comma
1071/// locations.
1072Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001073ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001074 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001075 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1076 Expr *Fn = static_cast<Expr *>(fn);
1077 Expr **Args = reinterpret_cast<Expr**>(args);
1078 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001079 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001080 OverloadedFunctionDecl *Ovl = NULL;
1081
1082 // If we're directly calling a function or a set of overloaded
1083 // functions, get the appropriate declaration.
1084 {
1085 DeclRefExpr *DRExpr = NULL;
1086 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1087 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1088 else
1089 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1090
1091 if (DRExpr) {
1092 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1093 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1094 }
1095 }
1096
1097 // If we have a set of overloaded functions, perform overload
1098 // resolution to pick the function.
1099 if (Ovl) {
1100 OverloadCandidateSet CandidateSet;
1101 OverloadCandidateSet::iterator Best;
1102 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
1103 switch (BestViableFunction(CandidateSet, Best)) {
1104 case OR_Success:
1105 {
1106 // Success! Let the remainder of this function build a call to
1107 // the function selected by overload resolution.
1108 FDecl = Best->Function;
1109 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1110 Fn->getSourceRange().getBegin());
1111 delete Fn;
1112 Fn = NewFn;
1113 }
1114 break;
1115
1116 case OR_No_Viable_Function:
1117 if (CandidateSet.empty())
1118 Diag(Fn->getSourceRange().getBegin(),
1119 diag::err_ovl_no_viable_function_in_call, Ovl->getName(),
1120 Fn->getSourceRange());
1121 else {
1122 Diag(Fn->getSourceRange().getBegin(),
1123 diag::err_ovl_no_viable_function_in_call_with_cands,
1124 Ovl->getName(), Fn->getSourceRange());
1125 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1126 }
1127 return true;
1128
1129 case OR_Ambiguous:
1130 Diag(Fn->getSourceRange().getBegin(),
1131 diag::err_ovl_ambiguous_call, Ovl->getName(),
1132 Fn->getSourceRange());
1133 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1134 return true;
1135 }
1136 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001137
1138 // Promote the function operand.
1139 UsualUnaryConversions(Fn);
1140
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001141 // Make the call expr early, before semantic checks. This guarantees cleanup
1142 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001143 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001144 Context.BoolTy, RParenLoc));
Steve Naroffd6163f32008-09-05 22:11:13 +00001145 const FunctionType *FuncT;
1146 if (!Fn->getType()->isBlockPointerType()) {
1147 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1148 // have type pointer to function".
1149 const PointerType *PT = Fn->getType()->getAsPointerType();
1150 if (PT == 0)
1151 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1152 Fn->getSourceRange());
1153 FuncT = PT->getPointeeType()->getAsFunctionType();
1154 } else { // This is a block call.
1155 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1156 getAsFunctionType();
1157 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001158 if (FuncT == 0)
Chris Lattner61000b12008-08-14 04:33:24 +00001159 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1160 Fn->getSourceRange());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001161
1162 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001163 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001164
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001165 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001166 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1167 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001168 unsigned NumArgsInProto = Proto->getNumArgs();
1169 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001170
Chris Lattner3e254fb2008-04-08 04:40:51 +00001171 // If too few arguments are available (and we don't have default
1172 // arguments for the remaining parameters), don't make the call.
1173 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +00001174 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001175 // Use default arguments for missing arguments
1176 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +00001177 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001178 } else
Steve Naroffd6163f32008-09-05 22:11:13 +00001179 return Diag(RParenLoc,
1180 !Fn->getType()->isBlockPointerType()
1181 ? diag::err_typecheck_call_too_few_args
1182 : diag::err_typecheck_block_too_few_args,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001183 Fn->getSourceRange());
1184 }
1185
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001186 // If too many are passed and not variadic, error on the extras and drop
1187 // them.
1188 if (NumArgs > NumArgsInProto) {
1189 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001190 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffd6163f32008-09-05 22:11:13 +00001191 !Fn->getType()->isBlockPointerType()
1192 ? diag::err_typecheck_call_too_many_args
1193 : diag::err_typecheck_block_too_many_args,
1194 Fn->getSourceRange(),
Chris Lattner4b009652007-07-25 00:24:17 +00001195 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001196 Args[NumArgs-1]->getLocEnd()));
1197 // This deletes the extra arguments.
1198 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001199 }
1200 NumArgsToCheck = NumArgsInProto;
1201 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001202
Chris Lattner4b009652007-07-25 00:24:17 +00001203 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001204 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001205 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001206
1207 Expr *Arg;
1208 if (i < NumArgs)
1209 Arg = Args[i];
1210 else
1211 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001212 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001213
Douglas Gregor81c29152008-10-29 00:13:59 +00001214 // Pass the argument.
1215 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner005ed752008-01-04 18:04:52 +00001216 return true;
Douglas Gregor81c29152008-10-29 00:13:59 +00001217
1218 TheCall->setArg(i, Arg);
Chris Lattner4b009652007-07-25 00:24:17 +00001219 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001220
1221 // If this is a variadic call, handle args passed through "...".
1222 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001223 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001224 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1225 Expr *Arg = Args[i];
1226 DefaultArgumentPromotion(Arg);
1227 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001228 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001229 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001230 } else {
1231 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1232
Steve Naroffdb65e052007-08-28 23:30:39 +00001233 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001234 for (unsigned i = 0; i != NumArgs; i++) {
1235 Expr *Arg = Args[i];
1236 DefaultArgumentPromotion(Arg);
1237 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001238 }
Chris Lattner4b009652007-07-25 00:24:17 +00001239 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001240
Chris Lattner2e64c072007-08-10 20:18:51 +00001241 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001242 if (FDecl)
1243 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001244
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001245 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001246}
1247
1248Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001249ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001250 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001251 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001252 QualType literalType = QualType::getFromOpaquePtr(Ty);
1253 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001254 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001255 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001256
Eli Friedman8c2173d2008-05-20 05:22:08 +00001257 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001258 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001259 return Diag(LParenLoc,
1260 diag::err_variable_object_no_init,
1261 SourceRange(LParenLoc,
1262 literalExpr->getSourceRange().getEnd()));
1263 } else if (literalType->isIncompleteType()) {
1264 return Diag(LParenLoc,
1265 diag::err_typecheck_decl_incomplete_type,
1266 literalType.getAsString(),
1267 SourceRange(LParenLoc,
1268 literalExpr->getSourceRange().getEnd()));
1269 }
1270
Douglas Gregor6428e762008-11-05 15:29:30 +00001271 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
1272 "temporary"))
Steve Naroff92590f92008-01-09 20:58:06 +00001273 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001274
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001275 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001276 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001277 if (CheckForConstantInitializer(literalExpr, literalType))
1278 return true;
1279 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001280 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1281 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001282}
1283
1284Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001285ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001286 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001287 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001288 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001289
Steve Naroff0acc9c92007-09-15 18:49:24 +00001290 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001291 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001292
Chris Lattner71ca8c82008-10-26 23:43:26 +00001293 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1294 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001295 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1296 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001297}
1298
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001299/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001300bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001301 UsualUnaryConversions(castExpr);
1302
1303 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1304 // type needs to be scalar.
1305 if (castType->isVoidType()) {
1306 // Cast to void allows any expr type.
1307 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1308 // GCC struct/union extension: allow cast to self.
1309 if (Context.getCanonicalType(castType) !=
1310 Context.getCanonicalType(castExpr->getType()) ||
1311 (!castType->isStructureType() && !castType->isUnionType())) {
1312 // Reject any other conversions to non-scalar types.
1313 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1314 castType.getAsString(), castExpr->getSourceRange());
1315 }
1316
1317 // accept this, but emit an ext-warn.
1318 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1319 castType.getAsString(), castExpr->getSourceRange());
1320 } else if (!castExpr->getType()->isScalarType() &&
1321 !castExpr->getType()->isVectorType()) {
1322 return Diag(castExpr->getLocStart(),
1323 diag::err_typecheck_expect_scalar_operand,
1324 castExpr->getType().getAsString(),castExpr->getSourceRange());
1325 } else if (castExpr->getType()->isVectorType()) {
1326 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1327 return true;
1328 } else if (castType->isVectorType()) {
1329 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1330 return true;
1331 }
1332 return false;
1333}
1334
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001335bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001336 assert(VectorTy->isVectorType() && "Not a vector type!");
1337
1338 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001339 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001340 return Diag(R.getBegin(),
1341 Ty->isVectorType() ?
1342 diag::err_invalid_conversion_between_vectors :
1343 diag::err_invalid_conversion_between_vector_and_integer,
1344 VectorTy.getAsString().c_str(),
1345 Ty.getAsString().c_str(), R);
1346 } else
1347 return Diag(R.getBegin(),
1348 diag::err_invalid_conversion_between_vector_and_scalar,
1349 VectorTy.getAsString().c_str(),
1350 Ty.getAsString().c_str(), R);
1351
1352 return false;
1353}
1354
Chris Lattner4b009652007-07-25 00:24:17 +00001355Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001356ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001357 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001358 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001359
1360 Expr *castExpr = static_cast<Expr*>(Op);
1361 QualType castType = QualType::getFromOpaquePtr(Ty);
1362
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001363 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1364 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00001365 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001366}
1367
Chris Lattner98a425c2007-11-26 01:40:58 +00001368/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1369/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001370inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1371 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1372 UsualUnaryConversions(cond);
1373 UsualUnaryConversions(lex);
1374 UsualUnaryConversions(rex);
1375 QualType condT = cond->getType();
1376 QualType lexT = lex->getType();
1377 QualType rexT = rex->getType();
1378
1379 // first, check the condition.
1380 if (!condT->isScalarType()) { // C99 6.5.15p2
1381 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1382 condT.getAsString());
1383 return QualType();
1384 }
Chris Lattner992ae932008-01-06 22:42:25 +00001385
1386 // Now check the two expressions.
1387
1388 // If both operands have arithmetic type, do the usual arithmetic conversions
1389 // to find a common type: C99 6.5.15p3,5.
1390 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001391 UsualArithmeticConversions(lex, rex);
1392 return lex->getType();
1393 }
Chris Lattner992ae932008-01-06 22:42:25 +00001394
1395 // If both operands are the same structure or union type, the result is that
1396 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001397 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001398 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001399 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001400 // "If both the operands have structure or union type, the result has
1401 // that type." This implies that CV qualifiers are dropped.
1402 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001403 }
Chris Lattner992ae932008-01-06 22:42:25 +00001404
1405 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001406 // The following || allows only one side to be void (a GCC-ism).
1407 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001408 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001409 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1410 rex->getSourceRange());
1411 if (!rexT->isVoidType())
1412 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001413 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001414 ImpCastExprToType(lex, Context.VoidTy);
1415 ImpCastExprToType(rex, Context.VoidTy);
1416 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001417 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001418 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1419 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001420 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1421 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001422 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001423 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001424 return lexT;
1425 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001426 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1427 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001428 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001429 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001430 return rexT;
1431 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001432 // Handle the case where both operands are pointers before we handle null
1433 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001434 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1435 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1436 // get the "pointed to" types
1437 QualType lhptee = LHSPT->getPointeeType();
1438 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001439
Chris Lattner71225142007-07-31 21:27:01 +00001440 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1441 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001442 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001443 // Figure out necessary qualifiers (C99 6.5.15p6)
1444 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001445 QualType destType = Context.getPointerType(destPointee);
1446 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1447 ImpCastExprToType(rex, destType); // promote to void*
1448 return destType;
1449 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001450 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001451 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001452 QualType destType = Context.getPointerType(destPointee);
1453 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1454 ImpCastExprToType(rex, destType); // promote to void*
1455 return destType;
1456 }
Chris Lattner4b009652007-07-25 00:24:17 +00001457
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001458 QualType compositeType = lexT;
1459
1460 // If either type is an Objective-C object type then check
1461 // compatibility according to Objective-C.
1462 if (Context.isObjCObjectPointerType(lexT) ||
1463 Context.isObjCObjectPointerType(rexT)) {
1464 // If both operands are interfaces and either operand can be
1465 // assigned to the other, use that type as the composite
1466 // type. This allows
1467 // xxx ? (A*) a : (B*) b
1468 // where B is a subclass of A.
1469 //
1470 // Additionally, as for assignment, if either type is 'id'
1471 // allow silent coercion. Finally, if the types are
1472 // incompatible then make sure to use 'id' as the composite
1473 // type so the result is acceptable for sending messages to.
1474
1475 // FIXME: This code should not be localized to here. Also this
1476 // should use a compatible check instead of abusing the
1477 // canAssignObjCInterfaces code.
1478 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1479 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1480 if (LHSIface && RHSIface &&
1481 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1482 compositeType = lexT;
1483 } else if (LHSIface && RHSIface &&
1484 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1485 compositeType = rexT;
1486 } else if (Context.isObjCIdType(lhptee) ||
1487 Context.isObjCIdType(rhptee)) {
1488 // FIXME: This code looks wrong, because isObjCIdType checks
1489 // the struct but getObjCIdType returns the pointer to
1490 // struct. This is horrible and should be fixed.
1491 compositeType = Context.getObjCIdType();
1492 } else {
1493 QualType incompatTy = Context.getObjCIdType();
1494 ImpCastExprToType(lex, incompatTy);
1495 ImpCastExprToType(rex, incompatTy);
1496 return incompatTy;
1497 }
1498 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1499 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001500 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001501 lexT.getAsString(), rexT.getAsString(),
1502 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001503 // In this situation, we assume void* type. No especially good
1504 // reason, but this is what gcc does, and we do have to pick
1505 // to get a consistent AST.
1506 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001507 ImpCastExprToType(lex, incompatTy);
1508 ImpCastExprToType(rex, incompatTy);
1509 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001510 }
1511 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001512 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1513 // differently qualified versions of compatible types, the result type is
1514 // a pointer to an appropriately qualified version of the *composite*
1515 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001516 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001517 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001518 ImpCastExprToType(lex, compositeType);
1519 ImpCastExprToType(rex, compositeType);
1520 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001521 }
Chris Lattner4b009652007-07-25 00:24:17 +00001522 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001523 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1524 // evaluates to "struct objc_object *" (and is handled above when comparing
1525 // id with statically typed objects).
1526 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1527 // GCC allows qualified id and any Objective-C type to devolve to
1528 // id. Currently localizing to here until clear this should be
1529 // part of ObjCQualifiedIdTypesAreCompatible.
1530 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1531 (lexT->isObjCQualifiedIdType() &&
1532 Context.isObjCObjectPointerType(rexT)) ||
1533 (rexT->isObjCQualifiedIdType() &&
1534 Context.isObjCObjectPointerType(lexT))) {
1535 // FIXME: This is not the correct composite type. This only
1536 // happens to work because id can more or less be used anywhere,
1537 // however this may change the type of method sends.
1538 // FIXME: gcc adds some type-checking of the arguments and emits
1539 // (confusing) incompatible comparison warnings in some
1540 // cases. Investigate.
1541 QualType compositeType = Context.getObjCIdType();
1542 ImpCastExprToType(lex, compositeType);
1543 ImpCastExprToType(rex, compositeType);
1544 return compositeType;
1545 }
1546 }
1547
Steve Naroff3eac7692008-09-10 19:17:48 +00001548 // Selection between block pointer types is ok as long as they are the same.
1549 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1550 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1551 return lexT;
1552
Chris Lattner992ae932008-01-06 22:42:25 +00001553 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001554 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1555 lexT.getAsString(), rexT.getAsString(),
1556 lex->getSourceRange(), rex->getSourceRange());
1557 return QualType();
1558}
1559
Steve Naroff87d58b42007-09-16 03:34:24 +00001560/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001561/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001562Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001563 SourceLocation ColonLoc,
1564 ExprTy *Cond, ExprTy *LHS,
1565 ExprTy *RHS) {
1566 Expr *CondExpr = (Expr *) Cond;
1567 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001568
1569 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1570 // was the condition.
1571 bool isLHSNull = LHSExpr == 0;
1572 if (isLHSNull)
1573 LHSExpr = CondExpr;
1574
Chris Lattner4b009652007-07-25 00:24:17 +00001575 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1576 RHSExpr, QuestionLoc);
1577 if (result.isNull())
1578 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001579 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1580 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001581}
1582
Chris Lattner4b009652007-07-25 00:24:17 +00001583
1584// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1585// being closely modeled after the C99 spec:-). The odd characteristic of this
1586// routine is it effectively iqnores the qualifiers on the top level pointee.
1587// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1588// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001589Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001590Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1591 QualType lhptee, rhptee;
1592
1593 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001594 lhptee = lhsType->getAsPointerType()->getPointeeType();
1595 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001596
1597 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001598 lhptee = Context.getCanonicalType(lhptee);
1599 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001600
Chris Lattner005ed752008-01-04 18:04:52 +00001601 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001602
1603 // C99 6.5.16.1p1: This following citation is common to constraints
1604 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1605 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001606 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001607 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001608 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001609
1610 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1611 // incomplete type and the other is a pointer to a qualified or unqualified
1612 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001613 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001614 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001615 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001616
1617 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001618 assert(rhptee->isFunctionType());
1619 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001620 }
1621
1622 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001623 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001624 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001625
1626 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001627 assert(lhptee->isFunctionType());
1628 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001629 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001630
1631 // Check for ObjC interfaces
1632 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1633 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1634 if (LHSIface && RHSIface &&
1635 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1636 return ConvTy;
1637
1638 // ID acts sort of like void* for ObjC interfaces
1639 if (LHSIface && Context.isObjCIdType(rhptee))
1640 return ConvTy;
1641 if (RHSIface && Context.isObjCIdType(lhptee))
1642 return ConvTy;
1643
Chris Lattner4b009652007-07-25 00:24:17 +00001644 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1645 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001646 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1647 rhptee.getUnqualifiedType()))
1648 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001649 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001650}
1651
Steve Naroff3454b6c2008-09-04 15:10:53 +00001652/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1653/// block pointer types are compatible or whether a block and normal pointer
1654/// are compatible. It is more restrict than comparing two function pointer
1655// types.
1656Sema::AssignConvertType
1657Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1658 QualType rhsType) {
1659 QualType lhptee, rhptee;
1660
1661 // get the "pointed to" type (ignoring qualifiers at the top level)
1662 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1663 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1664
1665 // make sure we operate on the canonical type
1666 lhptee = Context.getCanonicalType(lhptee);
1667 rhptee = Context.getCanonicalType(rhptee);
1668
1669 AssignConvertType ConvTy = Compatible;
1670
1671 // For blocks we enforce that qualifiers are identical.
1672 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1673 ConvTy = CompatiblePointerDiscardsQualifiers;
1674
1675 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1676 return IncompatibleBlockPointer;
1677 return ConvTy;
1678}
1679
Chris Lattner4b009652007-07-25 00:24:17 +00001680/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1681/// has code to accommodate several GCC extensions when type checking
1682/// pointers. Here are some objectionable examples that GCC considers warnings:
1683///
1684/// int a, *pint;
1685/// short *pshort;
1686/// struct foo *pfoo;
1687///
1688/// pint = pshort; // warning: assignment from incompatible pointer type
1689/// a = pint; // warning: assignment makes integer from pointer without a cast
1690/// pint = a; // warning: assignment makes pointer from integer without a cast
1691/// pint = pfoo; // warning: assignment from incompatible pointer type
1692///
1693/// As a result, the code for dealing with pointers is more complex than the
1694/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001695///
Chris Lattner005ed752008-01-04 18:04:52 +00001696Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001697Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001698 // Get canonical types. We're not formatting these types, just comparing
1699 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001700 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1701 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001702
1703 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001704 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001705
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001706 // If the left-hand side is a reference type, then we are in a
1707 // (rare!) case where we've allowed the use of references in C,
1708 // e.g., as a parameter type in a built-in function. In this case,
1709 // just make sure that the type referenced is compatible with the
1710 // right-hand side type. The caller is responsible for adjusting
1711 // lhsType so that the resulting expression does not have reference
1712 // type.
1713 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
1714 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001715 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001716 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001717 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001718
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001719 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1720 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001721 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001722 // Relax integer conversions like we do for pointers below.
1723 if (rhsType->isIntegerType())
1724 return IntToPointer;
1725 if (lhsType->isIntegerType())
1726 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00001727 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001728 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001729
Nate Begemanc5f0f652008-07-14 18:02:46 +00001730 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001731 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001732 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1733 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001734 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001735
Nate Begemanc5f0f652008-07-14 18:02:46 +00001736 // If we are allowing lax vector conversions, and LHS and RHS are both
1737 // vectors, the total size only needs to be the same. This is a bitcast;
1738 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001739 if (getLangOptions().LaxVectorConversions &&
1740 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001741 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1742 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001743 }
1744 return Incompatible;
1745 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001746
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001747 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001748 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001749
Chris Lattner390564e2008-04-07 06:49:41 +00001750 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001751 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001752 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001753
Chris Lattner390564e2008-04-07 06:49:41 +00001754 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001755 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001756
Steve Naroffa982c712008-09-29 18:10:17 +00001757 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00001758 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff3454b6c2008-09-04 15:10:53 +00001759 return BlockVoidPointer;
Steve Naroffa982c712008-09-29 18:10:17 +00001760
1761 // Treat block pointers as objects.
1762 if (getLangOptions().ObjC1 &&
1763 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1764 return Compatible;
1765 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001766 return Incompatible;
1767 }
1768
1769 if (isa<BlockPointerType>(lhsType)) {
1770 if (rhsType->isIntegerType())
1771 return IntToPointer;
1772
Steve Naroffa982c712008-09-29 18:10:17 +00001773 // Treat block pointers as objects.
1774 if (getLangOptions().ObjC1 &&
1775 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1776 return Compatible;
1777
Steve Naroff3454b6c2008-09-04 15:10:53 +00001778 if (rhsType->isBlockPointerType())
1779 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1780
1781 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1782 if (RHSPT->getPointeeType()->isVoidType())
1783 return BlockVoidPointer;
1784 }
Chris Lattner1853da22008-01-04 23:18:45 +00001785 return Incompatible;
1786 }
1787
Chris Lattner390564e2008-04-07 06:49:41 +00001788 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001789 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001790 if (lhsType == Context.BoolTy)
1791 return Compatible;
1792
1793 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001794 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001795
Chris Lattner390564e2008-04-07 06:49:41 +00001796 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001797 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001798
1799 if (isa<BlockPointerType>(lhsType) &&
1800 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1801 return BlockVoidPointer;
Chris Lattner1853da22008-01-04 23:18:45 +00001802 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001803 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001804
Chris Lattner1853da22008-01-04 23:18:45 +00001805 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001806 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001807 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001808 }
1809 return Incompatible;
1810}
1811
Chris Lattner005ed752008-01-04 18:04:52 +00001812Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001813Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001814 if (getLangOptions().CPlusPlus) {
1815 if (!lhsType->isRecordType()) {
1816 // C++ 5.17p3: If the left operand is not of class type, the
1817 // expression is implicitly converted (C++ 4) to the
1818 // cv-unqualified type of the left operand.
Douglas Gregorbb461502008-10-24 04:54:22 +00001819 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001820 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00001821 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001822 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001823 }
1824
1825 // FIXME: Currently, we fall through and treat C++ classes like C
1826 // structures.
1827 }
1828
Steve Naroffcdee22d2007-11-27 17:58:44 +00001829 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1830 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00001831 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1832 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001833 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001834 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001835 return Compatible;
1836 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001837
1838 // We don't allow conversion of non-null-pointer constants to integers.
1839 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1840 return IntToBlockPointer;
1841
Chris Lattner5f505bf2007-10-16 02:55:40 +00001842 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001843 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001844 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001845 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001846 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001847 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00001848 if (!lhsType->isReferenceType())
1849 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001850
Chris Lattner005ed752008-01-04 18:04:52 +00001851 Sema::AssignConvertType result =
1852 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001853
1854 // C99 6.5.16.1p2: The value of the right operand is converted to the
1855 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001856 // CheckAssignmentConstraints allows the left-hand side to be a reference,
1857 // so that we can use references in built-in functions even in C.
1858 // The getNonReferenceType() call makes sure that the resulting expression
1859 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00001860 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001861 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001862 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001863}
1864
Chris Lattner005ed752008-01-04 18:04:52 +00001865Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001866Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1867 return CheckAssignmentConstraints(lhsType, rhsType);
1868}
1869
Chris Lattner2c8bff72007-12-12 05:47:28 +00001870QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001871 Diag(loc, diag::err_typecheck_invalid_operands,
1872 lex->getType().getAsString(), rex->getType().getAsString(),
1873 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001874 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001875}
1876
1877inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1878 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001879 // For conversion purposes, we ignore any qualifiers.
1880 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001881 QualType lhsType =
1882 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1883 QualType rhsType =
1884 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001885
Nate Begemanc5f0f652008-07-14 18:02:46 +00001886 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001887 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001888 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001889
Nate Begemanc5f0f652008-07-14 18:02:46 +00001890 // Handle the case of a vector & extvector type of the same size and element
1891 // type. It would be nice if we only had one vector type someday.
1892 if (getLangOptions().LaxVectorConversions)
1893 if (const VectorType *LV = lhsType->getAsVectorType())
1894 if (const VectorType *RV = rhsType->getAsVectorType())
1895 if (LV->getElementType() == RV->getElementType() &&
1896 LV->getNumElements() == RV->getNumElements())
1897 return lhsType->isExtVectorType() ? lhsType : rhsType;
1898
1899 // If the lhs is an extended vector and the rhs is a scalar of the same type
1900 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001901 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001902 QualType eltType = V->getElementType();
1903
1904 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1905 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1906 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001907 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001908 return lhsType;
1909 }
1910 }
1911
Nate Begemanc5f0f652008-07-14 18:02:46 +00001912 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001913 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001914 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001915 QualType eltType = V->getElementType();
1916
1917 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1918 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1919 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001920 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001921 return rhsType;
1922 }
1923 }
1924
Chris Lattner4b009652007-07-25 00:24:17 +00001925 // You cannot convert between vector values of different size.
1926 Diag(loc, diag::err_typecheck_vector_not_convertable,
1927 lex->getType().getAsString(), rex->getType().getAsString(),
1928 lex->getSourceRange(), rex->getSourceRange());
1929 return QualType();
1930}
1931
1932inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001933 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001934{
1935 QualType lhsType = lex->getType(), rhsType = rex->getType();
1936
1937 if (lhsType->isVectorType() || rhsType->isVectorType())
1938 return CheckVectorOperands(loc, lex, rex);
1939
Steve Naroff8f708362007-08-24 19:07:16 +00001940 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001941
Chris Lattner4b009652007-07-25 00:24:17 +00001942 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001943 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001944 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001945}
1946
1947inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001948 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001949{
1950 QualType lhsType = lex->getType(), rhsType = rex->getType();
1951
Steve Naroff8f708362007-08-24 19:07:16 +00001952 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001953
Chris Lattner4b009652007-07-25 00:24:17 +00001954 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001955 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001956 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001957}
1958
1959inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001960 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001961{
1962 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1963 return CheckVectorOperands(loc, lex, rex);
1964
Steve Naroff8f708362007-08-24 19:07:16 +00001965 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001966
Chris Lattner4b009652007-07-25 00:24:17 +00001967 // handle the common case first (both operands are arithmetic).
1968 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001969 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001970
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001971 // Put any potential pointer into PExp
1972 Expr* PExp = lex, *IExp = rex;
1973 if (IExp->getType()->isPointerType())
1974 std::swap(PExp, IExp);
1975
1976 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1977 if (IExp->getType()->isIntegerType()) {
1978 // Check for arithmetic on pointers to incomplete types
1979 if (!PTy->getPointeeType()->isObjectType()) {
1980 if (PTy->getPointeeType()->isVoidType()) {
1981 Diag(loc, diag::ext_gnu_void_ptr,
1982 lex->getSourceRange(), rex->getSourceRange());
1983 } else {
1984 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1985 lex->getType().getAsString(), lex->getSourceRange());
1986 return QualType();
1987 }
1988 }
1989 return PExp->getType();
1990 }
1991 }
1992
Chris Lattner2c8bff72007-12-12 05:47:28 +00001993 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001994}
1995
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001996// C99 6.5.6
1997QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1998 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001999 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2000 return CheckVectorOperands(loc, lex, rex);
2001
Steve Naroff8f708362007-08-24 19:07:16 +00002002 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002003
Chris Lattnerf6da2912007-12-09 21:53:25 +00002004 // Enforce type constraints: C99 6.5.6p3.
2005
2006 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002007 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002008 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002009
2010 // Either ptr - int or ptr - ptr.
2011 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002012 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002013
Chris Lattnerf6da2912007-12-09 21:53:25 +00002014 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002015 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002016 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002017 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002018 Diag(loc, diag::ext_gnu_void_ptr,
2019 lex->getSourceRange(), rex->getSourceRange());
2020 } else {
2021 Diag(loc, diag::err_typecheck_sub_ptr_object,
2022 lex->getType().getAsString(), lex->getSourceRange());
2023 return QualType();
2024 }
2025 }
2026
2027 // The result type of a pointer-int computation is the pointer type.
2028 if (rex->getType()->isIntegerType())
2029 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002030
Chris Lattnerf6da2912007-12-09 21:53:25 +00002031 // Handle pointer-pointer subtractions.
2032 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002033 QualType rpointee = RHSPTy->getPointeeType();
2034
Chris Lattnerf6da2912007-12-09 21:53:25 +00002035 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002036 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002037 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002038 if (rpointee->isVoidType()) {
2039 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00002040 Diag(loc, diag::ext_gnu_void_ptr,
2041 lex->getSourceRange(), rex->getSourceRange());
2042 } else {
2043 Diag(loc, diag::err_typecheck_sub_ptr_object,
2044 rex->getType().getAsString(), rex->getSourceRange());
2045 return QualType();
2046 }
2047 }
2048
2049 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002050 if (!Context.typesAreCompatible(
2051 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2052 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002053 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
2054 lex->getType().getAsString(), rex->getType().getAsString(),
2055 lex->getSourceRange(), rex->getSourceRange());
2056 return QualType();
2057 }
2058
2059 return Context.getPointerDiffType();
2060 }
2061 }
2062
Chris Lattner2c8bff72007-12-12 05:47:28 +00002063 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002064}
2065
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002066// C99 6.5.7
2067QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2068 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002069 // C99 6.5.7p2: Each of the operands shall have integer type.
2070 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
2071 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002072
Chris Lattner2c8bff72007-12-12 05:47:28 +00002073 // Shifts don't perform usual arithmetic conversions, they just do integer
2074 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002075 if (!isCompAssign)
2076 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002077 UsualUnaryConversions(rex);
2078
2079 // "The type of the result is that of the promoted left operand."
2080 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002081}
2082
Eli Friedman0d9549b2008-08-22 00:56:42 +00002083static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2084 ASTContext& Context) {
2085 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2086 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2087 // ID acts sort of like void* for ObjC interfaces
2088 if (LHSIface && Context.isObjCIdType(RHS))
2089 return true;
2090 if (RHSIface && Context.isObjCIdType(LHS))
2091 return true;
2092 if (!LHSIface || !RHSIface)
2093 return false;
2094 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2095 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2096}
2097
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002098// C99 6.5.8
2099QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2100 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002101 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2102 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
2103
Chris Lattner254f3bc2007-08-26 01:18:55 +00002104 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002105 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2106 UsualArithmeticConversions(lex, rex);
2107 else {
2108 UsualUnaryConversions(lex);
2109 UsualUnaryConversions(rex);
2110 }
Chris Lattner4b009652007-07-25 00:24:17 +00002111 QualType lType = lex->getType();
2112 QualType rType = rex->getType();
2113
Ted Kremenek486509e2007-10-29 17:13:39 +00002114 // For non-floating point types, check for self-comparisons of the form
2115 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2116 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002117 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002118 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2119 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002120 if (DRL->getDecl() == DRR->getDecl())
2121 Diag(loc, diag::warn_selfcomparison);
2122 }
2123
Chris Lattner254f3bc2007-08-26 01:18:55 +00002124 if (isRelational) {
2125 if (lType->isRealType() && rType->isRealType())
2126 return Context.IntTy;
2127 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002128 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002129 if (lType->isFloatingType()) {
2130 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00002131 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002132 }
2133
Chris Lattner254f3bc2007-08-26 01:18:55 +00002134 if (lType->isArithmeticType() && rType->isArithmeticType())
2135 return Context.IntTy;
2136 }
Chris Lattner4b009652007-07-25 00:24:17 +00002137
Chris Lattner22be8422007-08-26 01:10:14 +00002138 bool LHSIsNull = lex->isNullPointerConstant(Context);
2139 bool RHSIsNull = rex->isNullPointerConstant(Context);
2140
Chris Lattner254f3bc2007-08-26 01:18:55 +00002141 // All of the following pointer related warnings are GCC extensions, except
2142 // when handling null pointer constants. One day, we can consider making them
2143 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002144 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002145 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002146 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002147 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002148 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002149
Steve Naroff3b435622007-11-13 14:57:38 +00002150 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002151 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2152 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002153 RCanPointeeTy.getUnqualifiedType()) &&
2154 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroff4462cb02007-08-16 21:48:38 +00002155 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2156 lType.getAsString(), rType.getAsString(),
2157 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002158 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002159 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002160 return Context.IntTy;
2161 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002162 // Handle block pointer types.
2163 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2164 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2165 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2166
2167 if (!LHSIsNull && !RHSIsNull &&
2168 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2169 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2170 lType.getAsString(), rType.getAsString(),
2171 lex->getSourceRange(), rex->getSourceRange());
2172 }
2173 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2174 return Context.IntTy;
2175 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002176 // Allow block pointers to be compared with null pointer constants.
2177 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2178 (lType->isPointerType() && rType->isBlockPointerType())) {
2179 if (!LHSIsNull && !RHSIsNull) {
2180 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2181 lType.getAsString(), rType.getAsString(),
2182 lex->getSourceRange(), rex->getSourceRange());
2183 }
2184 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2185 return Context.IntTy;
2186 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002187
Steve Naroff936c4362008-06-03 14:04:54 +00002188 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002189 if (lType->isPointerType() || rType->isPointerType()) {
2190 if (!Context.typesAreCompatible(lType, rType)) {
2191 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2192 lType.getAsString(), rType.getAsString(),
2193 lex->getSourceRange(), rex->getSourceRange());
2194 ImpCastExprToType(rex, lType);
2195 return Context.IntTy;
2196 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002197 ImpCastExprToType(rex, lType);
Steve Naroff792800d2008-10-22 22:40:28 +00002198 return Context.IntTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002199 }
Steve Naroff936c4362008-06-03 14:04:54 +00002200 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2201 ImpCastExprToType(rex, lType);
2202 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002203 } else {
2204 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
2205 Diag(loc, diag::warn_incompatible_qualified_id_operands,
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002206 lType.getAsString(), rType.getAsString(),
Steve Naroff19608432008-10-14 22:18:38 +00002207 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002208 ImpCastExprToType(rex, lType);
Steve Naroff792800d2008-10-22 22:40:28 +00002209 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002210 }
Steve Naroff936c4362008-06-03 14:04:54 +00002211 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002212 }
Steve Naroff936c4362008-06-03 14:04:54 +00002213 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2214 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002215 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002216 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2217 lType.getAsString(), rType.getAsString(),
2218 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002219 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002220 return Context.IntTy;
2221 }
Steve Naroff936c4362008-06-03 14:04:54 +00002222 if (lType->isIntegerType() &&
2223 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002224 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002225 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2226 lType.getAsString(), rType.getAsString(),
2227 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002228 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002229 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002230 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002231 // Handle block pointers.
2232 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2233 if (!RHSIsNull)
2234 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2235 lType.getAsString(), rType.getAsString(),
2236 lex->getSourceRange(), rex->getSourceRange());
2237 ImpCastExprToType(rex, lType); // promote the integer to pointer
2238 return Context.IntTy;
2239 }
2240 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2241 if (!LHSIsNull)
2242 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2243 lType.getAsString(), rType.getAsString(),
2244 lex->getSourceRange(), rex->getSourceRange());
2245 ImpCastExprToType(lex, rType); // promote the integer to pointer
2246 return Context.IntTy;
2247 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00002248 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002249}
2250
Nate Begemanc5f0f652008-07-14 18:02:46 +00002251/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2252/// operates on extended vector types. Instead of producing an IntTy result,
2253/// like a scalar comparison, a vector comparison produces a vector of integer
2254/// types.
2255QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2256 SourceLocation loc,
2257 bool isRelational) {
2258 // Check to make sure we're operating on vectors of the same type and width,
2259 // Allowing one side to be a scalar of element type.
2260 QualType vType = CheckVectorOperands(loc, lex, rex);
2261 if (vType.isNull())
2262 return vType;
2263
2264 QualType lType = lex->getType();
2265 QualType rType = rex->getType();
2266
2267 // For non-floating point types, check for self-comparisons of the form
2268 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2269 // often indicate logic errors in the program.
2270 if (!lType->isFloatingType()) {
2271 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2272 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2273 if (DRL->getDecl() == DRR->getDecl())
2274 Diag(loc, diag::warn_selfcomparison);
2275 }
2276
2277 // Check for comparisons of floating point operands using != and ==.
2278 if (!isRelational && lType->isFloatingType()) {
2279 assert (rType->isFloatingType());
2280 CheckFloatComparison(loc,lex,rex);
2281 }
2282
2283 // Return the type for the comparison, which is the same as vector type for
2284 // integer vectors, or an integer type of identical size and number of
2285 // elements for floating point vectors.
2286 if (lType->isIntegerType())
2287 return lType;
2288
2289 const VectorType *VTy = lType->getAsVectorType();
2290
2291 // FIXME: need to deal with non-32b int / non-64b long long
2292 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2293 if (TypeSize == 32) {
2294 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2295 }
2296 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2297 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2298}
2299
Chris Lattner4b009652007-07-25 00:24:17 +00002300inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00002301 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002302{
2303 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2304 return CheckVectorOperands(loc, lex, rex);
2305
Steve Naroff8f708362007-08-24 19:07:16 +00002306 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002307
2308 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002309 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002310 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002311}
2312
2313inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
2314 Expr *&lex, Expr *&rex, SourceLocation loc)
2315{
2316 UsualUnaryConversions(lex);
2317 UsualUnaryConversions(rex);
2318
Eli Friedmanbea3f842008-05-13 20:16:47 +00002319 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002320 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002321 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002322}
2323
2324inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00002325 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00002326{
2327 QualType lhsType = lex->getType();
2328 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner25168a52008-07-26 21:30:36 +00002329 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002330
2331 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00002332 case Expr::MLV_Valid:
2333 break;
2334 case Expr::MLV_ConstQualified:
2335 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2336 return QualType();
2337 case Expr::MLV_ArrayType:
2338 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2339 lhsType.getAsString(), lex->getSourceRange());
2340 return QualType();
2341 case Expr::MLV_NotObjectType:
2342 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2343 lhsType.getAsString(), lex->getSourceRange());
2344 return QualType();
2345 case Expr::MLV_InvalidExpression:
2346 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2347 lex->getSourceRange());
2348 return QualType();
2349 case Expr::MLV_IncompleteType:
2350 case Expr::MLV_IncompleteVoidType:
2351 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2352 lhsType.getAsString(), lex->getSourceRange());
2353 return QualType();
2354 case Expr::MLV_DuplicateVectorComponents:
2355 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2356 lex->getSourceRange());
2357 return QualType();
Steve Naroff076d6cb2008-09-26 14:41:28 +00002358 case Expr::MLV_NotBlockQualified:
2359 Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2360 lex->getSourceRange());
2361 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002362 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002363
Chris Lattner005ed752008-01-04 18:04:52 +00002364 AssignConvertType ConvTy;
Chris Lattner34c85082008-08-21 18:04:13 +00002365 if (compoundType.isNull()) {
2366 // Simple assignment "x = y".
Chris Lattner005ed752008-01-04 18:04:52 +00002367 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner34c85082008-08-21 18:04:13 +00002368
2369 // If the RHS is a unary plus or minus, check to see if they = and + are
2370 // right next to each other. If so, the user may have typo'd "x =+ 4"
2371 // instead of "x += 4".
2372 Expr *RHSCheck = rex;
2373 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2374 RHSCheck = ICE->getSubExpr();
2375 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2376 if ((UO->getOpcode() == UnaryOperator::Plus ||
2377 UO->getOpcode() == UnaryOperator::Minus) &&
2378 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2379 // Only if the two operators are exactly adjacent.
2380 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2381 Diag(loc, diag::warn_not_compound_assign,
2382 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2383 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2384 }
2385 } else {
2386 // Compound assignment "x += y"
Chris Lattner005ed752008-01-04 18:04:52 +00002387 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner34c85082008-08-21 18:04:13 +00002388 }
Chris Lattner005ed752008-01-04 18:04:52 +00002389
2390 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2391 rex, "assigning"))
2392 return QualType();
2393
Chris Lattner4b009652007-07-25 00:24:17 +00002394 // C99 6.5.16p3: The type of an assignment expression is the type of the
2395 // left operand unless the left operand has qualified type, in which case
2396 // it is the unqualified version of the type of the left operand.
2397 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2398 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002399 // C++ 5.17p1: the type of the assignment expression is that of its left
2400 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00002401 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002402}
2403
2404inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2405 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00002406
2407 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2408 DefaultFunctionArrayConversion(rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002409 return rex->getType();
2410}
2411
2412/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2413/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2414QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2415 QualType resType = op->getType();
2416 assert(!resType.isNull() && "no type for increment/decrement expression");
2417
Steve Naroffd30e1932007-08-24 17:20:07 +00002418 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00002419 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002420 if (pt->getPointeeType()->isVoidType()) {
2421 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2422 } else if (!pt->getPointeeType()->isObjectType()) {
2423 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00002424 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2425 resType.getAsString(), op->getSourceRange());
2426 return QualType();
2427 }
Steve Naroffd30e1932007-08-24 17:20:07 +00002428 } else if (!resType->isRealType()) {
2429 if (resType->isComplexType())
2430 // C99 does not support ++/-- on complex types.
2431 Diag(OpLoc, diag::ext_integer_increment_complex,
2432 resType.getAsString(), op->getSourceRange());
2433 else {
2434 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2435 resType.getAsString(), op->getSourceRange());
2436 return QualType();
2437 }
Chris Lattner4b009652007-07-25 00:24:17 +00002438 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002439 // At this point, we know we have a real, complex or pointer type.
2440 // Now make sure the operand is a modifiable lvalue.
Chris Lattner25168a52008-07-26 21:30:36 +00002441 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002442 if (mlval != Expr::MLV_Valid) {
2443 // FIXME: emit a more precise diagnostic...
2444 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2445 op->getSourceRange());
2446 return QualType();
2447 }
2448 return resType;
2449}
2450
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002451/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002452/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002453/// where the declaration is needed for type checking. We only need to
2454/// handle cases when the expression references a function designator
2455/// or is an lvalue. Here are some examples:
2456/// - &(x) => x
2457/// - &*****f => f for f a function designator.
2458/// - &s.xx => s
2459/// - &s.zz[1].yy -> s, if zz is an array
2460/// - *(x + 1) -> x, if x is an array
2461/// - &"123"[2] -> 0
2462/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002463static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002464 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002465 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002466 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002467 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002468 // Fields cannot be declared with a 'register' storage class.
2469 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002470 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002471 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002472 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002473 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002474 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002475
Douglas Gregord2baafd2008-10-21 16:13:35 +00002476 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002477 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002478 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002479 return 0;
2480 else
2481 return VD;
2482 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002483 case Stmt::UnaryOperatorClass: {
2484 UnaryOperator *UO = cast<UnaryOperator>(E);
2485
2486 switch(UO->getOpcode()) {
2487 case UnaryOperator::Deref: {
2488 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002489 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2490 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2491 if (!VD || VD->getType()->isPointerType())
2492 return 0;
2493 return VD;
2494 }
2495 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002496 }
2497 case UnaryOperator::Real:
2498 case UnaryOperator::Imag:
2499 case UnaryOperator::Extension:
2500 return getPrimaryDecl(UO->getSubExpr());
2501 default:
2502 return 0;
2503 }
2504 }
2505 case Stmt::BinaryOperatorClass: {
2506 BinaryOperator *BO = cast<BinaryOperator>(E);
2507
2508 // Handle cases involving pointer arithmetic. The result of an
2509 // Assign or AddAssign is not an lvalue so they can be ignored.
2510
2511 // (x + n) or (n + x) => x
2512 if (BO->getOpcode() == BinaryOperator::Add) {
2513 if (BO->getLHS()->getType()->isPointerType()) {
2514 return getPrimaryDecl(BO->getLHS());
2515 } else if (BO->getRHS()->getType()->isPointerType()) {
2516 return getPrimaryDecl(BO->getRHS());
2517 }
2518 }
2519
2520 return 0;
2521 }
Chris Lattner4b009652007-07-25 00:24:17 +00002522 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002523 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002524 case Stmt::ImplicitCastExprClass:
2525 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002526 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002527 default:
2528 return 0;
2529 }
2530}
2531
2532/// CheckAddressOfOperand - The operand of & must be either a function
2533/// designator or an lvalue designating an object. If it is an lvalue, the
2534/// object cannot be declared with storage class register or be a bit field.
2535/// Note: The usual conversions are *not* applied to the operand of the &
2536/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00002537/// In C++, the operand might be an overloaded function name, in which case
2538/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00002539QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002540 if (getLangOptions().C99) {
2541 // Implement C99-only parts of addressof rules.
2542 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2543 if (uOp->getOpcode() == UnaryOperator::Deref)
2544 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2545 // (assuming the deref expression is valid).
2546 return uOp->getSubExpr()->getType();
2547 }
2548 // Technically, there should be a check for array subscript
2549 // expressions here, but the result of one is always an lvalue anyway.
2550 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002551 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002552 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002553
2554 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002555 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2556 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002557 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2558 op->getSourceRange());
2559 return QualType();
2560 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002561 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2562 if (MemExpr->getMemberDecl()->isBitField()) {
2563 Diag(OpLoc, diag::err_typecheck_address_of,
2564 std::string("bit-field"), op->getSourceRange());
2565 return QualType();
2566 }
2567 // Check for Apple extension for accessing vector components.
2568 } else if (isa<ArraySubscriptExpr>(op) &&
2569 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2570 Diag(OpLoc, diag::err_typecheck_address_of,
2571 std::string("vector"), op->getSourceRange());
2572 return QualType();
2573 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002574 // We have an lvalue with a decl. Make sure the decl is not declared
2575 // with the register storage-class specifier.
2576 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2577 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002578 Diag(OpLoc, diag::err_typecheck_address_of,
2579 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002580 return QualType();
2581 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00002582 } else if (isa<OverloadedFunctionDecl>(dcl))
2583 return Context.OverloadTy;
2584 else
Chris Lattner4b009652007-07-25 00:24:17 +00002585 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002586 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002587
Chris Lattner4b009652007-07-25 00:24:17 +00002588 // If the operand has type "type", the result has type "pointer to type".
2589 return Context.getPointerType(op->getType());
2590}
2591
2592QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2593 UsualUnaryConversions(op);
2594 QualType qType = op->getType();
2595
Chris Lattner7931f4a2007-07-31 16:53:04 +00002596 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002597 // Note that per both C89 and C99, this is always legal, even
2598 // if ptype is an incomplete type or void.
2599 // It would be possible to warn about dereferencing a
2600 // void pointer, but it's completely well-defined,
2601 // and such a warning is unlikely to catch any mistakes.
2602 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002603 }
2604 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2605 qType.getAsString(), op->getSourceRange());
2606 return QualType();
2607}
2608
2609static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2610 tok::TokenKind Kind) {
2611 BinaryOperator::Opcode Opc;
2612 switch (Kind) {
2613 default: assert(0 && "Unknown binop!");
2614 case tok::star: Opc = BinaryOperator::Mul; break;
2615 case tok::slash: Opc = BinaryOperator::Div; break;
2616 case tok::percent: Opc = BinaryOperator::Rem; break;
2617 case tok::plus: Opc = BinaryOperator::Add; break;
2618 case tok::minus: Opc = BinaryOperator::Sub; break;
2619 case tok::lessless: Opc = BinaryOperator::Shl; break;
2620 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2621 case tok::lessequal: Opc = BinaryOperator::LE; break;
2622 case tok::less: Opc = BinaryOperator::LT; break;
2623 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2624 case tok::greater: Opc = BinaryOperator::GT; break;
2625 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2626 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2627 case tok::amp: Opc = BinaryOperator::And; break;
2628 case tok::caret: Opc = BinaryOperator::Xor; break;
2629 case tok::pipe: Opc = BinaryOperator::Or; break;
2630 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2631 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2632 case tok::equal: Opc = BinaryOperator::Assign; break;
2633 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2634 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2635 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2636 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2637 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2638 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2639 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2640 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2641 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2642 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2643 case tok::comma: Opc = BinaryOperator::Comma; break;
2644 }
2645 return Opc;
2646}
2647
2648static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2649 tok::TokenKind Kind) {
2650 UnaryOperator::Opcode Opc;
2651 switch (Kind) {
2652 default: assert(0 && "Unknown unary op!");
2653 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2654 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2655 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2656 case tok::star: Opc = UnaryOperator::Deref; break;
2657 case tok::plus: Opc = UnaryOperator::Plus; break;
2658 case tok::minus: Opc = UnaryOperator::Minus; break;
2659 case tok::tilde: Opc = UnaryOperator::Not; break;
2660 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002661 case tok::kw___real: Opc = UnaryOperator::Real; break;
2662 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2663 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2664 }
2665 return Opc;
2666}
2667
Douglas Gregord7f915e2008-11-06 23:29:22 +00002668/// CreateBuiltinBinOp - Creates a new built-in binary operation with
2669/// operator @p Opc at location @c TokLoc. This routine only supports
2670/// built-in operations; ActOnBinOp handles overloaded operators.
2671Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
2672 unsigned Op,
2673 Expr *lhs, Expr *rhs) {
2674 QualType ResultTy; // Result type of the binary operator.
2675 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2676 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
2677
2678 switch (Opc) {
2679 default:
2680 assert(0 && "Unknown binary expr!");
2681 case BinaryOperator::Assign:
2682 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
2683 break;
2684 case BinaryOperator::Mul:
2685 case BinaryOperator::Div:
2686 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
2687 break;
2688 case BinaryOperator::Rem:
2689 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
2690 break;
2691 case BinaryOperator::Add:
2692 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
2693 break;
2694 case BinaryOperator::Sub:
2695 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
2696 break;
2697 case BinaryOperator::Shl:
2698 case BinaryOperator::Shr:
2699 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
2700 break;
2701 case BinaryOperator::LE:
2702 case BinaryOperator::LT:
2703 case BinaryOperator::GE:
2704 case BinaryOperator::GT:
2705 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
2706 break;
2707 case BinaryOperator::EQ:
2708 case BinaryOperator::NE:
2709 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
2710 break;
2711 case BinaryOperator::And:
2712 case BinaryOperator::Xor:
2713 case BinaryOperator::Or:
2714 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
2715 break;
2716 case BinaryOperator::LAnd:
2717 case BinaryOperator::LOr:
2718 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
2719 break;
2720 case BinaryOperator::MulAssign:
2721 case BinaryOperator::DivAssign:
2722 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
2723 if (!CompTy.isNull())
2724 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2725 break;
2726 case BinaryOperator::RemAssign:
2727 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
2728 if (!CompTy.isNull())
2729 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2730 break;
2731 case BinaryOperator::AddAssign:
2732 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
2733 if (!CompTy.isNull())
2734 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2735 break;
2736 case BinaryOperator::SubAssign:
2737 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
2738 if (!CompTy.isNull())
2739 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2740 break;
2741 case BinaryOperator::ShlAssign:
2742 case BinaryOperator::ShrAssign:
2743 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
2744 if (!CompTy.isNull())
2745 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2746 break;
2747 case BinaryOperator::AndAssign:
2748 case BinaryOperator::XorAssign:
2749 case BinaryOperator::OrAssign:
2750 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
2751 if (!CompTy.isNull())
2752 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2753 break;
2754 case BinaryOperator::Comma:
2755 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
2756 break;
2757 }
2758 if (ResultTy.isNull())
2759 return true;
2760 if (CompTy.isNull())
2761 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
2762 else
2763 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
2764}
2765
Chris Lattner4b009652007-07-25 00:24:17 +00002766// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002767Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
2768 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002769 ExprTy *LHS, ExprTy *RHS) {
2770 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2771 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2772
Steve Naroff87d58b42007-09-16 03:34:24 +00002773 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2774 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002775
Douglas Gregord7f915e2008-11-06 23:29:22 +00002776 if (getLangOptions().CPlusPlus &&
2777 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
2778 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002779 // If this is one of the assignment operators, we only perform
2780 // overload resolution if the left-hand side is a class or
2781 // enumeration type (C++ [expr.ass]p3).
2782 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
2783 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
2784 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
2785 }
2786
Douglas Gregord7f915e2008-11-06 23:29:22 +00002787 // C++ [over.binary]p1:
2788 // A binary operator shall be implemented either by a non-static
2789 // member function (9.3) with one parameter or by a non-member
2790 // function with two parameters. Thus, for any binary operator
2791 // @, x@y can be interpreted as either x.operator@(y) or
2792 // operator@(x,y). If both forms of the operator function have
2793 // been declared, the rules in 13.3.1.2 determines which, if
2794 // any, interpretation is used.
2795 OverloadCandidateSet CandidateSet;
2796
2797 // Determine which overloaded operator we're dealing with.
2798 static const OverloadedOperatorKind OverOps[] = {
2799 OO_Star, OO_Slash, OO_Percent,
2800 OO_Plus, OO_Minus,
2801 OO_LessLess, OO_GreaterGreater,
2802 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2803 OO_EqualEqual, OO_ExclaimEqual,
2804 OO_Amp,
2805 OO_Caret,
2806 OO_Pipe,
2807 OO_AmpAmp,
2808 OO_PipePipe,
2809 OO_Equal, OO_StarEqual,
2810 OO_SlashEqual, OO_PercentEqual,
2811 OO_PlusEqual, OO_MinusEqual,
2812 OO_LessLessEqual, OO_GreaterGreaterEqual,
2813 OO_AmpEqual, OO_CaretEqual,
2814 OO_PipeEqual,
2815 OO_Comma
2816 };
2817 OverloadedOperatorKind OverOp = OverOps[Opc];
2818
2819 // Lookup this operator.
2820 Decl *D = LookupDecl(&PP.getIdentifierTable().getOverloadedOperator(OverOp),
2821 Decl::IDNS_Ordinary, S);
2822
2823 // Add any overloaded operators we find to the overload set.
2824 Expr *Args[2] = { lhs, rhs };
2825 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
2826 AddOverloadCandidate(FD, Args, 2, CandidateSet);
2827 else if (OverloadedFunctionDecl *Ovl
2828 = dyn_cast_or_null<OverloadedFunctionDecl>(D))
2829 AddOverloadCandidates(Ovl, Args, 2, CandidateSet);
2830
Douglas Gregor70d26122008-11-12 17:17:38 +00002831 // Add builtin overload candidates (C++ [over.built]).
2832 AddBuiltinBinaryOperatorCandidates(OverOp, Args, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00002833
2834 // Perform overload resolution.
2835 OverloadCandidateSet::iterator Best;
2836 switch (BestViableFunction(CandidateSet, Best)) {
2837 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00002838 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002839 FunctionDecl *FnDecl = Best->Function;
2840
Douglas Gregor70d26122008-11-12 17:17:38 +00002841 if (FnDecl) {
2842 // We matched an overloaded operator. Build a call to that
2843 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002844
Douglas Gregor70d26122008-11-12 17:17:38 +00002845 // Convert the arguments.
2846 // FIXME: Conversion will be different for member operators.
2847 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
2848 "passing") ||
2849 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
2850 "passing"))
2851 return true;
Douglas Gregord7f915e2008-11-06 23:29:22 +00002852
Douglas Gregor70d26122008-11-12 17:17:38 +00002853 // Determine the result type
2854 QualType ResultTy
2855 = FnDecl->getType()->getAsFunctionType()->getResultType();
2856 ResultTy = ResultTy.getNonReferenceType();
2857
2858 // Build the actual expression node.
2859 // FIXME: We lose the fact that we have a function here!
2860 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
2861 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, ResultTy,
2862 TokLoc);
2863 else
2864 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
2865 } else {
2866 // We matched a built-in operator. Convert the arguments, then
2867 // break out so that we will build the appropriate built-in
2868 // operator node.
2869 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
2870 "passing") ||
2871 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
2872 "passing"))
2873 return true;
2874
2875 break;
2876 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00002877 }
2878
2879 case OR_No_Viable_Function:
2880 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00002881 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002882 break;
2883
2884 case OR_Ambiguous:
2885 Diag(TokLoc,
2886 diag::err_ovl_ambiguous_oper,
2887 BinaryOperator::getOpcodeStr(Opc),
2888 lhs->getSourceRange(), rhs->getSourceRange());
2889 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2890 return true;
2891 }
2892
Douglas Gregor70d26122008-11-12 17:17:38 +00002893 // Either we found no viable overloaded operator or we matched a
2894 // built-in operator. In either case, fall through to trying to
2895 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002896 }
2897
Chris Lattner4b009652007-07-25 00:24:17 +00002898
Douglas Gregord7f915e2008-11-06 23:29:22 +00002899 // Build a built-in binary operation.
2900 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00002901}
2902
2903// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002904Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002905 ExprTy *input) {
2906 Expr *Input = (Expr*)input;
2907 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2908 QualType resultType;
2909 switch (Opc) {
2910 default:
2911 assert(0 && "Unimplemented unary expr!");
2912 case UnaryOperator::PreInc:
2913 case UnaryOperator::PreDec:
2914 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2915 break;
2916 case UnaryOperator::AddrOf:
2917 resultType = CheckAddressOfOperand(Input, OpLoc);
2918 break;
2919 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002920 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002921 resultType = CheckIndirectionOperand(Input, OpLoc);
2922 break;
2923 case UnaryOperator::Plus:
2924 case UnaryOperator::Minus:
2925 UsualUnaryConversions(Input);
2926 resultType = Input->getType();
2927 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2928 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2929 resultType.getAsString());
2930 break;
2931 case UnaryOperator::Not: // bitwise complement
2932 UsualUnaryConversions(Input);
2933 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002934 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2935 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2936 // C99 does not support '~' for complex conjugation.
2937 Diag(OpLoc, diag::ext_integer_complement_complex,
2938 resultType.getAsString(), Input->getSourceRange());
2939 else if (!resultType->isIntegerType())
2940 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2941 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002942 break;
2943 case UnaryOperator::LNot: // logical negation
2944 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2945 DefaultFunctionArrayConversion(Input);
2946 resultType = Input->getType();
2947 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2948 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2949 resultType.getAsString());
2950 // LNot always has type int. C99 6.5.3.3p5.
2951 resultType = Context.IntTy;
2952 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002953 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002954 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002955 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002956 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002957 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002958 resultType = Input->getType();
2959 break;
2960 }
2961 if (resultType.isNull())
2962 return true;
2963 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2964}
2965
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002966/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2967Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002968 SourceLocation LabLoc,
2969 IdentifierInfo *LabelII) {
2970 // Look up the record for this label identifier.
2971 LabelStmt *&LabelDecl = LabelMap[LabelII];
2972
Daniel Dunbar879788d2008-08-04 16:51:22 +00002973 // If we haven't seen this label yet, create a forward reference. It
2974 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00002975 if (LabelDecl == 0)
2976 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2977
2978 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002979 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2980 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002981}
2982
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002983Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002984 SourceLocation RPLoc) { // "({..})"
2985 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2986 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2987 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2988
2989 // FIXME: there are a variety of strange constraints to enforce here, for
2990 // example, it is not possible to goto into a stmt expression apparently.
2991 // More semantic analysis is needed.
2992
2993 // FIXME: the last statement in the compount stmt has its value used. We
2994 // should not warn about it being unused.
2995
2996 // If there are sub stmts in the compound stmt, take the type of the last one
2997 // as the type of the stmtexpr.
2998 QualType Ty = Context.VoidTy;
2999
Chris Lattner200964f2008-07-26 19:51:01 +00003000 if (!Compound->body_empty()) {
3001 Stmt *LastStmt = Compound->body_back();
3002 // If LastStmt is a label, skip down through into the body.
3003 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3004 LastStmt = Label->getSubStmt();
3005
3006 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003007 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003008 }
Chris Lattner4b009652007-07-25 00:24:17 +00003009
3010 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3011}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003012
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003013Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003014 SourceLocation TypeLoc,
3015 TypeTy *argty,
3016 OffsetOfComponent *CompPtr,
3017 unsigned NumComponents,
3018 SourceLocation RPLoc) {
3019 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3020 assert(!ArgTy.isNull() && "Missing type argument!");
3021
3022 // We must have at least one component that refers to the type, and the first
3023 // one is known to be a field designator. Verify that the ArgTy represents
3024 // a struct/union/class.
3025 if (!ArgTy->isRecordType())
3026 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
3027
3028 // Otherwise, create a compound literal expression as the base, and
3029 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003030 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003031
Chris Lattnerb37522e2007-08-31 21:49:13 +00003032 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3033 // GCC extension, diagnose them.
3034 if (NumComponents != 1)
3035 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
3036 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
3037
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003038 for (unsigned i = 0; i != NumComponents; ++i) {
3039 const OffsetOfComponent &OC = CompPtr[i];
3040 if (OC.isBrackets) {
3041 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003042 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003043 if (!AT) {
3044 delete Res;
3045 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
3046 Res->getType().getAsString());
3047 }
3048
Chris Lattner2af6a802007-08-30 17:59:59 +00003049 // FIXME: C++: Verify that operator[] isn't overloaded.
3050
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003051 // C99 6.5.2.1p1
3052 Expr *Idx = static_cast<Expr*>(OC.U.E);
3053 if (!Idx->getType()->isIntegerType())
3054 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
3055 Idx->getSourceRange());
3056
3057 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3058 continue;
3059 }
3060
3061 const RecordType *RC = Res->getType()->getAsRecordType();
3062 if (!RC) {
3063 delete Res;
3064 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
3065 Res->getType().getAsString());
3066 }
3067
3068 // Get the decl corresponding to this.
3069 RecordDecl *RD = RC->getDecl();
3070 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
3071 if (!MemberDecl)
3072 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
3073 OC.U.IdentInfo->getName(),
3074 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00003075
3076 // FIXME: C++: Verify that MemberDecl isn't a static field.
3077 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003078 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3079 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003080 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3081 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003082 }
3083
3084 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3085 BuiltinLoc);
3086}
3087
3088
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003089Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003090 TypeTy *arg1, TypeTy *arg2,
3091 SourceLocation RPLoc) {
3092 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3093 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3094
3095 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3096
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003097 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003098}
3099
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003100Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003101 ExprTy *expr1, ExprTy *expr2,
3102 SourceLocation RPLoc) {
3103 Expr *CondExpr = static_cast<Expr*>(cond);
3104 Expr *LHSExpr = static_cast<Expr*>(expr1);
3105 Expr *RHSExpr = static_cast<Expr*>(expr2);
3106
3107 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3108
3109 // The conditional expression is required to be a constant expression.
3110 llvm::APSInt condEval(32);
3111 SourceLocation ExpLoc;
3112 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
3113 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
3114 CondExpr->getSourceRange());
3115
3116 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3117 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3118 RHSExpr->getType();
3119 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3120}
3121
Steve Naroff52a81c02008-09-03 18:15:37 +00003122//===----------------------------------------------------------------------===//
3123// Clang Extensions.
3124//===----------------------------------------------------------------------===//
3125
3126/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003127void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003128 // Analyze block parameters.
3129 BlockSemaInfo *BSI = new BlockSemaInfo();
3130
3131 // Add BSI to CurBlock.
3132 BSI->PrevBlockInfo = CurBlock;
3133 CurBlock = BSI;
3134
3135 BSI->ReturnType = 0;
3136 BSI->TheScope = BlockScope;
3137
Steve Naroff52059382008-10-10 01:28:17 +00003138 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
3139 PushDeclContext(BSI->TheDecl);
3140}
3141
3142void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003143 // Analyze arguments to block.
3144 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3145 "Not a function declarator!");
3146 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3147
Steve Naroff52059382008-10-10 01:28:17 +00003148 CurBlock->hasPrototype = FTI.hasPrototype;
3149 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003150
3151 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3152 // no arguments, not a function that takes a single void argument.
3153 if (FTI.hasPrototype &&
3154 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3155 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3156 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3157 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003158 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003159 } else if (FTI.hasPrototype) {
3160 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003161 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3162 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003163 }
Steve Naroff52059382008-10-10 01:28:17 +00003164 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3165
3166 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3167 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3168 // If this has an identifier, add it to the scope stack.
3169 if ((*AI)->getIdentifier())
3170 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003171}
3172
3173/// ActOnBlockError - If there is an error parsing a block, this callback
3174/// is invoked to pop the information about the block from the action impl.
3175void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3176 // Ensure that CurBlock is deleted.
3177 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3178
3179 // Pop off CurBlock, handle nested blocks.
3180 CurBlock = CurBlock->PrevBlockInfo;
3181
3182 // FIXME: Delete the ParmVarDecl objects as well???
3183
3184}
3185
3186/// ActOnBlockStmtExpr - This is called when the body of a block statement
3187/// literal was successfully completed. ^(int x){...}
3188Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3189 Scope *CurScope) {
3190 // Ensure that CurBlock is deleted.
3191 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3192 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3193
Steve Naroff52059382008-10-10 01:28:17 +00003194 PopDeclContext();
3195
Steve Naroff52a81c02008-09-03 18:15:37 +00003196 // Pop off CurBlock, handle nested blocks.
3197 CurBlock = CurBlock->PrevBlockInfo;
3198
3199 QualType RetTy = Context.VoidTy;
3200 if (BSI->ReturnType)
3201 RetTy = QualType(BSI->ReturnType, 0);
3202
3203 llvm::SmallVector<QualType, 8> ArgTypes;
3204 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3205 ArgTypes.push_back(BSI->Params[i]->getType());
3206
3207 QualType BlockTy;
3208 if (!BSI->hasPrototype)
3209 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3210 else
3211 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003212 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003213
3214 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003215
Steve Naroff95029d92008-10-08 18:44:00 +00003216 BSI->TheDecl->setBody(Body.take());
3217 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003218}
3219
Nate Begemanbd881ef2008-01-30 20:50:20 +00003220/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003221/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003222/// The number of arguments has already been validated to match the number of
3223/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003224static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3225 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003226 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003227 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003228 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3229 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003230
3231 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003232 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003233 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003234 return true;
3235}
3236
3237Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3238 SourceLocation *CommaLocs,
3239 SourceLocation BuiltinLoc,
3240 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003241 // __builtin_overload requires at least 2 arguments
3242 if (NumArgs < 2)
3243 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3244 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003245
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003246 // The first argument is required to be a constant expression. It tells us
3247 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003248 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003249 Expr *NParamsExpr = Args[0];
3250 llvm::APSInt constEval(32);
3251 SourceLocation ExpLoc;
3252 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
3253 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3254 NParamsExpr->getSourceRange());
3255
3256 // Verify that the number of parameters is > 0
3257 unsigned NumParams = constEval.getZExtValue();
3258 if (NumParams == 0)
3259 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3260 NParamsExpr->getSourceRange());
3261 // Verify that we have at least 1 + NumParams arguments to the builtin.
3262 if ((NumParams + 1) > NumArgs)
3263 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3264 SourceRange(BuiltinLoc, RParenLoc));
3265
3266 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003267 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003268 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003269 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3270 // UsualUnaryConversions will convert the function DeclRefExpr into a
3271 // pointer to function.
3272 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003273 const FunctionTypeProto *FnType = 0;
3274 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3275 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003276
3277 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3278 // parameters, and the number of parameters must match the value passed to
3279 // the builtin.
3280 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00003281 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
3282 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003283
3284 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003285 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003286 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003287 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003288 if (OE)
3289 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
3290 OE->getFn()->getSourceRange());
3291 // Remember our match, and continue processing the remaining arguments
3292 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003293 OE = new OverloadExpr(Args, NumArgs, i,
3294 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003295 BuiltinLoc, RParenLoc);
3296 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003297 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003298 // Return the newly created OverloadExpr node, if we succeded in matching
3299 // exactly one of the candidate functions.
3300 if (OE)
3301 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003302
3303 // If we didn't find a matching function Expr in the __builtin_overload list
3304 // the return an error.
3305 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003306 for (unsigned i = 0; i != NumParams; ++i) {
3307 if (i != 0) typeNames += ", ";
3308 typeNames += Args[i+1]->getType().getAsString();
3309 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003310
3311 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3312 SourceRange(BuiltinLoc, RParenLoc));
3313}
3314
Anders Carlsson36760332007-10-15 20:28:48 +00003315Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3316 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003317 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003318 Expr *E = static_cast<Expr*>(expr);
3319 QualType T = QualType::getFromOpaquePtr(type);
3320
3321 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003322
3323 // Get the va_list type
3324 QualType VaListType = Context.getBuiltinVaListType();
3325 // Deal with implicit array decay; for example, on x86-64,
3326 // va_list is an array, but it's supposed to decay to
3327 // a pointer for va_arg.
3328 if (VaListType->isArrayType())
3329 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003330 // Make sure the input expression also decays appropriately.
3331 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003332
3333 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003334 return Diag(E->getLocStart(),
3335 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3336 E->getType().getAsString(),
3337 E->getSourceRange());
3338
3339 // FIXME: Warn if a non-POD type is passed in.
3340
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003341 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003342}
3343
Chris Lattner005ed752008-01-04 18:04:52 +00003344bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3345 SourceLocation Loc,
3346 QualType DstType, QualType SrcType,
3347 Expr *SrcExpr, const char *Flavor) {
3348 // Decode the result (notice that AST's are still created for extensions).
3349 bool isInvalid = false;
3350 unsigned DiagKind;
3351 switch (ConvTy) {
3352 default: assert(0 && "Unknown conversion type");
3353 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003354 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003355 DiagKind = diag::ext_typecheck_convert_pointer_int;
3356 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003357 case IntToPointer:
3358 DiagKind = diag::ext_typecheck_convert_int_pointer;
3359 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003360 case IncompatiblePointer:
3361 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3362 break;
3363 case FunctionVoidPointer:
3364 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3365 break;
3366 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003367 // If the qualifiers lost were because we were applying the
3368 // (deprecated) C++ conversion from a string literal to a char*
3369 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3370 // Ideally, this check would be performed in
3371 // CheckPointerTypesForAssignment. However, that would require a
3372 // bit of refactoring (so that the second argument is an
3373 // expression, rather than a type), which should be done as part
3374 // of a larger effort to fix CheckPointerTypesForAssignment for
3375 // C++ semantics.
3376 if (getLangOptions().CPlusPlus &&
3377 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3378 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003379 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3380 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003381 case IntToBlockPointer:
3382 DiagKind = diag::err_int_to_block_pointer;
3383 break;
3384 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003385 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003386 break;
3387 case BlockVoidPointer:
3388 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3389 break;
Steve Naroff19608432008-10-14 22:18:38 +00003390 case IncompatibleObjCQualifiedId:
3391 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3392 // it can give a more specific diagnostic.
3393 DiagKind = diag::warn_incompatible_qualified_id;
3394 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003395 case Incompatible:
3396 DiagKind = diag::err_typecheck_convert_incompatible;
3397 isInvalid = true;
3398 break;
3399 }
3400
3401 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3402 SrcExpr->getSourceRange());
3403 return isInvalid;
3404}