blob: 8b2aca61ea0085aa8932cb3a9c4f51aede4421af [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Chris Lattner299b8842008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattner299b8842008-07-25 21:10:04 +000033/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
34void Sema::DefaultFunctionArrayConversion(Expr *&E) {
35 QualType Ty = E->getType();
36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
37
Chris Lattner299b8842008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000040 else if (Ty->isArrayType()) {
41 // In C90 mode, arrays only promote to pointers if the array expression is
42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
43 // type 'array of type' is converted to an expression that has type 'pointer
44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
45 // that has type 'array of type' ...". The relevant change is "an lvalue"
46 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000047 //
48 // C++ 4.2p1:
49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
50 // T" can be converted to an rvalue of type "pointer to T".
51 //
52 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
53 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattner299b8842008-07-25 21:10:04 +000056}
57
58/// UsualUnaryConversions - Performs various conversions that are common to most
59/// operators (C99 6.3). The conversions of array and function types are
60/// sometimes surpressed. For example, the array->pointer conversion doesn't
61/// apply if the array is an argument to the sizeof or address (&) operators.
62/// In these instances, this routine should *not* be called.
63Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
64 QualType Ty = Expr->getType();
65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
66
Chris Lattner299b8842008-07-25 21:10:04 +000067 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
68 ImpCastExprToType(Expr, Context.IntTy);
69 else
70 DefaultFunctionArrayConversion(Expr);
71
72 return Expr;
73}
74
Chris Lattner9305c3d2008-07-25 22:25:12 +000075/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
76/// do not have a prototype. Arguments that have type float are promoted to
77/// double. All other argument types are converted by UsualUnaryConversions().
78void Sema::DefaultArgumentPromotion(Expr *&Expr) {
79 QualType Ty = Expr->getType();
80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
81
82 // If this is a 'float' (CVR qualified or typedef) promote to double.
83 if (const BuiltinType *BT = Ty->getAsBuiltinType())
84 if (BT->getKind() == BuiltinType::Float)
85 return ImpCastExprToType(Expr, Context.DoubleTy);
86
87 UsualUnaryConversions(Expr);
88}
89
Chris Lattner299b8842008-07-25 21:10:04 +000090/// UsualArithmeticConversions - Performs various conversions that are common to
91/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
92/// routine returns the first non-arithmetic type found. The client is
93/// responsible for emitting appropriate error diagnostics.
94/// FIXME: verify the conversion rules for "complex int" are consistent with
95/// GCC.
96QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
97 bool isCompAssign) {
98 if (!isCompAssign) {
99 UsualUnaryConversions(lhsExpr);
100 UsualUnaryConversions(rhsExpr);
101 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000102
Chris Lattner299b8842008-07-25 21:10:04 +0000103 // For conversion purposes, we ignore any qualifiers.
104 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000105 QualType lhs =
106 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
107 QualType rhs =
108 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000109
110 // If both types are identical, no conversion is needed.
111 if (lhs == rhs)
112 return lhs;
113
114 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
115 // The caller can deal with this (e.g. pointer + int).
116 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
117 return lhs;
118
119 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
120 if (!isCompAssign) {
121 ImpCastExprToType(lhsExpr, destType);
122 ImpCastExprToType(rhsExpr, destType);
123 }
124 return destType;
125}
126
127QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
128 // Perform the usual unary conversions. We do this early so that
129 // integral promotions to "int" can allow us to exit early, in the
130 // lhs == rhs check. Also, for conversion purposes, we ignore any
131 // qualifiers. For example, "const float" and "float" are
132 // equivalent.
Douglas Gregor3d4492e2008-11-13 20:12:29 +0000133 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
134 else lhs = lhs.getUnqualifiedType();
135 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
136 else rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000137
Chris Lattner299b8842008-07-25 21:10:04 +0000138 // If both types are identical, no conversion is needed.
139 if (lhs == rhs)
140 return lhs;
141
142 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
143 // The caller can deal with this (e.g. pointer + int).
144 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
145 return lhs;
146
147 // At this point, we have two different arithmetic types.
148
149 // Handle complex types first (C99 6.3.1.8p1).
150 if (lhs->isComplexType() || rhs->isComplexType()) {
151 // if we have an integer operand, the result is the complex type.
152 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
153 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000154 return lhs;
155 }
156 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
157 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000158 return rhs;
159 }
160 // This handles complex/complex, complex/float, or float/complex.
161 // When both operands are complex, the shorter operand is converted to the
162 // type of the longer, and that is the type of the result. This corresponds
163 // to what is done when combining two real floating-point operands.
164 // The fun begins when size promotion occur across type domains.
165 // From H&S 6.3.4: When one operand is complex and the other is a real
166 // floating-point type, the less precise type is converted, within it's
167 // real or complex domain, to the precision of the other type. For example,
168 // when combining a "long double" with a "double _Complex", the
169 // "double _Complex" is promoted to "long double _Complex".
170 int result = Context.getFloatingTypeOrder(lhs, rhs);
171
172 if (result > 0) { // The left side is bigger, convert rhs.
173 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000174 } else if (result < 0) { // The right side is bigger, convert lhs.
175 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000176 }
177 // At this point, lhs and rhs have the same rank/size. Now, make sure the
178 // domains match. This is a requirement for our implementation, C99
179 // does not require this promotion.
180 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
181 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000182 return rhs;
183 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000184 return lhs;
185 }
186 }
187 return lhs; // The domain/size match exactly.
188 }
189 // Now handle "real" floating types (i.e. float, double, long double).
190 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
191 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000192 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000193 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000194 return lhs;
195 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000196 if (rhs->isComplexIntegerType()) {
197 // convert rhs to the complex floating point type.
198 return Context.getComplexType(lhs);
199 }
200 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000201 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000202 return rhs;
203 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000204 if (lhs->isComplexIntegerType()) {
205 // convert lhs to the complex floating point type.
206 return Context.getComplexType(rhs);
207 }
Chris Lattner299b8842008-07-25 21:10:04 +0000208 // We have two real floating types, float/complex combos were handled above.
209 // Convert the smaller operand to the bigger result.
210 int result = Context.getFloatingTypeOrder(lhs, rhs);
211
212 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000213 return lhs;
214 }
215 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000216 return rhs;
217 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000218 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000219 }
220 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
221 // Handle GCC complex int extension.
222 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
223 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
224
225 if (lhsComplexInt && rhsComplexInt) {
226 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
227 rhsComplexInt->getElementType()) >= 0) {
228 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000229 return lhs;
230 }
Chris Lattner299b8842008-07-25 21:10:04 +0000231 return rhs;
232 } else if (lhsComplexInt && rhs->isIntegerType()) {
233 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000234 return lhs;
235 } else if (rhsComplexInt && lhs->isIntegerType()) {
236 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000237 return rhs;
238 }
239 }
240 // Finally, we have two differing integer types.
241 // The rules for this case are in C99 6.3.1.8
242 int compare = Context.getIntegerTypeOrder(lhs, rhs);
243 bool lhsSigned = lhs->isSignedIntegerType(),
244 rhsSigned = rhs->isSignedIntegerType();
245 QualType destType;
246 if (lhsSigned == rhsSigned) {
247 // Same signedness; use the higher-ranked type
248 destType = compare >= 0 ? lhs : rhs;
249 } else if (compare != (lhsSigned ? 1 : -1)) {
250 // The unsigned type has greater than or equal rank to the
251 // signed type, so use the unsigned type
252 destType = lhsSigned ? rhs : lhs;
253 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
254 // The two types are different widths; if we are here, that
255 // means the signed type is larger than the unsigned type, so
256 // use the signed type.
257 destType = lhsSigned ? lhs : rhs;
258 } else {
259 // The signed type is higher-ranked than the unsigned type,
260 // but isn't actually any bigger (like unsigned int and long
261 // on most 32-bit systems). Use the unsigned type corresponding
262 // to the signed type.
263 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
264 }
Chris Lattner299b8842008-07-25 21:10:04 +0000265 return destType;
266}
267
268//===----------------------------------------------------------------------===//
269// Semantic Analysis for various Expression Types
270//===----------------------------------------------------------------------===//
271
272
Steve Naroff87d58b42007-09-16 03:34:24 +0000273/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000274/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
275/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
276/// multiple tokens. However, the common case is that StringToks points to one
277/// string.
278///
279Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000280Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000281 assert(NumStringToks && "Must have at least one string!");
282
283 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
284 if (Literal.hadError)
285 return ExprResult(true);
286
287 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
288 for (unsigned i = 0; i != NumStringToks; ++i)
289 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000290
291 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000292 if (Literal.Pascal && Literal.GetStringLength() > 256)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000293 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
294 << SourceRange(StringToks[0].getLocation(),
295 StringToks[NumStringToks-1].getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000296
Chris Lattnera6dcce32008-02-11 00:02:17 +0000297 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000298 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000299 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000300
301 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
302 if (getLangOptions().CPlusPlus)
303 StrTy.addConst();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000304
305 // Get an array type for the string, according to C99 6.4.5. This includes
306 // the nul terminator character as well as the string length for pascal
307 // strings.
308 StrTy = Context.getConstantArrayType(StrTy,
309 llvm::APInt(32, Literal.GetStringLength()+1),
310 ArrayType::Normal, 0);
311
Chris Lattner4b009652007-07-25 00:24:17 +0000312 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
313 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000314 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000315 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000316 StringToks[NumStringToks-1].getLocation());
317}
318
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000319/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
320/// CurBlock to VD should cause it to be snapshotted (as we do for auto
321/// variables defined outside the block) or false if this is not needed (e.g.
322/// for values inside the block or for globals).
323///
324/// FIXME: This will create BlockDeclRefExprs for global variables,
325/// function references, etc which is suboptimal :) and breaks
326/// things like "integer constant expression" tests.
327static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
328 ValueDecl *VD) {
329 // If the value is defined inside the block, we couldn't snapshot it even if
330 // we wanted to.
331 if (CurBlock->TheDecl == VD->getDeclContext())
332 return false;
333
334 // If this is an enum constant or function, it is constant, don't snapshot.
335 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
336 return false;
337
338 // If this is a reference to an extern, static, or global variable, no need to
339 // snapshot it.
340 // FIXME: What about 'const' variables in C++?
341 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
342 return Var->hasLocalStorage();
343
344 return true;
345}
346
347
348
Steve Naroff0acc9c92007-09-15 18:49:24 +0000349/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000350/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000351/// identifier is used in a function call context.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000352/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the
353/// class or namespace that the identifier must be a member of.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000354Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000355 IdentifierInfo &II,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000356 bool HasTrailingLParen,
357 const CXXScopeSpec *SS) {
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000358 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
359}
360
Douglas Gregor566782a2009-01-06 05:10:23 +0000361/// BuildDeclRefExpr - Build either a DeclRefExpr or a
362/// QualifiedDeclRefExpr based on whether or not SS is a
363/// nested-name-specifier.
364DeclRefExpr *Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
365 bool TypeDependent, bool ValueDependent,
366 const CXXScopeSpec *SS) {
367 if (SS && !SS->isEmpty())
368 return new QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent,
369 SS->getRange().getBegin());
370 else
371 return new DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
372}
373
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000374/// ActOnDeclarationNameExpr - The parser has read some kind of name
375/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
376/// performs lookup on that name and returns an expression that refers
377/// to that name. This routine isn't directly called from the parser,
378/// because the parser doesn't know about DeclarationName. Rather,
379/// this routine is called by ActOnIdentifierExpr,
380/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
381/// which form the DeclarationName from the corresponding syntactic
382/// forms.
383///
384/// HasTrailingLParen indicates whether this identifier is used in a
385/// function call context. LookupCtx is only used for a C++
386/// qualified-id (foo::bar) to indicate the class or namespace that
387/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000388///
389/// If ForceResolution is true, then we will attempt to resolve the
390/// name even if it looks like a dependent name. This option is off by
391/// default.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000392Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
393 DeclarationName Name,
394 bool HasTrailingLParen,
Douglas Gregora133e262008-12-06 00:22:45 +0000395 const CXXScopeSpec *SS,
396 bool ForceResolution) {
397 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
398 HasTrailingLParen && !SS && !ForceResolution) {
399 // We've seen something of the form
400 // identifier(
401 // and we are in a template, so it is likely that 's' is a
402 // dependent name. However, we won't know until we've parsed all
403 // of the call arguments. So, build a CXXDependentNameExpr node
404 // to represent this name. Then, if it turns out that none of the
405 // arguments are type-dependent, we'll force the resolution of the
406 // dependent name at that point.
407 return new CXXDependentNameExpr(Name.getAsIdentifierInfo(),
408 Context.DependentTy, Loc);
409 }
410
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000411 // Could be enum-constant, value decl, instance variable, etc.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000412 Decl *D;
413 if (SS && !SS->isEmpty()) {
414 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
415 if (DC == 0)
416 return true;
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000417 D = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000418 } else
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000419 D = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Douglas Gregora133e262008-12-06 00:22:45 +0000420
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000421 // If this reference is in an Objective-C method, then ivar lookup happens as
422 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000423 IdentifierInfo *II = Name.getAsIdentifierInfo();
424 if (II && getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000425 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000426 // There are two cases to handle here. 1) scoped lookup could have failed,
427 // in which case we should look for an ivar. 2) scoped lookup could have
428 // found a decl, but that decl is outside the current method (i.e. a global
429 // variable). In these two cases, we do a lookup for an ivar with this
430 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000431 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000432 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000433 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000434 // FIXME: This should use a new expr for a direct reference, don't turn
435 // this into Self->ivar, just return a BareIVarExpr or something.
436 IdentifierInfo &II = Context.Idents.get("self");
437 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000438 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), Loc,
439 static_cast<Expr*>(SelfExpr.Val), true, true);
440 Context.setFieldDecl(IFace, IV, MRef);
441 return MRef;
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000442 }
443 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000444 // Needed to implement property "super.method" notation.
Chris Lattner87fada82008-11-20 05:35:30 +0000445 if (SD == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000446 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000447 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000448 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000449 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000450 }
Chris Lattner4b009652007-07-25 00:24:17 +0000451 if (D == 0) {
452 // Otherwise, this could be an implicitly declared function reference (legal
453 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000454 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000455 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000456 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000457 else {
458 // If this name wasn't predeclared and if this is not a function call,
459 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000460 if (SS && !SS->isEmpty())
Chris Lattner77d52da2008-11-20 06:06:08 +0000461 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattnerb1753422008-11-23 21:45:46 +0000462 << Name << SS->getRange();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000463 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
464 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000465 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000466 else
Chris Lattnerb1753422008-11-23 21:45:46 +0000467 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000468 }
469 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000470
Douglas Gregor3257fb52008-12-22 05:46:06 +0000471 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
472 if (!MD->isStatic()) {
473 // C++ [class.mfct.nonstatic]p2:
474 // [...] if name lookup (3.4.1) resolves the name in the
475 // id-expression to a nonstatic nontype member of class X or of
476 // a base class of X, the id-expression is transformed into a
477 // class member access expression (5.2.5) using (*this) (9.3.2)
478 // as the postfix-expression to the left of the '.' operator.
479 DeclContext *Ctx = 0;
480 QualType MemberType;
481 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
482 Ctx = FD->getDeclContext();
483 MemberType = FD->getType();
484
485 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
486 MemberType = RefType->getPointeeType();
487 else if (!FD->isMutable()) {
488 unsigned combinedQualifiers
489 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
490 MemberType = MemberType.getQualifiedType(combinedQualifiers);
491 }
492 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
493 if (!Method->isStatic()) {
494 Ctx = Method->getParent();
495 MemberType = Method->getType();
496 }
497 } else if (OverloadedFunctionDecl *Ovl
498 = dyn_cast<OverloadedFunctionDecl>(D)) {
499 for (OverloadedFunctionDecl::function_iterator
500 Func = Ovl->function_begin(),
501 FuncEnd = Ovl->function_end();
502 Func != FuncEnd; ++Func) {
503 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
504 if (!DMethod->isStatic()) {
505 Ctx = Ovl->getDeclContext();
506 MemberType = Context.OverloadTy;
507 break;
508 }
509 }
510 }
511
512 if (Ctx && Ctx->isCXXRecord()) {
513 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
514 QualType ThisType = Context.getTagDeclType(MD->getParent());
515 if ((Context.getCanonicalType(CtxType)
516 == Context.getCanonicalType(ThisType)) ||
517 IsDerivedFrom(ThisType, CtxType)) {
518 // Build the implicit member access expression.
519 Expr *This = new CXXThisExpr(SourceLocation(),
520 MD->getThisType(Context));
521 return new MemberExpr(This, true, cast<NamedDecl>(D),
522 SourceLocation(), MemberType);
523 }
524 }
525 }
526 }
527
Douglas Gregor8acb7272008-12-11 16:49:14 +0000528 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000529 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
530 if (MD->isStatic())
531 // "invalid use of member 'x' in static member function"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000532 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattner271d4c22008-11-24 05:29:24 +0000533 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000534 }
535
Douglas Gregor3257fb52008-12-22 05:46:06 +0000536 // Any other ways we could have found the field in a well-formed
537 // program would have been turned into implicit member expressions
538 // above.
Chris Lattner271d4c22008-11-24 05:29:24 +0000539 return Diag(Loc, diag::err_invalid_non_static_member_use)
540 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000541 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000542
Chris Lattner4b009652007-07-25 00:24:17 +0000543 if (isa<TypedefDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000544 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremenek42730c52008-01-07 19:49:32 +0000545 if (isa<ObjCInterfaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000546 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000547 if (isa<NamespaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000548 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000549
Steve Naroffd6163f32008-09-05 22:11:13 +0000550 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000551 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Douglas Gregor566782a2009-01-06 05:10:23 +0000552 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc, false, false, SS);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000553
Steve Naroffd6163f32008-09-05 22:11:13 +0000554 ValueDecl *VD = cast<ValueDecl>(D);
555
556 // check if referencing an identifier with __attribute__((deprecated)).
557 if (VD->getAttr<DeprecatedAttr>())
Chris Lattner271d4c22008-11-24 05:29:24 +0000558 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Douglas Gregor48840c72008-12-10 23:01:14 +0000559
560 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
561 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
562 Scope *CheckS = S;
563 while (CheckS) {
564 if (CheckS->isWithinElse() &&
565 CheckS->getControlParent()->isDeclScope(Var)) {
566 if (Var->getType()->isBooleanType())
567 Diag(Loc, diag::warn_value_always_false) << Var->getDeclName();
568 else
569 Diag(Loc, diag::warn_value_always_zero) << Var->getDeclName();
570 break;
571 }
572
573 // Move up one more control parent to check again.
574 CheckS = CheckS->getControlParent();
575 if (CheckS)
576 CheckS = CheckS->getParent();
577 }
578 }
579 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000580
581 // Only create DeclRefExpr's for valid Decl's.
582 if (VD->isInvalidDecl())
583 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000584
585 // If the identifier reference is inside a block, and it refers to a value
586 // that is outside the block, create a BlockDeclRefExpr instead of a
587 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
588 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000589 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000590 // We do not do this for things like enum constants, global variables, etc,
591 // as they do not get snapshotted.
592 //
593 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000594 // The BlocksAttr indicates the variable is bound by-reference.
595 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000596 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
597 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000598
599 // Variable will be bound by-copy, make it const within the closure.
600 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000601 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
602 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000603 }
604 // If this reference is not in a block or if the referenced variable is
605 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000606
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000607 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000608 bool ValueDependent = false;
609 if (getLangOptions().CPlusPlus) {
610 // C++ [temp.dep.expr]p3:
611 // An id-expression is type-dependent if it contains:
612 // - an identifier that was declared with a dependent type,
613 if (VD->getType()->isDependentType())
614 TypeDependent = true;
615 // - FIXME: a template-id that is dependent,
616 // - a conversion-function-id that specifies a dependent type,
617 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
618 Name.getCXXNameType()->isDependentType())
619 TypeDependent = true;
620 // - a nested-name-specifier that contains a class-name that
621 // names a dependent type.
622 else if (SS && !SS->isEmpty()) {
623 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
624 DC; DC = DC->getParent()) {
625 // FIXME: could stop early at namespace scope.
626 if (DC->isCXXRecord()) {
627 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
628 if (Context.getTypeDeclType(Record)->isDependentType()) {
629 TypeDependent = true;
630 break;
631 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000632 }
633 }
634 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000635
Douglas Gregora5d84612008-12-10 20:57:37 +0000636 // C++ [temp.dep.constexpr]p2:
637 //
638 // An identifier is value-dependent if it is:
639 // - a name declared with a dependent type,
640 if (TypeDependent)
641 ValueDependent = true;
642 // - the name of a non-type template parameter,
643 else if (isa<NonTypeTemplateParmDecl>(VD))
644 ValueDependent = true;
645 // - a constant with integral or enumeration type and is
646 // initialized with an expression that is value-dependent
647 // (FIXME!).
648 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000649
Douglas Gregor566782a2009-01-06 05:10:23 +0000650 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
651 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +0000652}
653
Chris Lattner69909292008-08-10 01:53:14 +0000654Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000655 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000656 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000657
658 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000659 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000660 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
661 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
662 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000663 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000664
Chris Lattner7e637512008-01-12 08:14:25 +0000665 // Pre-defined identifiers are of type char[x], where x is the length of the
666 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000667 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000668 if (FunctionDecl *FD = getCurFunctionDecl())
669 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000670 else if (ObjCMethodDecl *MD = getCurMethodDecl())
671 Length = MD->getSynthesizedMethodSize();
672 else {
673 Diag(Loc, diag::ext_predef_outside_function);
674 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
675 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
676 }
677
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000678
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000679 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000680 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000681 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000682 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000683}
684
Steve Naroff87d58b42007-09-16 03:34:24 +0000685Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000686 llvm::SmallString<16> CharBuffer;
687 CharBuffer.resize(Tok.getLength());
688 const char *ThisTokBegin = &CharBuffer[0];
689 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
690
691 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
692 Tok.getLocation(), PP);
693 if (Literal.hadError())
694 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000695
696 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
697
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000698 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
699 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000700}
701
Steve Naroff87d58b42007-09-16 03:34:24 +0000702Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000703 // fast path for a single digit (which is quite common). A single digit
704 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
705 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000706 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000707
Chris Lattner8cd0e932008-03-05 18:54:05 +0000708 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000709 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000710 Context.IntTy,
711 Tok.getLocation()));
712 }
713 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000714 // Add padding so that NumericLiteralParser can overread by one character.
715 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000716 const char *ThisTokBegin = &IntegerBuffer[0];
717
718 // Get the spelling of the token, which eliminates trigraphs, etc.
719 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000720
Chris Lattner4b009652007-07-25 00:24:17 +0000721 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
722 Tok.getLocation(), PP);
723 if (Literal.hadError)
724 return ExprResult(true);
725
Chris Lattner1de66eb2007-08-26 03:42:43 +0000726 Expr *Res;
727
728 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000729 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000730 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000731 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000732 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000733 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000734 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000735 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000736
737 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
738
Ted Kremenekddedbe22007-11-29 00:56:49 +0000739 // isExact will be set by GetFloatValue().
740 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000741 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000742 Ty, Tok.getLocation());
743
Chris Lattner1de66eb2007-08-26 03:42:43 +0000744 } else if (!Literal.isIntegerLiteral()) {
745 return ExprResult(true);
746 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000747 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000748
Neil Booth7421e9c2007-08-29 22:00:19 +0000749 // long long is a C99 feature.
750 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000751 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000752 Diag(Tok.getLocation(), diag::ext_longlong);
753
Chris Lattner4b009652007-07-25 00:24:17 +0000754 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000755 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000756
757 if (Literal.GetIntegerValue(ResultVal)) {
758 // If this value didn't fit into uintmax_t, warn and force to ull.
759 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000760 Ty = Context.UnsignedLongLongTy;
761 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000762 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000763 } else {
764 // If this value fits into a ULL, try to figure out what else it fits into
765 // according to the rules of C99 6.4.4.1p5.
766
767 // Octal, Hexadecimal, and integers with a U suffix are allowed to
768 // be an unsigned int.
769 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
770
771 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000772 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000773 if (!Literal.isLong && !Literal.isLongLong) {
774 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000775 unsigned IntSize = Context.Target.getIntWidth();
776
Chris Lattner4b009652007-07-25 00:24:17 +0000777 // Does it fit in a unsigned int?
778 if (ResultVal.isIntN(IntSize)) {
779 // Does it fit in a signed int?
780 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000781 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000782 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000783 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000784 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000785 }
Chris Lattner4b009652007-07-25 00:24:17 +0000786 }
787
788 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000789 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000790 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000791
792 // Does it fit in a unsigned long?
793 if (ResultVal.isIntN(LongSize)) {
794 // Does it fit in a signed long?
795 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000796 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000797 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000798 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000799 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000800 }
Chris Lattner4b009652007-07-25 00:24:17 +0000801 }
802
803 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000804 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000805 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000806
807 // Does it fit in a unsigned long long?
808 if (ResultVal.isIntN(LongLongSize)) {
809 // Does it fit in a signed long long?
810 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000811 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000812 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000813 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000814 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000815 }
816 }
817
818 // If we still couldn't decide a type, we probably have something that
819 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000820 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000821 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000822 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000823 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000824 }
Chris Lattnere4068872008-05-09 05:59:00 +0000825
826 if (ResultVal.getBitWidth() != Width)
827 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000828 }
829
Chris Lattner48d7f382008-04-02 04:24:33 +0000830 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000831 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000832
833 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
834 if (Literal.isImaginary)
835 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
836
837 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000838}
839
Steve Naroff87d58b42007-09-16 03:34:24 +0000840Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000841 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000842 Expr *E = (Expr *)Val;
843 assert((E != 0) && "ActOnParenExpr() missing expr");
844 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000845}
846
847/// The UsualUnaryConversions() function is *not* called by this routine.
848/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000849bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
850 SourceLocation OpLoc,
851 const SourceRange &ExprRange,
852 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000853 // C99 6.5.3.4p1:
854 if (isa<FunctionType>(exprType) && isSizeof)
855 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000856 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +0000857 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000858 Diag(OpLoc, diag::ext_sizeof_void_type)
859 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
860 else if (exprType->isIncompleteType())
861 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
862 diag::err_alignof_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000863 << exprType << ExprRange;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000864
865 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000866}
867
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000868/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
869/// the same for @c alignof and @c __alignof
870/// Note that the ArgRange is invalid if isType is false.
871Action::ExprResult
872Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
873 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +0000874 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000875 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000876
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000877 QualType ArgTy;
878 SourceRange Range;
879 if (isType) {
880 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
881 Range = ArgRange;
882 } else {
883 // Get the end location.
884 Expr *ArgEx = (Expr *)TyOrEx;
885 Range = ArgEx->getSourceRange();
886 ArgTy = ArgEx->getType();
887 }
888
889 // Verify that the operand is valid.
890 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +0000891 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000892
893 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
894 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
895 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +0000896}
897
Chris Lattner5110ad52007-08-24 21:41:10 +0000898QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000899 DefaultFunctionArrayConversion(V);
900
Chris Lattnera16e42d2007-08-26 05:39:26 +0000901 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000902 if (const ComplexType *CT = V->getType()->getAsComplexType())
903 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000904
905 // Otherwise they pass through real integer and floating point types here.
906 if (V->getType()->isArithmeticType())
907 return V->getType();
908
909 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +0000910 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000911 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000912}
913
914
Chris Lattner4b009652007-07-25 00:24:17 +0000915
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000916Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000917 tok::TokenKind Kind,
918 ExprTy *Input) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000919 Expr *Arg = (Expr *)Input;
920
Chris Lattner4b009652007-07-25 00:24:17 +0000921 UnaryOperator::Opcode Opc;
922 switch (Kind) {
923 default: assert(0 && "Unknown unary op!");
924 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
925 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
926 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000927
928 if (getLangOptions().CPlusPlus &&
929 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
930 // Which overloaded operator?
931 OverloadedOperatorKind OverOp =
932 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
933
934 // C++ [over.inc]p1:
935 //
936 // [...] If the function is a member function with one
937 // parameter (which shall be of type int) or a non-member
938 // function with two parameters (the second of which shall be
939 // of type int), it defines the postfix increment operator ++
940 // for objects of that type. When the postfix increment is
941 // called as a result of using the ++ operator, the int
942 // argument will have value zero.
943 Expr *Args[2] = {
944 Arg,
945 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
946 /*isSigned=*/true),
947 Context.IntTy, SourceLocation())
948 };
949
950 // Build the candidate set for overloading
951 OverloadCandidateSet CandidateSet;
952 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
953
954 // Perform overload resolution.
955 OverloadCandidateSet::iterator Best;
956 switch (BestViableFunction(CandidateSet, Best)) {
957 case OR_Success: {
958 // We found a built-in operator or an overloaded operator.
959 FunctionDecl *FnDecl = Best->Function;
960
961 if (FnDecl) {
962 // We matched an overloaded operator. Build a call to that
963 // operator.
964
965 // Convert the arguments.
966 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
967 if (PerformObjectArgumentInitialization(Arg, Method))
968 return true;
969 } else {
970 // Convert the arguments.
971 if (PerformCopyInitialization(Arg,
972 FnDecl->getParamDecl(0)->getType(),
973 "passing"))
974 return true;
975 }
976
977 // Determine the result type
978 QualType ResultTy
979 = FnDecl->getType()->getAsFunctionType()->getResultType();
980 ResultTy = ResultTy.getNonReferenceType();
981
982 // Build the actual expression node.
983 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
984 SourceLocation());
985 UsualUnaryConversions(FnExpr);
986
987 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
988 } else {
989 // We matched a built-in operator. Convert the arguments, then
990 // break out so that we will build the appropriate built-in
991 // operator node.
992 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
993 "passing"))
994 return true;
995
996 break;
997 }
998 }
999
1000 case OR_No_Viable_Function:
1001 // No viable function; fall through to handling this as a
1002 // built-in operator, which will produce an error message for us.
1003 break;
1004
1005 case OR_Ambiguous:
1006 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1007 << UnaryOperator::getOpcodeStr(Opc)
1008 << Arg->getSourceRange();
1009 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1010 return true;
1011 }
1012
1013 // Either we found no viable overloaded operator or we matched a
1014 // built-in operator. In either case, fall through to trying to
1015 // build a built-in operation.
1016 }
1017
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001018 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1019 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001020 if (result.isNull())
1021 return true;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001022 return new UnaryOperator(Arg, Opc, result, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001023}
1024
1025Action::ExprResult Sema::
Douglas Gregor80723c52008-11-19 17:17:41 +00001026ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001027 ExprTy *Idx, SourceLocation RLoc) {
1028 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
1029
Douglas Gregor80723c52008-11-19 17:17:41 +00001030 if (getLangOptions().CPlusPlus &&
Eli Friedmane658bf52008-12-15 22:34:21 +00001031 (LHSExp->getType()->isRecordType() ||
1032 LHSExp->getType()->isEnumeralType() ||
1033 RHSExp->getType()->isRecordType() ||
1034 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001035 // Add the appropriate overloaded operators (C++ [over.match.oper])
1036 // to the candidate set.
1037 OverloadCandidateSet CandidateSet;
1038 Expr *Args[2] = { LHSExp, RHSExp };
1039 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
1040
1041 // Perform overload resolution.
1042 OverloadCandidateSet::iterator Best;
1043 switch (BestViableFunction(CandidateSet, Best)) {
1044 case OR_Success: {
1045 // We found a built-in operator or an overloaded operator.
1046 FunctionDecl *FnDecl = Best->Function;
1047
1048 if (FnDecl) {
1049 // We matched an overloaded operator. Build a call to that
1050 // operator.
1051
1052 // Convert the arguments.
1053 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1054 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1055 PerformCopyInitialization(RHSExp,
1056 FnDecl->getParamDecl(0)->getType(),
1057 "passing"))
1058 return true;
1059 } else {
1060 // Convert the arguments.
1061 if (PerformCopyInitialization(LHSExp,
1062 FnDecl->getParamDecl(0)->getType(),
1063 "passing") ||
1064 PerformCopyInitialization(RHSExp,
1065 FnDecl->getParamDecl(1)->getType(),
1066 "passing"))
1067 return true;
1068 }
1069
1070 // Determine the result type
1071 QualType ResultTy
1072 = FnDecl->getType()->getAsFunctionType()->getResultType();
1073 ResultTy = ResultTy.getNonReferenceType();
1074
1075 // Build the actual expression node.
1076 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1077 SourceLocation());
1078 UsualUnaryConversions(FnExpr);
1079
1080 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
1081 } else {
1082 // We matched a built-in operator. Convert the arguments, then
1083 // break out so that we will build the appropriate built-in
1084 // operator node.
1085 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1086 "passing") ||
1087 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1088 "passing"))
1089 return true;
1090
1091 break;
1092 }
1093 }
1094
1095 case OR_No_Viable_Function:
1096 // No viable function; fall through to handling this as a
1097 // built-in operator, which will produce an error message for us.
1098 break;
1099
1100 case OR_Ambiguous:
1101 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1102 << "[]"
1103 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1104 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1105 return true;
1106 }
1107
1108 // Either we found no viable overloaded operator or we matched a
1109 // built-in operator. In either case, fall through to trying to
1110 // build a built-in operation.
1111 }
1112
Chris Lattner4b009652007-07-25 00:24:17 +00001113 // Perform default conversions.
1114 DefaultFunctionArrayConversion(LHSExp);
1115 DefaultFunctionArrayConversion(RHSExp);
1116
1117 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1118
1119 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001120 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001121 // in the subscript position. As a result, we need to derive the array base
1122 // and index from the expression types.
1123 Expr *BaseExpr, *IndexExpr;
1124 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001125 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001126 BaseExpr = LHSExp;
1127 IndexExpr = RHSExp;
1128 // FIXME: need to deal with const...
1129 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001130 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001131 // Handle the uncommon case of "123[Ptr]".
1132 BaseExpr = RHSExp;
1133 IndexExpr = LHSExp;
1134 // FIXME: need to deal with const...
1135 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001136 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1137 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001138 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +00001139
1140 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +00001141 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1142 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001143 return Diag(LLoc, diag::err_ext_vector_component_access)
1144 << SourceRange(LLoc, RLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001145 // FIXME: need to deal with const...
1146 ResultType = VTy->getElementType();
1147 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001148 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
1149 << RHSExp->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001150 }
1151 // C99 6.5.2.1p1
1152 if (!IndexExpr->getType()->isIntegerType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001153 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
1154 << IndexExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001155
1156 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1157 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001158 // void (*)(int)) and pointers to incomplete types. Functions are not
1159 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001160 if (!ResultType->isObjectType())
1161 return Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001162 diag::err_typecheck_subscript_not_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001163 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001164
1165 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
1166}
1167
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001168QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001169CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001170 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001171 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001172
1173 // This flag determines whether or not the component is to be treated as a
1174 // special name, or a regular GLSL-style component access.
1175 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001176
1177 // The vector accessor can't exceed the number of elements.
1178 const char *compStr = CompName.getName();
1179 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001180 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001181 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001182 return QualType();
1183 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001184
1185 // Check that we've found one of the special components, or that the component
1186 // names must come from the same set.
1187 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1188 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1189 SpecialComponent = true;
1190 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001191 do
1192 compStr++;
1193 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1194 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1195 do
1196 compStr++;
1197 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1198 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1199 do
1200 compStr++;
1201 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1202 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001203
Nate Begemanc8e51f82008-05-09 06:41:27 +00001204 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001205 // We didn't get to the end of the string. This means the component names
1206 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001207 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1208 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001209 return QualType();
1210 }
1211 // Each component accessor can't exceed the vector type.
1212 compStr = CompName.getName();
1213 while (*compStr) {
1214 if (vecType->isAccessorWithinNumElements(*compStr))
1215 compStr++;
1216 else
1217 break;
1218 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001219 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001220 // We didn't get to the end of the string. This means a component accessor
1221 // exceeds the number of elements in the vector.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001222 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001223 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001224 return QualType();
1225 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001226
1227 // If we have a special component name, verify that the current vector length
1228 // is an even number, since all special component names return exactly half
1229 // the elements.
1230 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001231 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001232 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001233 return QualType();
1234 }
1235
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001236 // The component accessor looks fine - now we need to compute the actual type.
1237 // The vector type is implied by the component accessor. For example,
1238 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001239 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1240 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner65cae292008-11-19 08:23:25 +00001241 : CompName.getLength();
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001242 if (CompSize == 1)
1243 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001244
Nate Begemanaf6ed502008-04-18 23:10:10 +00001245 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001246 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001247 // diagostics look bad. We want extended vector types to appear built-in.
1248 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1249 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1250 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001251 }
1252 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001253}
1254
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001255/// constructSetterName - Return the setter name for the given
1256/// identifier, i.e. "set" + Name where the initial character of Name
1257/// has been capitalized.
1258// FIXME: Merge with same routine in Parser. But where should this
1259// live?
1260static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1261 const IdentifierInfo *Name) {
1262 llvm::SmallString<100> SelectorName;
1263 SelectorName = "set";
1264 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1265 SelectorName[3] = toupper(SelectorName[3]);
1266 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1267}
1268
Chris Lattner4b009652007-07-25 00:24:17 +00001269Action::ExprResult Sema::
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001270ActOnMemberReferenceExpr(Scope *S, ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001271 tok::TokenKind OpKind, SourceLocation MemberLoc,
1272 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001273 Expr *BaseExpr = static_cast<Expr *>(Base);
1274 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001275
1276 // Perform default conversions.
1277 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +00001278
Steve Naroff2cb66382007-07-26 03:11:44 +00001279 QualType BaseType = BaseExpr->getType();
1280 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001281
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001282 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1283 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001284 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001285 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001286 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001287 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001288 return BuildOverloadedArrowExpr(S, BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroff2cb66382007-07-26 03:11:44 +00001289 else
Chris Lattner8ba580c2008-11-19 05:08:23 +00001290 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001291 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001292 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001293
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001294 // Handle field access to simple records. This also handles access to fields
1295 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001296 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001297 RecordDecl *RDecl = RTy->getDecl();
1298 if (RTy->isIncompleteType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001299 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattner271d4c22008-11-24 05:29:24 +00001300 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroff2cb66382007-07-26 03:11:44 +00001301 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001302 // FIXME: Qualified name lookup for C++ is a bit more complicated
1303 // than this.
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001304 Decl *MemberDecl = LookupDecl(DeclarationName(&Member), Decl::IDNS_Ordinary,
1305 S, RDecl, false, false);
1306 if (!MemberDecl)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001307 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner65cae292008-11-19 08:23:25 +00001308 << &Member << BaseExpr->getSourceRange();
Douglas Gregor8acb7272008-12-11 16:49:14 +00001309
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001310 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor82d44772008-12-20 23:49:58 +00001311 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1312 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001313 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001314 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1315 MemberType = Ref->getPointeeType();
1316 else {
1317 unsigned combinedQualifiers =
1318 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001319 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001320 combinedQualifiers &= ~QualType::Const;
1321 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1322 }
Eli Friedman76b49832008-02-06 22:48:16 +00001323
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001324 return new MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
Douglas Gregor82d44772008-12-20 23:49:58 +00001325 MemberLoc, MemberType);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001326 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001327 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Var, MemberLoc,
1328 Var->getType().getNonReferenceType());
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001329 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001330 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberFn, MemberLoc,
1331 MemberFn->getType());
1332 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001333 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001334 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl, MemberLoc,
1335 Context.OverloadTy);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001336 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001337 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Enum, MemberLoc,
1338 Enum->getType());
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001339 else if (isa<TypeDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001340 return Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1341 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Eli Friedman76b49832008-02-06 22:48:16 +00001342
Douglas Gregor82d44772008-12-20 23:49:58 +00001343 // We found a declaration kind that we didn't expect. This is a
1344 // generic error message that tells the user that she can't refer
1345 // to this member with '.' or '->'.
1346 return Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1347 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Chris Lattnera57cf472008-07-21 04:28:12 +00001348 }
1349
Chris Lattnere9d71612008-07-21 04:59:05 +00001350 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1351 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001352 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001353 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Fariborz Jahanianea944842008-12-18 17:29:46 +00001354 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc,
1355 BaseExpr,
1356 OpKind == tok::arrow);
1357 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
1358 return MRef;
Fariborz Jahanian09772392008-12-13 22:20:28 +00001359 }
Chris Lattner8ba580c2008-11-19 05:08:23 +00001360 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattner271d4c22008-11-24 05:29:24 +00001361 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattner8ba580c2008-11-19 05:08:23 +00001362 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001363 }
1364
Chris Lattnere9d71612008-07-21 04:59:05 +00001365 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1366 // pointer to a (potentially qualified) interface type.
1367 const PointerType *PTy;
1368 const ObjCInterfaceType *IFTy;
1369 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1370 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1371 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001372
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001373 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001374 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1375 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1376
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001377 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001378 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1379 E = IFTy->qual_end(); I != E; ++I)
1380 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1381 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001382
1383 // If that failed, look for an "implicit" property by seeing if the nullary
1384 // selector is implemented.
1385
1386 // FIXME: The logic for looking up nullary and unary selectors should be
1387 // shared with the code in ActOnInstanceMessage.
1388
1389 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1390 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1391
1392 // If this reference is in an @implementation, check for 'private' methods.
1393 if (!Getter)
1394 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1395 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1396 if (ObjCImplementationDecl *ImpDecl =
1397 ObjCImplementations[ClassDecl->getIdentifier()])
1398 Getter = ImpDecl->getInstanceMethod(Sel);
1399
Steve Naroff04151f32008-10-22 19:16:27 +00001400 // Look through local category implementations associated with the class.
1401 if (!Getter) {
1402 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1403 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1404 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1405 }
1406 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001407 if (Getter) {
1408 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001409 // will look for the matching setter, in case it is needed.
1410 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1411 &Member);
1412 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1413 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1414 if (!Setter) {
1415 // If this reference is in an @implementation, also check for 'private'
1416 // methods.
1417 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1418 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1419 if (ObjCImplementationDecl *ImpDecl =
1420 ObjCImplementations[ClassDecl->getIdentifier()])
1421 Setter = ImpDecl->getInstanceMethod(SetterSel);
1422 }
1423 // Look through local category implementations associated with the class.
1424 if (!Setter) {
1425 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1426 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1427 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1428 }
1429 }
1430
1431 // FIXME: we must check that the setter has property type.
1432 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00001433 MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001434 }
Anders Carlsson96095fc2008-12-19 17:27:57 +00001435
1436 return Diag(MemberLoc, diag::err_property_not_found) <<
1437 &Member << BaseType;
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001438 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001439 // Handle properties on qualified "id" protocols.
1440 const ObjCQualifiedIdType *QIdTy;
1441 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1442 // Check protocols on qualified interfaces.
1443 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001444 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001445 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1446 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001447 // Also must look for a getter name which uses property syntax.
1448 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1449 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1450 return new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(), OMD,
1451 OpLoc, MemberLoc, NULL, 0);
1452 }
1453 }
Anders Carlsson96095fc2008-12-19 17:27:57 +00001454
1455 return Diag(MemberLoc, diag::err_property_not_found) <<
1456 &Member << BaseType;
Steve Naroffd1d44402008-10-20 22:53:06 +00001457 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001458 // Handle 'field access' to vectors, such as 'V.xx'.
1459 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1460 // Component access limited to variables (reject vec4.rg.g).
1461 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1462 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001463 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1464 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001465 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1466 if (ret.isNull())
1467 return true;
1468 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1469 }
1470
Chris Lattner8ba580c2008-11-19 05:08:23 +00001471 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001472 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001473}
1474
Douglas Gregor3257fb52008-12-22 05:46:06 +00001475/// ConvertArgumentsForCall - Converts the arguments specified in
1476/// Args/NumArgs to the parameter types of the function FDecl with
1477/// function prototype Proto. Call is the call expression itself, and
1478/// Fn is the function expression. For a C++ member function, this
1479/// routine does not attempt to convert the object argument. Returns
1480/// true if the call is ill-formed.
1481bool
1482Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1483 FunctionDecl *FDecl,
1484 const FunctionTypeProto *Proto,
1485 Expr **Args, unsigned NumArgs,
1486 SourceLocation RParenLoc) {
1487 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1488 // assignment, to the types of the corresponding parameter, ...
1489 unsigned NumArgsInProto = Proto->getNumArgs();
1490 unsigned NumArgsToCheck = NumArgs;
1491
1492 // If too few arguments are available (and we don't have default
1493 // arguments for the remaining parameters), don't make the call.
1494 if (NumArgs < NumArgsInProto) {
1495 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1496 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1497 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1498 // Use default arguments for missing arguments
1499 NumArgsToCheck = NumArgsInProto;
1500 Call->setNumArgs(NumArgsInProto);
1501 }
1502
1503 // If too many are passed and not variadic, error on the extras and drop
1504 // them.
1505 if (NumArgs > NumArgsInProto) {
1506 if (!Proto->isVariadic()) {
1507 Diag(Args[NumArgsInProto]->getLocStart(),
1508 diag::err_typecheck_call_too_many_args)
1509 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1510 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1511 Args[NumArgs-1]->getLocEnd());
1512 // This deletes the extra arguments.
1513 Call->setNumArgs(NumArgsInProto);
1514 }
1515 NumArgsToCheck = NumArgsInProto;
1516 }
1517
1518 // Continue to check argument types (even if we have too few/many args).
1519 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1520 QualType ProtoArgType = Proto->getArgType(i);
1521
1522 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001523 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001524 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001525
1526 // Pass the argument.
1527 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1528 return true;
1529 } else
1530 // We already type-checked the argument, so we know it works.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001531 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
1532 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001533
Douglas Gregor3257fb52008-12-22 05:46:06 +00001534 Call->setArg(i, Arg);
1535 }
1536
1537 // If this is a variadic call, handle args passed through "...".
1538 if (Proto->isVariadic()) {
1539 // Promote the arguments (C99 6.5.2.2p7).
1540 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1541 Expr *Arg = Args[i];
1542 DefaultArgumentPromotion(Arg);
1543 Call->setArg(i, Arg);
1544 }
1545 }
1546
1547 return false;
1548}
1549
Steve Naroff87d58b42007-09-16 03:34:24 +00001550/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001551/// This provides the location of the left/right parens and a list of comma
1552/// locations.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001553Action::ExprResult
1554Sema::ActOnCallExpr(Scope *S, ExprTy *fn, SourceLocation LParenLoc,
1555 ExprTy **args, unsigned NumArgs,
1556 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner4b009652007-07-25 00:24:17 +00001557 Expr *Fn = static_cast<Expr *>(fn);
1558 Expr **Args = reinterpret_cast<Expr**>(args);
1559 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001560 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001561 OverloadedFunctionDecl *Ovl = NULL;
1562
Douglas Gregora133e262008-12-06 00:22:45 +00001563 // Determine whether this is a dependent call inside a C++ template,
1564 // in which case we won't do any semantic analysis now.
1565 bool Dependent = false;
1566 if (Fn->isTypeDependent()) {
1567 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1568 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1569 Dependent = true;
1570 else {
1571 // Resolve the CXXDependentNameExpr to an actual identifier;
1572 // it wasn't really a dependent name after all.
1573 ExprResult Resolved
1574 = ActOnDeclarationNameExpr(S, FnName->getLocation(), FnName->getName(),
1575 /*HasTrailingLParen=*/true,
1576 /*SS=*/0,
1577 /*ForceResolution=*/true);
1578 if (Resolved.isInvalid)
1579 return true;
1580 else {
1581 delete Fn;
1582 Fn = (Expr *)Resolved.Val;
1583 }
1584 }
1585 } else
1586 Dependent = true;
1587 } else
1588 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1589
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001590 // FIXME: Will need to cache the results of name lookup (including
1591 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001592 if (Dependent)
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001593 return new CallExpr(Fn, Args, NumArgs, Context.DependentTy, RParenLoc);
1594
Douglas Gregor3257fb52008-12-22 05:46:06 +00001595 // Determine whether this is a call to an object (C++ [over.call.object]).
1596 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
1597 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1598 CommaLocs, RParenLoc);
1599
1600 // Determine whether this is a call to a member function.
1601 if (getLangOptions().CPlusPlus) {
1602 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1603 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1604 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
1605 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1606 CommaLocs, RParenLoc);
1607 }
1608
Douglas Gregord2baafd2008-10-21 16:13:35 +00001609 // If we're directly calling a function or a set of overloaded
1610 // functions, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001611 DeclRefExpr *DRExpr = NULL;
1612 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1613 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1614 else
1615 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1616
1617 if (DRExpr) {
1618 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1619 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Douglas Gregord2baafd2008-10-21 16:13:35 +00001620 }
1621
Douglas Gregord2baafd2008-10-21 16:13:35 +00001622 if (Ovl) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001623 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1624 RParenLoc);
1625 if (!FDecl)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001626 return true;
1627
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001628 // Update Fn to refer to the actual function selected.
Douglas Gregor566782a2009-01-06 05:10:23 +00001629 Expr *NewFn = 0;
1630 if (QualifiedDeclRefExpr *QDRExpr = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
1631 NewFn = new QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1632 QDRExpr->getLocation(), false, false,
1633 QDRExpr->getSourceRange().getBegin());
1634 else
1635 NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1636 Fn->getSourceRange().getBegin());
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001637 Fn->Destroy(Context);
1638 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001639 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001640
1641 // Promote the function operand.
1642 UsualUnaryConversions(Fn);
1643
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001644 // Make the call expr early, before semantic checks. This guarantees cleanup
1645 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001646 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001647 Context.BoolTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001648
Steve Naroffd6163f32008-09-05 22:11:13 +00001649 const FunctionType *FuncT;
1650 if (!Fn->getType()->isBlockPointerType()) {
1651 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1652 // have type pointer to function".
1653 const PointerType *PT = Fn->getType()->getAsPointerType();
1654 if (PT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001655 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001656 << Fn->getType() << Fn->getSourceRange();
Steve Naroffd6163f32008-09-05 22:11:13 +00001657 FuncT = PT->getPointeeType()->getAsFunctionType();
1658 } else { // This is a block call.
1659 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1660 getAsFunctionType();
1661 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001662 if (FuncT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001663 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001664 << Fn->getType() << Fn->getSourceRange();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001665
1666 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001667 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001668
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001669 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001670 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1671 RParenLoc))
1672 return true;
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001673 } else {
1674 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1675
Steve Naroffdb65e052007-08-28 23:30:39 +00001676 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001677 for (unsigned i = 0; i != NumArgs; i++) {
1678 Expr *Arg = Args[i];
1679 DefaultArgumentPromotion(Arg);
1680 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001681 }
Chris Lattner4b009652007-07-25 00:24:17 +00001682 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001683
Douglas Gregor3257fb52008-12-22 05:46:06 +00001684 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1685 if (!Method->isStatic())
1686 return Diag(LParenLoc, diag::err_member_call_without_object)
1687 << Fn->getSourceRange();
1688
Chris Lattner2e64c072007-08-10 20:18:51 +00001689 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001690 if (FDecl)
1691 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001692
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001693 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001694}
1695
1696Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001697ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001698 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001699 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001700 QualType literalType = QualType::getFromOpaquePtr(Ty);
1701 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001702 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001703 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001704
Eli Friedman8c2173d2008-05-20 05:22:08 +00001705 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001706 if (literalType->isVariableArrayType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001707 return Diag(LParenLoc, diag::err_variable_object_no_init)
1708 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001709 } else if (literalType->isIncompleteType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001710 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +00001711 << literalType
Chris Lattner8ba580c2008-11-19 05:08:23 +00001712 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001713 }
1714
Douglas Gregor6428e762008-11-05 15:29:30 +00001715 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Chris Lattner271d4c22008-11-24 05:29:24 +00001716 DeclarationName()))
Steve Naroff92590f92008-01-09 20:58:06 +00001717 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001718
Chris Lattnere5cb5862008-12-04 23:50:19 +00001719 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001720 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001721 if (CheckForConstantInitializer(literalExpr, literalType))
1722 return true;
1723 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001724 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1725 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001726}
1727
1728Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001729ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001730 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001731 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001732 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001733
Steve Naroff0acc9c92007-09-15 18:49:24 +00001734 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001735 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001736
Chris Lattner71ca8c82008-10-26 23:43:26 +00001737 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1738 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001739 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1740 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001741}
1742
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001743/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001744bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001745 UsualUnaryConversions(castExpr);
1746
1747 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1748 // type needs to be scalar.
1749 if (castType->isVoidType()) {
1750 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001751 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1752 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001753 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1754 // GCC struct/union extension: allow cast to self.
1755 if (Context.getCanonicalType(castType) !=
1756 Context.getCanonicalType(castExpr->getType()) ||
1757 (!castType->isStructureType() && !castType->isUnionType())) {
1758 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001759 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001760 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001761 }
1762
1763 // accept this, but emit an ext-warn.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001764 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001765 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001766 } else if (!castExpr->getType()->isScalarType() &&
1767 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001768 return Diag(castExpr->getLocStart(),
1769 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001770 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001771 } else if (castExpr->getType()->isVectorType()) {
1772 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1773 return true;
1774 } else if (castType->isVectorType()) {
1775 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1776 return true;
1777 }
1778 return false;
1779}
1780
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001781bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001782 assert(VectorTy->isVectorType() && "Not a vector type!");
1783
1784 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001785 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001786 return Diag(R.getBegin(),
1787 Ty->isVectorType() ?
1788 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00001789 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001790 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001791 } else
1792 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001793 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001794 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001795
1796 return false;
1797}
1798
Chris Lattner4b009652007-07-25 00:24:17 +00001799Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001800ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001801 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001802 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001803
1804 Expr *castExpr = static_cast<Expr*>(Op);
1805 QualType castType = QualType::getFromOpaquePtr(Ty);
1806
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001807 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1808 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00001809 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001810}
1811
Chris Lattner98a425c2007-11-26 01:40:58 +00001812/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1813/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001814inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1815 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1816 UsualUnaryConversions(cond);
1817 UsualUnaryConversions(lex);
1818 UsualUnaryConversions(rex);
1819 QualType condT = cond->getType();
1820 QualType lexT = lex->getType();
1821 QualType rexT = rex->getType();
1822
1823 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001824 if (!cond->isTypeDependent()) {
1825 if (!condT->isScalarType()) { // C99 6.5.15p2
1826 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
1827 return QualType();
1828 }
Chris Lattner4b009652007-07-25 00:24:17 +00001829 }
Chris Lattner992ae932008-01-06 22:42:25 +00001830
1831 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001832 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
1833 return Context.DependentTy;
1834
Chris Lattner992ae932008-01-06 22:42:25 +00001835 // If both operands have arithmetic type, do the usual arithmetic conversions
1836 // to find a common type: C99 6.5.15p3,5.
1837 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001838 UsualArithmeticConversions(lex, rex);
1839 return lex->getType();
1840 }
Chris Lattner992ae932008-01-06 22:42:25 +00001841
1842 // If both operands are the same structure or union type, the result is that
1843 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001844 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001845 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001846 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001847 // "If both the operands have structure or union type, the result has
1848 // that type." This implies that CV qualifiers are dropped.
1849 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001850 }
Chris Lattner992ae932008-01-06 22:42:25 +00001851
1852 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001853 // The following || allows only one side to be void (a GCC-ism).
1854 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001855 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001856 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
1857 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00001858 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001859 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
1860 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00001861 ImpCastExprToType(lex, Context.VoidTy);
1862 ImpCastExprToType(rex, Context.VoidTy);
1863 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001864 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001865 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1866 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001867 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1868 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001869 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001870 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001871 return lexT;
1872 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001873 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1874 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001875 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001876 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001877 return rexT;
1878 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001879 // Handle the case where both operands are pointers before we handle null
1880 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001881 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1882 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1883 // get the "pointed to" types
1884 QualType lhptee = LHSPT->getPointeeType();
1885 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001886
Chris Lattner71225142007-07-31 21:27:01 +00001887 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1888 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001889 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001890 // Figure out necessary qualifiers (C99 6.5.15p6)
1891 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001892 QualType destType = Context.getPointerType(destPointee);
1893 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1894 ImpCastExprToType(rex, destType); // promote to void*
1895 return destType;
1896 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001897 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001898 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001899 QualType destType = Context.getPointerType(destPointee);
1900 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1901 ImpCastExprToType(rex, destType); // promote to void*
1902 return destType;
1903 }
Chris Lattner4b009652007-07-25 00:24:17 +00001904
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001905 QualType compositeType = lexT;
1906
1907 // If either type is an Objective-C object type then check
1908 // compatibility according to Objective-C.
1909 if (Context.isObjCObjectPointerType(lexT) ||
1910 Context.isObjCObjectPointerType(rexT)) {
1911 // If both operands are interfaces and either operand can be
1912 // assigned to the other, use that type as the composite
1913 // type. This allows
1914 // xxx ? (A*) a : (B*) b
1915 // where B is a subclass of A.
1916 //
1917 // Additionally, as for assignment, if either type is 'id'
1918 // allow silent coercion. Finally, if the types are
1919 // incompatible then make sure to use 'id' as the composite
1920 // type so the result is acceptable for sending messages to.
1921
1922 // FIXME: This code should not be localized to here. Also this
1923 // should use a compatible check instead of abusing the
1924 // canAssignObjCInterfaces code.
1925 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1926 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1927 if (LHSIface && RHSIface &&
1928 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1929 compositeType = lexT;
1930 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00001931 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001932 compositeType = rexT;
1933 } else if (Context.isObjCIdType(lhptee) ||
1934 Context.isObjCIdType(rhptee)) {
1935 // FIXME: This code looks wrong, because isObjCIdType checks
1936 // the struct but getObjCIdType returns the pointer to
1937 // struct. This is horrible and should be fixed.
1938 compositeType = Context.getObjCIdType();
1939 } else {
1940 QualType incompatTy = Context.getObjCIdType();
1941 ImpCastExprToType(lex, incompatTy);
1942 ImpCastExprToType(rex, incompatTy);
1943 return incompatTy;
1944 }
1945 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1946 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00001947 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001948 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001949 // In this situation, we assume void* type. No especially good
1950 // reason, but this is what gcc does, and we do have to pick
1951 // to get a consistent AST.
1952 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001953 ImpCastExprToType(lex, incompatTy);
1954 ImpCastExprToType(rex, incompatTy);
1955 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001956 }
1957 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001958 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1959 // differently qualified versions of compatible types, the result type is
1960 // a pointer to an appropriately qualified version of the *composite*
1961 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001962 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001963 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001964 ImpCastExprToType(lex, compositeType);
1965 ImpCastExprToType(rex, compositeType);
1966 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001967 }
Chris Lattner4b009652007-07-25 00:24:17 +00001968 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001969 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1970 // evaluates to "struct objc_object *" (and is handled above when comparing
1971 // id with statically typed objects).
1972 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1973 // GCC allows qualified id and any Objective-C type to devolve to
1974 // id. Currently localizing to here until clear this should be
1975 // part of ObjCQualifiedIdTypesAreCompatible.
1976 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1977 (lexT->isObjCQualifiedIdType() &&
1978 Context.isObjCObjectPointerType(rexT)) ||
1979 (rexT->isObjCQualifiedIdType() &&
1980 Context.isObjCObjectPointerType(lexT))) {
1981 // FIXME: This is not the correct composite type. This only
1982 // happens to work because id can more or less be used anywhere,
1983 // however this may change the type of method sends.
1984 // FIXME: gcc adds some type-checking of the arguments and emits
1985 // (confusing) incompatible comparison warnings in some
1986 // cases. Investigate.
1987 QualType compositeType = Context.getObjCIdType();
1988 ImpCastExprToType(lex, compositeType);
1989 ImpCastExprToType(rex, compositeType);
1990 return compositeType;
1991 }
1992 }
1993
Steve Naroff3eac7692008-09-10 19:17:48 +00001994 // Selection between block pointer types is ok as long as they are the same.
1995 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1996 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1997 return lexT;
1998
Chris Lattner992ae932008-01-06 22:42:25 +00001999 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002000 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002001 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002002 return QualType();
2003}
2004
Steve Naroff87d58b42007-09-16 03:34:24 +00002005/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002006/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00002007Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002008 SourceLocation ColonLoc,
2009 ExprTy *Cond, ExprTy *LHS,
2010 ExprTy *RHS) {
2011 Expr *CondExpr = (Expr *) Cond;
2012 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00002013
2014 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2015 // was the condition.
2016 bool isLHSNull = LHSExpr == 0;
2017 if (isLHSNull)
2018 LHSExpr = CondExpr;
2019
Chris Lattner4b009652007-07-25 00:24:17 +00002020 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
2021 RHSExpr, QuestionLoc);
2022 if (result.isNull())
2023 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00002024 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
2025 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00002026}
2027
Chris Lattner4b009652007-07-25 00:24:17 +00002028
2029// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2030// being closely modeled after the C99 spec:-). The odd characteristic of this
2031// routine is it effectively iqnores the qualifiers on the top level pointee.
2032// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2033// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002034Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002035Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2036 QualType lhptee, rhptee;
2037
2038 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002039 lhptee = lhsType->getAsPointerType()->getPointeeType();
2040 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002041
2042 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002043 lhptee = Context.getCanonicalType(lhptee);
2044 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002045
Chris Lattner005ed752008-01-04 18:04:52 +00002046 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002047
2048 // C99 6.5.16.1p1: This following citation is common to constraints
2049 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2050 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002051 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002052 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002053 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002054
2055 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2056 // incomplete type and the other is a pointer to a qualified or unqualified
2057 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002058 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002059 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002060 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002061
2062 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002063 assert(rhptee->isFunctionType());
2064 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002065 }
2066
2067 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002068 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002069 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002070
2071 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002072 assert(lhptee->isFunctionType());
2073 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002074 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002075
2076 // Check for ObjC interfaces
2077 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2078 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2079 if (LHSIface && RHSIface &&
2080 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2081 return ConvTy;
2082
2083 // ID acts sort of like void* for ObjC interfaces
2084 if (LHSIface && Context.isObjCIdType(rhptee))
2085 return ConvTy;
2086 if (RHSIface && Context.isObjCIdType(lhptee))
2087 return ConvTy;
2088
Chris Lattner4b009652007-07-25 00:24:17 +00002089 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2090 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002091 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2092 rhptee.getUnqualifiedType()))
2093 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002094 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002095}
2096
Steve Naroff3454b6c2008-09-04 15:10:53 +00002097/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2098/// block pointer types are compatible or whether a block and normal pointer
2099/// are compatible. It is more restrict than comparing two function pointer
2100// types.
2101Sema::AssignConvertType
2102Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2103 QualType rhsType) {
2104 QualType lhptee, rhptee;
2105
2106 // get the "pointed to" type (ignoring qualifiers at the top level)
2107 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2108 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2109
2110 // make sure we operate on the canonical type
2111 lhptee = Context.getCanonicalType(lhptee);
2112 rhptee = Context.getCanonicalType(rhptee);
2113
2114 AssignConvertType ConvTy = Compatible;
2115
2116 // For blocks we enforce that qualifiers are identical.
2117 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2118 ConvTy = CompatiblePointerDiscardsQualifiers;
2119
2120 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2121 return IncompatibleBlockPointer;
2122 return ConvTy;
2123}
2124
Chris Lattner4b009652007-07-25 00:24:17 +00002125/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2126/// has code to accommodate several GCC extensions when type checking
2127/// pointers. Here are some objectionable examples that GCC considers warnings:
2128///
2129/// int a, *pint;
2130/// short *pshort;
2131/// struct foo *pfoo;
2132///
2133/// pint = pshort; // warning: assignment from incompatible pointer type
2134/// a = pint; // warning: assignment makes integer from pointer without a cast
2135/// pint = a; // warning: assignment makes pointer from integer without a cast
2136/// pint = pfoo; // warning: assignment from incompatible pointer type
2137///
2138/// As a result, the code for dealing with pointers is more complex than the
2139/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002140///
Chris Lattner005ed752008-01-04 18:04:52 +00002141Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002142Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002143 // Get canonical types. We're not formatting these types, just comparing
2144 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002145 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2146 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002147
2148 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002149 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002150
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002151 // If the left-hand side is a reference type, then we are in a
2152 // (rare!) case where we've allowed the use of references in C,
2153 // e.g., as a parameter type in a built-in function. In this case,
2154 // just make sure that the type referenced is compatible with the
2155 // right-hand side type. The caller is responsible for adjusting
2156 // lhsType so that the resulting expression does not have reference
2157 // type.
2158 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2159 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002160 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002161 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002162 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002163
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002164 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2165 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002166 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002167 // Relax integer conversions like we do for pointers below.
2168 if (rhsType->isIntegerType())
2169 return IntToPointer;
2170 if (lhsType->isIntegerType())
2171 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002172 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002173 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002174
Nate Begemanc5f0f652008-07-14 18:02:46 +00002175 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002176 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002177 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2178 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002179 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002180
Nate Begemanc5f0f652008-07-14 18:02:46 +00002181 // If we are allowing lax vector conversions, and LHS and RHS are both
2182 // vectors, the total size only needs to be the same. This is a bitcast;
2183 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002184 if (getLangOptions().LaxVectorConversions &&
2185 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002186 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2187 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002188 }
2189 return Incompatible;
2190 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002191
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002192 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002193 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002194
Chris Lattner390564e2008-04-07 06:49:41 +00002195 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002196 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002197 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002198
Chris Lattner390564e2008-04-07 06:49:41 +00002199 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002200 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002201
Steve Naroffa982c712008-09-29 18:10:17 +00002202 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002203 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002204 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002205
2206 // Treat block pointers as objects.
2207 if (getLangOptions().ObjC1 &&
2208 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2209 return Compatible;
2210 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002211 return Incompatible;
2212 }
2213
2214 if (isa<BlockPointerType>(lhsType)) {
2215 if (rhsType->isIntegerType())
2216 return IntToPointer;
2217
Steve Naroffa982c712008-09-29 18:10:17 +00002218 // Treat block pointers as objects.
2219 if (getLangOptions().ObjC1 &&
2220 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2221 return Compatible;
2222
Steve Naroff3454b6c2008-09-04 15:10:53 +00002223 if (rhsType->isBlockPointerType())
2224 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2225
2226 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2227 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002228 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002229 }
Chris Lattner1853da22008-01-04 23:18:45 +00002230 return Incompatible;
2231 }
2232
Chris Lattner390564e2008-04-07 06:49:41 +00002233 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002234 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002235 if (lhsType == Context.BoolTy)
2236 return Compatible;
2237
2238 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002239 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002240
Chris Lattner390564e2008-04-07 06:49:41 +00002241 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002242 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002243
2244 if (isa<BlockPointerType>(lhsType) &&
2245 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002246 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002247 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002248 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002249
Chris Lattner1853da22008-01-04 23:18:45 +00002250 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002251 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002252 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002253 }
2254 return Incompatible;
2255}
2256
Chris Lattner005ed752008-01-04 18:04:52 +00002257Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002258Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002259 if (getLangOptions().CPlusPlus) {
2260 if (!lhsType->isRecordType()) {
2261 // C++ 5.17p3: If the left operand is not of class type, the
2262 // expression is implicitly converted (C++ 4) to the
2263 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002264 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2265 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002266 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002267 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002268 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002269 }
2270
2271 // FIXME: Currently, we fall through and treat C++ classes like C
2272 // structures.
2273 }
2274
Steve Naroffcdee22d2007-11-27 17:58:44 +00002275 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2276 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002277 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2278 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002279 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002280 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002281 return Compatible;
2282 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002283
2284 // We don't allow conversion of non-null-pointer constants to integers.
2285 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2286 return IntToBlockPointer;
2287
Chris Lattner5f505bf2007-10-16 02:55:40 +00002288 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002289 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002290 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002291 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002292 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002293 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002294 if (!lhsType->isReferenceType())
2295 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002296
Chris Lattner005ed752008-01-04 18:04:52 +00002297 Sema::AssignConvertType result =
2298 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002299
2300 // C99 6.5.16.1p2: The value of the right operand is converted to the
2301 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002302 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2303 // so that we can use references in built-in functions even in C.
2304 // The getNonReferenceType() call makes sure that the resulting expression
2305 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002306 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002307 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002308 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002309}
2310
Chris Lattner005ed752008-01-04 18:04:52 +00002311Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002312Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2313 return CheckAssignmentConstraints(lhsType, rhsType);
2314}
2315
Chris Lattner1eafdea2008-11-18 01:30:42 +00002316QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002317 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002318 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002319 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002320 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002321}
2322
Chris Lattner1eafdea2008-11-18 01:30:42 +00002323inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002324 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002325 // For conversion purposes, we ignore any qualifiers.
2326 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002327 QualType lhsType =
2328 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2329 QualType rhsType =
2330 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002331
Nate Begemanc5f0f652008-07-14 18:02:46 +00002332 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002333 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002334 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002335
Nate Begemanc5f0f652008-07-14 18:02:46 +00002336 // Handle the case of a vector & extvector type of the same size and element
2337 // type. It would be nice if we only had one vector type someday.
2338 if (getLangOptions().LaxVectorConversions)
2339 if (const VectorType *LV = lhsType->getAsVectorType())
2340 if (const VectorType *RV = rhsType->getAsVectorType())
2341 if (LV->getElementType() == RV->getElementType() &&
2342 LV->getNumElements() == RV->getNumElements())
2343 return lhsType->isExtVectorType() ? lhsType : rhsType;
2344
2345 // If the lhs is an extended vector and the rhs is a scalar of the same type
2346 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002347 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002348 QualType eltType = V->getElementType();
2349
2350 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2351 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2352 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002353 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002354 return lhsType;
2355 }
2356 }
2357
Nate Begemanc5f0f652008-07-14 18:02:46 +00002358 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002359 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002360 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002361 QualType eltType = V->getElementType();
2362
2363 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2364 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2365 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002366 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002367 return rhsType;
2368 }
2369 }
2370
Chris Lattner4b009652007-07-25 00:24:17 +00002371 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002372 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002373 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002374 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002375 return QualType();
2376}
2377
2378inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002379 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002380{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002381 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002382 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002383
Steve Naroff8f708362007-08-24 19:07:16 +00002384 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002385
Chris Lattner4b009652007-07-25 00:24:17 +00002386 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002387 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002388 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002389}
2390
2391inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002392 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002393{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002394 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2395 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2396 return CheckVectorOperands(Loc, lex, rex);
2397 return InvalidOperands(Loc, lex, rex);
2398 }
Chris Lattner4b009652007-07-25 00:24:17 +00002399
Steve Naroff8f708362007-08-24 19:07:16 +00002400 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002401
Chris Lattner4b009652007-07-25 00:24:17 +00002402 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002403 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002404 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002405}
2406
2407inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002408 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002409{
2410 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002411 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002412
Steve Naroff8f708362007-08-24 19:07:16 +00002413 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002414
Chris Lattner4b009652007-07-25 00:24:17 +00002415 // handle the common case first (both operands are arithmetic).
2416 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002417 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002418
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002419 // Put any potential pointer into PExp
2420 Expr* PExp = lex, *IExp = rex;
2421 if (IExp->getType()->isPointerType())
2422 std::swap(PExp, IExp);
2423
2424 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2425 if (IExp->getType()->isIntegerType()) {
2426 // Check for arithmetic on pointers to incomplete types
2427 if (!PTy->getPointeeType()->isObjectType()) {
2428 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002429 Diag(Loc, diag::ext_gnu_void_ptr)
2430 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002431 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002432 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002433 << lex->getType() << lex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002434 return QualType();
2435 }
2436 }
2437 return PExp->getType();
2438 }
2439 }
2440
Chris Lattner1eafdea2008-11-18 01:30:42 +00002441 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002442}
2443
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002444// C99 6.5.6
2445QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002446 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002447 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002448 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002449
Steve Naroff8f708362007-08-24 19:07:16 +00002450 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002451
Chris Lattnerf6da2912007-12-09 21:53:25 +00002452 // Enforce type constraints: C99 6.5.6p3.
2453
2454 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002455 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002456 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002457
2458 // Either ptr - int or ptr - ptr.
2459 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002460 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002461
Chris Lattnerf6da2912007-12-09 21:53:25 +00002462 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002463 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002464 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002465 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002466 Diag(Loc, diag::ext_gnu_void_ptr)
2467 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002468 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002469 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002470 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002471 return QualType();
2472 }
2473 }
2474
2475 // The result type of a pointer-int computation is the pointer type.
2476 if (rex->getType()->isIntegerType())
2477 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002478
Chris Lattnerf6da2912007-12-09 21:53:25 +00002479 // Handle pointer-pointer subtractions.
2480 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002481 QualType rpointee = RHSPTy->getPointeeType();
2482
Chris Lattnerf6da2912007-12-09 21:53:25 +00002483 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002484 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002485 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002486 if (rpointee->isVoidType()) {
2487 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002488 Diag(Loc, diag::ext_gnu_void_ptr)
2489 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002490 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002491 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002492 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002493 return QualType();
2494 }
2495 }
2496
2497 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002498 if (!Context.typesAreCompatible(
2499 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2500 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002501 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002502 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002503 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002504 return QualType();
2505 }
2506
2507 return Context.getPointerDiffType();
2508 }
2509 }
2510
Chris Lattner1eafdea2008-11-18 01:30:42 +00002511 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002512}
2513
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002514// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002515QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002516 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002517 // C99 6.5.7p2: Each of the operands shall have integer type.
2518 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002519 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002520
Chris Lattner2c8bff72007-12-12 05:47:28 +00002521 // Shifts don't perform usual arithmetic conversions, they just do integer
2522 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002523 if (!isCompAssign)
2524 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002525 UsualUnaryConversions(rex);
2526
2527 // "The type of the result is that of the promoted left operand."
2528 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002529}
2530
Eli Friedman0d9549b2008-08-22 00:56:42 +00002531static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2532 ASTContext& Context) {
2533 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2534 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2535 // ID acts sort of like void* for ObjC interfaces
2536 if (LHSIface && Context.isObjCIdType(RHS))
2537 return true;
2538 if (RHSIface && Context.isObjCIdType(LHS))
2539 return true;
2540 if (!LHSIface || !RHSIface)
2541 return false;
2542 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2543 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2544}
2545
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002546// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002547QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002548 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002549 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002550 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002551
Chris Lattner254f3bc2007-08-26 01:18:55 +00002552 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002553 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2554 UsualArithmeticConversions(lex, rex);
2555 else {
2556 UsualUnaryConversions(lex);
2557 UsualUnaryConversions(rex);
2558 }
Chris Lattner4b009652007-07-25 00:24:17 +00002559 QualType lType = lex->getType();
2560 QualType rType = rex->getType();
2561
Ted Kremenek486509e2007-10-29 17:13:39 +00002562 // For non-floating point types, check for self-comparisons of the form
2563 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2564 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002565 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002566 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2567 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002568 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002569 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002570 }
2571
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002572 // The result of comparisons is 'bool' in C++, 'int' in C.
2573 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2574
Chris Lattner254f3bc2007-08-26 01:18:55 +00002575 if (isRelational) {
2576 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002577 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002578 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002579 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002580 if (lType->isFloatingType()) {
2581 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002582 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002583 }
2584
Chris Lattner254f3bc2007-08-26 01:18:55 +00002585 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002586 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002587 }
Chris Lattner4b009652007-07-25 00:24:17 +00002588
Chris Lattner22be8422007-08-26 01:10:14 +00002589 bool LHSIsNull = lex->isNullPointerConstant(Context);
2590 bool RHSIsNull = rex->isNullPointerConstant(Context);
2591
Chris Lattner254f3bc2007-08-26 01:18:55 +00002592 // All of the following pointer related warnings are GCC extensions, except
2593 // when handling null pointer constants. One day, we can consider making them
2594 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002595 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002596 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002597 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002598 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002599 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002600
Steve Naroff3b435622007-11-13 14:57:38 +00002601 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002602 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2603 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002604 RCanPointeeTy.getUnqualifiedType()) &&
2605 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002606 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002607 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002608 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002609 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002610 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002611 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002612 // Handle block pointer types.
2613 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2614 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2615 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2616
2617 if (!LHSIsNull && !RHSIsNull &&
2618 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002619 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002620 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002621 }
2622 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002623 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002624 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002625 // Allow block pointers to be compared with null pointer constants.
2626 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2627 (lType->isPointerType() && rType->isBlockPointerType())) {
2628 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002629 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002630 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002631 }
2632 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002633 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002634 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002635
Steve Naroff936c4362008-06-03 14:04:54 +00002636 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002637 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002638 const PointerType *LPT = lType->getAsPointerType();
2639 const PointerType *RPT = rType->getAsPointerType();
2640 bool LPtrToVoid = LPT ?
2641 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2642 bool RPtrToVoid = RPT ?
2643 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2644
2645 if (!LPtrToVoid && !RPtrToVoid &&
2646 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002647 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002648 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002649 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002650 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002651 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002652 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002653 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002654 }
Steve Naroff936c4362008-06-03 14:04:54 +00002655 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2656 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002657 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002658 } else {
2659 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002660 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002661 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002662 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002663 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002664 }
Steve Naroff936c4362008-06-03 14:04:54 +00002665 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002666 }
Steve Naroff936c4362008-06-03 14:04:54 +00002667 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2668 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002669 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002670 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002671 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002672 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002673 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002674 }
Steve Naroff936c4362008-06-03 14:04:54 +00002675 if (lType->isIntegerType() &&
2676 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002677 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002678 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002679 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002680 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002681 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002682 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002683 // Handle block pointers.
2684 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2685 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002686 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002687 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002688 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002689 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002690 }
2691 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2692 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002693 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002694 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002695 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002696 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002697 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002698 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002699}
2700
Nate Begemanc5f0f652008-07-14 18:02:46 +00002701/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2702/// operates on extended vector types. Instead of producing an IntTy result,
2703/// like a scalar comparison, a vector comparison produces a vector of integer
2704/// types.
2705QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002706 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002707 bool isRelational) {
2708 // Check to make sure we're operating on vectors of the same type and width,
2709 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002710 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002711 if (vType.isNull())
2712 return vType;
2713
2714 QualType lType = lex->getType();
2715 QualType rType = rex->getType();
2716
2717 // For non-floating point types, check for self-comparisons of the form
2718 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2719 // often indicate logic errors in the program.
2720 if (!lType->isFloatingType()) {
2721 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2722 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2723 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002724 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002725 }
2726
2727 // Check for comparisons of floating point operands using != and ==.
2728 if (!isRelational && lType->isFloatingType()) {
2729 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002730 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002731 }
2732
2733 // Return the type for the comparison, which is the same as vector type for
2734 // integer vectors, or an integer type of identical size and number of
2735 // elements for floating point vectors.
2736 if (lType->isIntegerType())
2737 return lType;
2738
2739 const VectorType *VTy = lType->getAsVectorType();
2740
2741 // FIXME: need to deal with non-32b int / non-64b long long
2742 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2743 if (TypeSize == 32) {
2744 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2745 }
2746 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2747 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2748}
2749
Chris Lattner4b009652007-07-25 00:24:17 +00002750inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002751 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002752{
2753 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002754 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002755
Steve Naroff8f708362007-08-24 19:07:16 +00002756 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002757
2758 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002759 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002760 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002761}
2762
2763inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00002764 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00002765{
2766 UsualUnaryConversions(lex);
2767 UsualUnaryConversions(rex);
2768
Eli Friedmanbea3f842008-05-13 20:16:47 +00002769 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002770 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002771 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002772}
2773
Chris Lattner4c2642c2008-11-18 01:22:49 +00002774/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2775/// emit an error and return true. If so, return false.
2776static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2777 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2778 if (IsLV == Expr::MLV_Valid)
2779 return false;
2780
2781 unsigned Diag = 0;
2782 bool NeedType = false;
2783 switch (IsLV) { // C99 6.5.16p2
2784 default: assert(0 && "Unknown result from isModifiableLvalue!");
2785 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00002786 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002787 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2788 NeedType = true;
2789 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002790 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002791 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2792 NeedType = true;
2793 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00002794 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002795 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2796 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002797 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002798 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2799 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002800 case Expr::MLV_IncompleteType:
2801 case Expr::MLV_IncompleteVoidType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002802 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2803 NeedType = true;
2804 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002805 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002806 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2807 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00002808 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002809 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2810 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00002811 case Expr::MLV_ReadonlyProperty:
2812 Diag = diag::error_readonly_property_assignment;
2813 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00002814 case Expr::MLV_NoSetterProperty:
2815 Diag = diag::error_nosetter_property_assignment;
2816 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002817 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002818
Chris Lattner4c2642c2008-11-18 01:22:49 +00002819 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002820 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002821 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00002822 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002823 return true;
2824}
2825
2826
2827
2828// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00002829QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
2830 SourceLocation Loc,
2831 QualType CompoundType) {
2832 // Verify that LHS is a modifiable lvalue, and emit error if not.
2833 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00002834 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00002835
2836 QualType LHSType = LHS->getType();
2837 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00002838
Chris Lattner005ed752008-01-04 18:04:52 +00002839 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002840 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00002841 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002842 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner34c85082008-08-21 18:04:13 +00002843
2844 // If the RHS is a unary plus or minus, check to see if they = and + are
2845 // right next to each other. If so, the user may have typo'd "x =+ 4"
2846 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002847 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00002848 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2849 RHSCheck = ICE->getSubExpr();
2850 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2851 if ((UO->getOpcode() == UnaryOperator::Plus ||
2852 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00002853 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00002854 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002855 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00002856 Diag(Loc, diag::warn_not_compound_assign)
2857 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
2858 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00002859 }
2860 } else {
2861 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00002862 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00002863 }
Chris Lattner005ed752008-01-04 18:04:52 +00002864
Chris Lattner1eafdea2008-11-18 01:30:42 +00002865 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
2866 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00002867 return QualType();
2868
Chris Lattner4b009652007-07-25 00:24:17 +00002869 // C99 6.5.16p3: The type of an assignment expression is the type of the
2870 // left operand unless the left operand has qualified type, in which case
2871 // it is the unqualified version of the type of the left operand.
2872 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2873 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002874 // C++ 5.17p1: the type of the assignment expression is that of its left
2875 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002876 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002877}
2878
Chris Lattner1eafdea2008-11-18 01:30:42 +00002879// C99 6.5.17
2880QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
2881 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00002882
2883 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002884 DefaultFunctionArrayConversion(RHS);
2885 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002886}
2887
2888/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2889/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00002890QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
2891 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00002892 QualType ResType = Op->getType();
2893 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002894
Sebastian Redl0440c8c2008-12-20 09:35:34 +00002895 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
2896 // Decrement of bool is not allowed.
2897 if (!isInc) {
2898 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
2899 return QualType();
2900 }
2901 // Increment of bool sets it to true, but is deprecated.
2902 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
2903 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00002904 // OK!
2905 } else if (const PointerType *PT = ResType->getAsPointerType()) {
2906 // C99 6.5.2.4p2, 6.5.6p2
2907 if (PT->getPointeeType()->isObjectType()) {
2908 // Pointer to object is ok!
2909 } else if (PT->getPointeeType()->isVoidType()) {
2910 // Pointer to void is extension.
2911 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
2912 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +00002913 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002914 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002915 return QualType();
2916 }
Chris Lattnere65182c2008-11-21 07:05:48 +00002917 } else if (ResType->isComplexType()) {
2918 // C99 does not support ++/-- on complex types, we allow as an extension.
2919 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002920 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002921 } else {
2922 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002923 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002924 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002925 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002926 // At this point, we know we have a real, complex or pointer type.
2927 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00002928 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00002929 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00002930 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00002931}
2932
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002933/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002934/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002935/// where the declaration is needed for type checking. We only need to
2936/// handle cases when the expression references a function designator
2937/// or is an lvalue. Here are some examples:
2938/// - &(x) => x
2939/// - &*****f => f for f a function designator.
2940/// - &s.xx => s
2941/// - &s.zz[1].yy -> s, if zz is an array
2942/// - *(x + 1) -> x, if x is an array
2943/// - &"123"[2] -> 0
2944/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002945static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002946 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002947 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00002948 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002949 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002950 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002951 // Fields cannot be declared with a 'register' storage class.
2952 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002953 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002954 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002955 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002956 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002957 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002958
Douglas Gregord2baafd2008-10-21 16:13:35 +00002959 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002960 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002961 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002962 return 0;
2963 else
2964 return VD;
2965 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002966 case Stmt::UnaryOperatorClass: {
2967 UnaryOperator *UO = cast<UnaryOperator>(E);
2968
2969 switch(UO->getOpcode()) {
2970 case UnaryOperator::Deref: {
2971 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002972 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2973 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2974 if (!VD || VD->getType()->isPointerType())
2975 return 0;
2976 return VD;
2977 }
2978 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002979 }
2980 case UnaryOperator::Real:
2981 case UnaryOperator::Imag:
2982 case UnaryOperator::Extension:
2983 return getPrimaryDecl(UO->getSubExpr());
2984 default:
2985 return 0;
2986 }
2987 }
2988 case Stmt::BinaryOperatorClass: {
2989 BinaryOperator *BO = cast<BinaryOperator>(E);
2990
2991 // Handle cases involving pointer arithmetic. The result of an
2992 // Assign or AddAssign is not an lvalue so they can be ignored.
2993
2994 // (x + n) or (n + x) => x
2995 if (BO->getOpcode() == BinaryOperator::Add) {
2996 if (BO->getLHS()->getType()->isPointerType()) {
2997 return getPrimaryDecl(BO->getLHS());
2998 } else if (BO->getRHS()->getType()->isPointerType()) {
2999 return getPrimaryDecl(BO->getRHS());
3000 }
3001 }
3002
3003 return 0;
3004 }
Chris Lattner4b009652007-07-25 00:24:17 +00003005 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003006 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003007 case Stmt::ImplicitCastExprClass:
3008 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003009 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003010 default:
3011 return 0;
3012 }
3013}
3014
3015/// CheckAddressOfOperand - The operand of & must be either a function
3016/// designator or an lvalue designating an object. If it is an lvalue, the
3017/// object cannot be declared with storage class register or be a bit field.
3018/// Note: The usual conversions are *not* applied to the operand of the &
3019/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003020/// In C++, the operand might be an overloaded function name, in which case
3021/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003022QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003023 if (op->isTypeDependent())
3024 return Context.DependentTy;
3025
Steve Naroff9c6c3592008-01-13 17:10:08 +00003026 if (getLangOptions().C99) {
3027 // Implement C99-only parts of addressof rules.
3028 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3029 if (uOp->getOpcode() == UnaryOperator::Deref)
3030 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3031 // (assuming the deref expression is valid).
3032 return uOp->getSubExpr()->getType();
3033 }
3034 // Technically, there should be a check for array subscript
3035 // expressions here, but the result of one is always an lvalue anyway.
3036 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003037 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003038 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003039
Chris Lattner4b009652007-07-25 00:24:17 +00003040 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003041 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3042 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003043 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3044 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003045 return QualType();
3046 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003047 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003048 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3049 if (Field->isBitField()) {
3050 Diag(OpLoc, diag::err_typecheck_address_of)
3051 << "bit-field" << op->getSourceRange();
3052 return QualType();
3053 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003054 }
3055 // Check for Apple extension for accessing vector components.
3056 } else if (isa<ArraySubscriptExpr>(op) &&
3057 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003058 Diag(OpLoc, diag::err_typecheck_address_of)
3059 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003060 return QualType();
3061 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003062 // We have an lvalue with a decl. Make sure the decl is not declared
3063 // with the register storage-class specifier.
3064 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3065 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003066 Diag(OpLoc, diag::err_typecheck_address_of)
3067 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003068 return QualType();
3069 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003070 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003071 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003072 } else if (isa<FieldDecl>(dcl)) {
3073 // Okay: we can take the address of a field.
Nuno Lopesdf239522008-12-16 22:58:26 +00003074 } else if (isa<FunctionDecl>(dcl)) {
3075 // Okay: we can take the address of a function.
Douglas Gregor5b82d612008-12-10 21:26:49 +00003076 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003077 else
Chris Lattner4b009652007-07-25 00:24:17 +00003078 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003079 }
Chris Lattnera55e3212008-07-27 00:48:22 +00003080
Chris Lattner4b009652007-07-25 00:24:17 +00003081 // If the operand has type "type", the result has type "pointer to type".
3082 return Context.getPointerType(op->getType());
3083}
3084
Chris Lattnerda5c0872008-11-23 09:13:29 +00003085QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3086 UsualUnaryConversions(Op);
3087 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003088
Chris Lattnerda5c0872008-11-23 09:13:29 +00003089 // Note that per both C89 and C99, this is always legal, even if ptype is an
3090 // incomplete type or void. It would be possible to warn about dereferencing
3091 // a void pointer, but it's completely well-defined, and such a warning is
3092 // unlikely to catch any mistakes.
3093 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003094 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003095
Chris Lattner77d52da2008-11-20 06:06:08 +00003096 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003097 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003098 return QualType();
3099}
3100
3101static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3102 tok::TokenKind Kind) {
3103 BinaryOperator::Opcode Opc;
3104 switch (Kind) {
3105 default: assert(0 && "Unknown binop!");
3106 case tok::star: Opc = BinaryOperator::Mul; break;
3107 case tok::slash: Opc = BinaryOperator::Div; break;
3108 case tok::percent: Opc = BinaryOperator::Rem; break;
3109 case tok::plus: Opc = BinaryOperator::Add; break;
3110 case tok::minus: Opc = BinaryOperator::Sub; break;
3111 case tok::lessless: Opc = BinaryOperator::Shl; break;
3112 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3113 case tok::lessequal: Opc = BinaryOperator::LE; break;
3114 case tok::less: Opc = BinaryOperator::LT; break;
3115 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3116 case tok::greater: Opc = BinaryOperator::GT; break;
3117 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3118 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3119 case tok::amp: Opc = BinaryOperator::And; break;
3120 case tok::caret: Opc = BinaryOperator::Xor; break;
3121 case tok::pipe: Opc = BinaryOperator::Or; break;
3122 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3123 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3124 case tok::equal: Opc = BinaryOperator::Assign; break;
3125 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3126 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3127 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3128 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3129 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3130 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3131 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3132 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3133 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3134 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3135 case tok::comma: Opc = BinaryOperator::Comma; break;
3136 }
3137 return Opc;
3138}
3139
3140static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3141 tok::TokenKind Kind) {
3142 UnaryOperator::Opcode Opc;
3143 switch (Kind) {
3144 default: assert(0 && "Unknown unary op!");
3145 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3146 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3147 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3148 case tok::star: Opc = UnaryOperator::Deref; break;
3149 case tok::plus: Opc = UnaryOperator::Plus; break;
3150 case tok::minus: Opc = UnaryOperator::Minus; break;
3151 case tok::tilde: Opc = UnaryOperator::Not; break;
3152 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003153 case tok::kw___real: Opc = UnaryOperator::Real; break;
3154 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3155 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3156 }
3157 return Opc;
3158}
3159
Douglas Gregord7f915e2008-11-06 23:29:22 +00003160/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3161/// operator @p Opc at location @c TokLoc. This routine only supports
3162/// built-in operations; ActOnBinOp handles overloaded operators.
3163Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3164 unsigned Op,
3165 Expr *lhs, Expr *rhs) {
3166 QualType ResultTy; // Result type of the binary operator.
3167 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3168 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3169
3170 switch (Opc) {
3171 default:
3172 assert(0 && "Unknown binary expr!");
3173 case BinaryOperator::Assign:
3174 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3175 break;
3176 case BinaryOperator::Mul:
3177 case BinaryOperator::Div:
3178 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3179 break;
3180 case BinaryOperator::Rem:
3181 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3182 break;
3183 case BinaryOperator::Add:
3184 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3185 break;
3186 case BinaryOperator::Sub:
3187 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3188 break;
3189 case BinaryOperator::Shl:
3190 case BinaryOperator::Shr:
3191 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3192 break;
3193 case BinaryOperator::LE:
3194 case BinaryOperator::LT:
3195 case BinaryOperator::GE:
3196 case BinaryOperator::GT:
3197 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3198 break;
3199 case BinaryOperator::EQ:
3200 case BinaryOperator::NE:
3201 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3202 break;
3203 case BinaryOperator::And:
3204 case BinaryOperator::Xor:
3205 case BinaryOperator::Or:
3206 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3207 break;
3208 case BinaryOperator::LAnd:
3209 case BinaryOperator::LOr:
3210 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3211 break;
3212 case BinaryOperator::MulAssign:
3213 case BinaryOperator::DivAssign:
3214 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3215 if (!CompTy.isNull())
3216 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3217 break;
3218 case BinaryOperator::RemAssign:
3219 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3220 if (!CompTy.isNull())
3221 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3222 break;
3223 case BinaryOperator::AddAssign:
3224 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3225 if (!CompTy.isNull())
3226 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3227 break;
3228 case BinaryOperator::SubAssign:
3229 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3230 if (!CompTy.isNull())
3231 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3232 break;
3233 case BinaryOperator::ShlAssign:
3234 case BinaryOperator::ShrAssign:
3235 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3236 if (!CompTy.isNull())
3237 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3238 break;
3239 case BinaryOperator::AndAssign:
3240 case BinaryOperator::XorAssign:
3241 case BinaryOperator::OrAssign:
3242 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3243 if (!CompTy.isNull())
3244 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3245 break;
3246 case BinaryOperator::Comma:
3247 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3248 break;
3249 }
3250 if (ResultTy.isNull())
3251 return true;
3252 if (CompTy.isNull())
3253 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
3254 else
3255 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
3256}
3257
Chris Lattner4b009652007-07-25 00:24:17 +00003258// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003259Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3260 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00003261 ExprTy *LHS, ExprTy *RHS) {
3262 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3263 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
3264
Steve Naroff87d58b42007-09-16 03:34:24 +00003265 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3266 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003267
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003268 // If either expression is type-dependent, just build the AST.
3269 // FIXME: We'll need to perform some caching of the result of name
3270 // lookup for operator+.
3271 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3272 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3273 return new CompoundAssignOperator(lhs, rhs, Opc, Context.DependentTy,
3274 Context.DependentTy, TokLoc);
3275 else
3276 return new BinaryOperator(lhs, rhs, Opc, Context.DependentTy, TokLoc);
3277 }
3278
Douglas Gregord7f915e2008-11-06 23:29:22 +00003279 if (getLangOptions().CPlusPlus &&
3280 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3281 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003282 // If this is one of the assignment operators, we only perform
3283 // overload resolution if the left-hand side is a class or
3284 // enumeration type (C++ [expr.ass]p3).
3285 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3286 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3287 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3288 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003289
3290 // Determine which overloaded operator we're dealing with.
3291 static const OverloadedOperatorKind OverOps[] = {
3292 OO_Star, OO_Slash, OO_Percent,
3293 OO_Plus, OO_Minus,
3294 OO_LessLess, OO_GreaterGreater,
3295 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3296 OO_EqualEqual, OO_ExclaimEqual,
3297 OO_Amp,
3298 OO_Caret,
3299 OO_Pipe,
3300 OO_AmpAmp,
3301 OO_PipePipe,
3302 OO_Equal, OO_StarEqual,
3303 OO_SlashEqual, OO_PercentEqual,
3304 OO_PlusEqual, OO_MinusEqual,
3305 OO_LessLessEqual, OO_GreaterGreaterEqual,
3306 OO_AmpEqual, OO_CaretEqual,
3307 OO_PipeEqual,
3308 OO_Comma
3309 };
3310 OverloadedOperatorKind OverOp = OverOps[Opc];
3311
Douglas Gregor5ed15042008-11-18 23:14:02 +00003312 // Add the appropriate overloaded operators (C++ [over.match.oper])
3313 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003314 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003315 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003316 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003317
3318 // Perform overload resolution.
3319 OverloadCandidateSet::iterator Best;
3320 switch (BestViableFunction(CandidateSet, Best)) {
3321 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003322 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003323 FunctionDecl *FnDecl = Best->Function;
3324
Douglas Gregor70d26122008-11-12 17:17:38 +00003325 if (FnDecl) {
3326 // We matched an overloaded operator. Build a call to that
3327 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003328
Douglas Gregor70d26122008-11-12 17:17:38 +00003329 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003330 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3331 if (PerformObjectArgumentInitialization(lhs, Method) ||
3332 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3333 "passing"))
3334 return true;
3335 } else {
3336 // Convert the arguments.
3337 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3338 "passing") ||
3339 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3340 "passing"))
3341 return true;
3342 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003343
Douglas Gregor70d26122008-11-12 17:17:38 +00003344 // Determine the result type
3345 QualType ResultTy
3346 = FnDecl->getType()->getAsFunctionType()->getResultType();
3347 ResultTy = ResultTy.getNonReferenceType();
3348
3349 // Build the actual expression node.
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003350 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3351 SourceLocation());
3352 UsualUnaryConversions(FnExpr);
3353
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003354 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregor70d26122008-11-12 17:17:38 +00003355 } else {
3356 // We matched a built-in operator. Convert the arguments, then
3357 // break out so that we will build the appropriate built-in
3358 // operator node.
3359 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
3360 "passing") ||
3361 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
3362 "passing"))
3363 return true;
3364
3365 break;
3366 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003367 }
3368
3369 case OR_No_Viable_Function:
3370 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003371 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003372 break;
3373
3374 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003375 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3376 << BinaryOperator::getOpcodeStr(Opc)
3377 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003378 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3379 return true;
3380 }
3381
Douglas Gregor70d26122008-11-12 17:17:38 +00003382 // Either we found no viable overloaded operator or we matched a
3383 // built-in operator. In either case, fall through to trying to
3384 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003385 }
Chris Lattner4b009652007-07-25 00:24:17 +00003386
Douglas Gregord7f915e2008-11-06 23:29:22 +00003387 // Build a built-in binary operation.
3388 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003389}
3390
3391// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003392Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3393 tok::TokenKind Op, ExprTy *input) {
Chris Lattner4b009652007-07-25 00:24:17 +00003394 Expr *Input = (Expr*)input;
3395 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003396
3397 if (getLangOptions().CPlusPlus &&
3398 (Input->getType()->isRecordType()
3399 || Input->getType()->isEnumeralType())) {
3400 // Determine which overloaded operator we're dealing with.
3401 static const OverloadedOperatorKind OverOps[] = {
3402 OO_None, OO_None,
3403 OO_PlusPlus, OO_MinusMinus,
3404 OO_Amp, OO_Star,
3405 OO_Plus, OO_Minus,
3406 OO_Tilde, OO_Exclaim,
3407 OO_None, OO_None,
3408 OO_None,
3409 OO_None
3410 };
3411 OverloadedOperatorKind OverOp = OverOps[Opc];
3412
3413 // Add the appropriate overloaded operators (C++ [over.match.oper])
3414 // to the candidate set.
3415 OverloadCandidateSet CandidateSet;
3416 if (OverOp != OO_None)
3417 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3418
3419 // Perform overload resolution.
3420 OverloadCandidateSet::iterator Best;
3421 switch (BestViableFunction(CandidateSet, Best)) {
3422 case OR_Success: {
3423 // We found a built-in operator or an overloaded operator.
3424 FunctionDecl *FnDecl = Best->Function;
3425
3426 if (FnDecl) {
3427 // We matched an overloaded operator. Build a call to that
3428 // operator.
3429
3430 // Convert the arguments.
3431 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3432 if (PerformObjectArgumentInitialization(Input, Method))
3433 return true;
3434 } else {
3435 // Convert the arguments.
3436 if (PerformCopyInitialization(Input,
3437 FnDecl->getParamDecl(0)->getType(),
3438 "passing"))
3439 return true;
3440 }
3441
3442 // Determine the result type
3443 QualType ResultTy
3444 = FnDecl->getType()->getAsFunctionType()->getResultType();
3445 ResultTy = ResultTy.getNonReferenceType();
3446
3447 // Build the actual expression node.
3448 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3449 SourceLocation());
3450 UsualUnaryConversions(FnExpr);
3451
3452 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3453 } else {
3454 // We matched a built-in operator. Convert the arguments, then
3455 // break out so that we will build the appropriate built-in
3456 // operator node.
3457 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0],
3458 "passing"))
3459 return true;
3460
3461 break;
3462 }
3463 }
3464
3465 case OR_No_Viable_Function:
3466 // No viable function; fall through to handling this as a
3467 // built-in operator, which will produce an error message for us.
3468 break;
3469
3470 case OR_Ambiguous:
3471 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3472 << UnaryOperator::getOpcodeStr(Opc)
3473 << Input->getSourceRange();
3474 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3475 return true;
3476 }
3477
3478 // Either we found no viable overloaded operator or we matched a
3479 // built-in operator. In either case, fall through to trying to
3480 // build a built-in operation.
3481 }
3482
Chris Lattner4b009652007-07-25 00:24:17 +00003483 QualType resultType;
3484 switch (Opc) {
3485 default:
3486 assert(0 && "Unimplemented unary expr!");
3487 case UnaryOperator::PreInc:
3488 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003489 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3490 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003491 break;
3492 case UnaryOperator::AddrOf:
3493 resultType = CheckAddressOfOperand(Input, OpLoc);
3494 break;
3495 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003496 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003497 resultType = CheckIndirectionOperand(Input, OpLoc);
3498 break;
3499 case UnaryOperator::Plus:
3500 case UnaryOperator::Minus:
3501 UsualUnaryConversions(Input);
3502 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003503 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3504 break;
3505 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3506 resultType->isEnumeralType())
3507 break;
3508 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3509 Opc == UnaryOperator::Plus &&
3510 resultType->isPointerType())
3511 break;
3512
Chris Lattner77d52da2008-11-20 06:06:08 +00003513 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003514 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003515 case UnaryOperator::Not: // bitwise complement
3516 UsualUnaryConversions(Input);
3517 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003518 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3519 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3520 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003521 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003522 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003523 else if (!resultType->isIntegerType())
Chris Lattner77d52da2008-11-20 06:06:08 +00003524 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003525 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003526 break;
3527 case UnaryOperator::LNot: // logical negation
3528 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3529 DefaultFunctionArrayConversion(Input);
3530 resultType = Input->getType();
3531 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattner77d52da2008-11-20 06:06:08 +00003532 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003533 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003534 // LNot always has type int. C99 6.5.3.3p5.
3535 resultType = Context.IntTy;
3536 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003537 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003538 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003539 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003540 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003541 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003542 resultType = Input->getType();
3543 break;
3544 }
3545 if (resultType.isNull())
3546 return true;
3547 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3548}
3549
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003550/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3551Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003552 SourceLocation LabLoc,
3553 IdentifierInfo *LabelII) {
3554 // Look up the record for this label identifier.
3555 LabelStmt *&LabelDecl = LabelMap[LabelII];
3556
Daniel Dunbar879788d2008-08-04 16:51:22 +00003557 // If we haven't seen this label yet, create a forward reference. It
3558 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003559 if (LabelDecl == 0)
3560 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3561
3562 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003563 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3564 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003565}
3566
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003567Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003568 SourceLocation RPLoc) { // "({..})"
3569 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3570 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3571 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3572
3573 // FIXME: there are a variety of strange constraints to enforce here, for
3574 // example, it is not possible to goto into a stmt expression apparently.
3575 // More semantic analysis is needed.
3576
3577 // FIXME: the last statement in the compount stmt has its value used. We
3578 // should not warn about it being unused.
3579
3580 // If there are sub stmts in the compound stmt, take the type of the last one
3581 // as the type of the stmtexpr.
3582 QualType Ty = Context.VoidTy;
3583
Chris Lattner200964f2008-07-26 19:51:01 +00003584 if (!Compound->body_empty()) {
3585 Stmt *LastStmt = Compound->body_back();
3586 // If LastStmt is a label, skip down through into the body.
3587 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3588 LastStmt = Label->getSubStmt();
3589
3590 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003591 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003592 }
Chris Lattner4b009652007-07-25 00:24:17 +00003593
3594 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3595}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003596
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003597Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3598 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003599 SourceLocation TypeLoc,
3600 TypeTy *argty,
3601 OffsetOfComponent *CompPtr,
3602 unsigned NumComponents,
3603 SourceLocation RPLoc) {
3604 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3605 assert(!ArgTy.isNull() && "Missing type argument!");
3606
3607 // We must have at least one component that refers to the type, and the first
3608 // one is known to be a field designator. Verify that the ArgTy represents
3609 // a struct/union/class.
3610 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003611 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003612
3613 // Otherwise, create a compound literal expression as the base, and
3614 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003615 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003616
Chris Lattnerb37522e2007-08-31 21:49:13 +00003617 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3618 // GCC extension, diagnose them.
3619 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003620 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3621 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003622
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003623 for (unsigned i = 0; i != NumComponents; ++i) {
3624 const OffsetOfComponent &OC = CompPtr[i];
3625 if (OC.isBrackets) {
3626 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003627 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003628 if (!AT) {
3629 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003630 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003631 }
3632
Chris Lattner2af6a802007-08-30 17:59:59 +00003633 // FIXME: C++: Verify that operator[] isn't overloaded.
3634
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003635 // C99 6.5.2.1p1
3636 Expr *Idx = static_cast<Expr*>(OC.U.E);
3637 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003638 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3639 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003640
3641 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3642 continue;
3643 }
3644
3645 const RecordType *RC = Res->getType()->getAsRecordType();
3646 if (!RC) {
3647 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003648 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003649 }
3650
3651 // Get the decl corresponding to this.
3652 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003653 FieldDecl *MemberDecl
3654 = dyn_cast_or_null<FieldDecl>(LookupDecl(OC.U.IdentInfo,
3655 Decl::IDNS_Ordinary,
3656 S, RD, false, false));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003657 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003658 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3659 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003660
3661 // FIXME: C++: Verify that MemberDecl isn't a static field.
3662 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003663 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3664 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003665 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3666 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003667 }
3668
3669 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3670 BuiltinLoc);
3671}
3672
3673
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003674Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003675 TypeTy *arg1, TypeTy *arg2,
3676 SourceLocation RPLoc) {
3677 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3678 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3679
3680 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3681
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003682 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003683}
3684
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003685Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003686 ExprTy *expr1, ExprTy *expr2,
3687 SourceLocation RPLoc) {
3688 Expr *CondExpr = static_cast<Expr*>(cond);
3689 Expr *LHSExpr = static_cast<Expr*>(expr1);
3690 Expr *RHSExpr = static_cast<Expr*>(expr2);
3691
3692 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3693
3694 // The conditional expression is required to be a constant expression.
3695 llvm::APSInt condEval(32);
3696 SourceLocation ExpLoc;
3697 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003698 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3699 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00003700
3701 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3702 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3703 RHSExpr->getType();
3704 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3705}
3706
Steve Naroff52a81c02008-09-03 18:15:37 +00003707//===----------------------------------------------------------------------===//
3708// Clang Extensions.
3709//===----------------------------------------------------------------------===//
3710
3711/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003712void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003713 // Analyze block parameters.
3714 BlockSemaInfo *BSI = new BlockSemaInfo();
3715
3716 // Add BSI to CurBlock.
3717 BSI->PrevBlockInfo = CurBlock;
3718 CurBlock = BSI;
3719
3720 BSI->ReturnType = 0;
3721 BSI->TheScope = BlockScope;
3722
Steve Naroff52059382008-10-10 01:28:17 +00003723 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003724 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00003725}
3726
3727void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003728 // Analyze arguments to block.
3729 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3730 "Not a function declarator!");
3731 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3732
Steve Naroff52059382008-10-10 01:28:17 +00003733 CurBlock->hasPrototype = FTI.hasPrototype;
3734 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003735
3736 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3737 // no arguments, not a function that takes a single void argument.
3738 if (FTI.hasPrototype &&
3739 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3740 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3741 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3742 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003743 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003744 } else if (FTI.hasPrototype) {
3745 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003746 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3747 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003748 }
Steve Naroff52059382008-10-10 01:28:17 +00003749 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3750
3751 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3752 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3753 // If this has an identifier, add it to the scope stack.
3754 if ((*AI)->getIdentifier())
3755 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003756}
3757
3758/// ActOnBlockError - If there is an error parsing a block, this callback
3759/// is invoked to pop the information about the block from the action impl.
3760void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3761 // Ensure that CurBlock is deleted.
3762 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3763
3764 // Pop off CurBlock, handle nested blocks.
3765 CurBlock = CurBlock->PrevBlockInfo;
3766
3767 // FIXME: Delete the ParmVarDecl objects as well???
3768
3769}
3770
3771/// ActOnBlockStmtExpr - This is called when the body of a block statement
3772/// literal was successfully completed. ^(int x){...}
3773Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3774 Scope *CurScope) {
3775 // Ensure that CurBlock is deleted.
3776 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3777 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3778
Steve Naroff52059382008-10-10 01:28:17 +00003779 PopDeclContext();
3780
Steve Naroff52a81c02008-09-03 18:15:37 +00003781 // Pop off CurBlock, handle nested blocks.
3782 CurBlock = CurBlock->PrevBlockInfo;
3783
3784 QualType RetTy = Context.VoidTy;
3785 if (BSI->ReturnType)
3786 RetTy = QualType(BSI->ReturnType, 0);
3787
3788 llvm::SmallVector<QualType, 8> ArgTypes;
3789 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3790 ArgTypes.push_back(BSI->Params[i]->getType());
3791
3792 QualType BlockTy;
3793 if (!BSI->hasPrototype)
3794 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3795 else
3796 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003797 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003798
3799 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003800
Steve Naroff95029d92008-10-08 18:44:00 +00003801 BSI->TheDecl->setBody(Body.take());
3802 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003803}
3804
Nate Begemanbd881ef2008-01-30 20:50:20 +00003805/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003806/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003807/// The number of arguments has already been validated to match the number of
3808/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003809static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3810 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003811 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003812 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003813 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3814 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003815
3816 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003817 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003818 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003819 return true;
3820}
3821
3822Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3823 SourceLocation *CommaLocs,
3824 SourceLocation BuiltinLoc,
3825 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003826 // __builtin_overload requires at least 2 arguments
3827 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003828 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3829 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003830
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003831 // The first argument is required to be a constant expression. It tells us
3832 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003833 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003834 Expr *NParamsExpr = Args[0];
3835 llvm::APSInt constEval(32);
3836 SourceLocation ExpLoc;
3837 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003838 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3839 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003840
3841 // Verify that the number of parameters is > 0
3842 unsigned NumParams = constEval.getZExtValue();
3843 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003844 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3845 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003846 // Verify that we have at least 1 + NumParams arguments to the builtin.
3847 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003848 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3849 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003850
3851 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003852 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003853 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003854 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3855 // UsualUnaryConversions will convert the function DeclRefExpr into a
3856 // pointer to function.
3857 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003858 const FunctionTypeProto *FnType = 0;
3859 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3860 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003861
3862 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3863 // parameters, and the number of parameters must match the value passed to
3864 // the builtin.
3865 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003866 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
3867 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003868
3869 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003870 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003871 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003872 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003873 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003874 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
3875 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00003876 // Remember our match, and continue processing the remaining arguments
3877 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003878 OE = new OverloadExpr(Args, NumArgs, i,
3879 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003880 BuiltinLoc, RParenLoc);
3881 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003882 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003883 // Return the newly created OverloadExpr node, if we succeded in matching
3884 // exactly one of the candidate functions.
3885 if (OE)
3886 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003887
3888 // If we didn't find a matching function Expr in the __builtin_overload list
3889 // the return an error.
3890 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003891 for (unsigned i = 0; i != NumParams; ++i) {
3892 if (i != 0) typeNames += ", ";
3893 typeNames += Args[i+1]->getType().getAsString();
3894 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003895
Chris Lattner77d52da2008-11-20 06:06:08 +00003896 return Diag(BuiltinLoc, diag::err_overload_no_match)
3897 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003898}
3899
Anders Carlsson36760332007-10-15 20:28:48 +00003900Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3901 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003902 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003903 Expr *E = static_cast<Expr*>(expr);
3904 QualType T = QualType::getFromOpaquePtr(type);
3905
3906 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003907
3908 // Get the va_list type
3909 QualType VaListType = Context.getBuiltinVaListType();
3910 // Deal with implicit array decay; for example, on x86-64,
3911 // va_list is an array, but it's supposed to decay to
3912 // a pointer for va_arg.
3913 if (VaListType->isArrayType())
3914 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003915 // Make sure the input expression also decays appropriately.
3916 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003917
3918 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003919 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00003920 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003921 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00003922
3923 // FIXME: Warn if a non-POD type is passed in.
3924
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003925 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003926}
3927
Douglas Gregorad4b3792008-11-29 04:51:27 +00003928Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
3929 // The type of __null will be int or long, depending on the size of
3930 // pointers on the target.
3931 QualType Ty;
3932 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
3933 Ty = Context.IntTy;
3934 else
3935 Ty = Context.LongTy;
3936
3937 return new GNUNullExpr(Ty, TokenLoc);
3938}
3939
Chris Lattner005ed752008-01-04 18:04:52 +00003940bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3941 SourceLocation Loc,
3942 QualType DstType, QualType SrcType,
3943 Expr *SrcExpr, const char *Flavor) {
3944 // Decode the result (notice that AST's are still created for extensions).
3945 bool isInvalid = false;
3946 unsigned DiagKind;
3947 switch (ConvTy) {
3948 default: assert(0 && "Unknown conversion type");
3949 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003950 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003951 DiagKind = diag::ext_typecheck_convert_pointer_int;
3952 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003953 case IntToPointer:
3954 DiagKind = diag::ext_typecheck_convert_int_pointer;
3955 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003956 case IncompatiblePointer:
3957 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3958 break;
3959 case FunctionVoidPointer:
3960 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3961 break;
3962 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003963 // If the qualifiers lost were because we were applying the
3964 // (deprecated) C++ conversion from a string literal to a char*
3965 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3966 // Ideally, this check would be performed in
3967 // CheckPointerTypesForAssignment. However, that would require a
3968 // bit of refactoring (so that the second argument is an
3969 // expression, rather than a type), which should be done as part
3970 // of a larger effort to fix CheckPointerTypesForAssignment for
3971 // C++ semantics.
3972 if (getLangOptions().CPlusPlus &&
3973 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3974 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003975 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3976 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003977 case IntToBlockPointer:
3978 DiagKind = diag::err_int_to_block_pointer;
3979 break;
3980 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003981 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003982 break;
Steve Naroff19608432008-10-14 22:18:38 +00003983 case IncompatibleObjCQualifiedId:
3984 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3985 // it can give a more specific diagnostic.
3986 DiagKind = diag::warn_incompatible_qualified_id;
3987 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003988 case Incompatible:
3989 DiagKind = diag::err_typecheck_convert_incompatible;
3990 isInvalid = true;
3991 break;
3992 }
3993
Chris Lattner271d4c22008-11-24 05:29:24 +00003994 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
3995 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00003996 return isInvalid;
3997}
Anders Carlssond5201b92008-11-30 19:50:32 +00003998
3999bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4000{
4001 Expr::EvalResult EvalResult;
4002
4003 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4004 EvalResult.HasSideEffects) {
4005 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4006
4007 if (EvalResult.Diag) {
4008 // We only show the note if it's not the usual "invalid subexpression"
4009 // or if it's actually in a subexpression.
4010 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4011 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4012 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4013 }
4014
4015 return true;
4016 }
4017
4018 if (EvalResult.Diag) {
4019 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4020 E->getSourceRange();
4021
4022 // Print the reason it's not a constant.
4023 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4024 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4025 }
4026
4027 if (Result)
4028 *Result = EvalResult.Val.getInt();
4029 return false;
4030}