blob: 2721bb8dc60f8d23148b2b08a93703223f0e49d4 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner04421082008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Chris Lattnere7a2e912008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattnere7a2e912008-07-25 21:10:04 +000033/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
34void Sema::DefaultFunctionArrayConversion(Expr *&E) {
35 QualType Ty = E->getType();
36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
37
Chris Lattnere7a2e912008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-07-25 21:33:13 +000040 else if (Ty->isArrayType()) {
41 // In C90 mode, arrays only promote to pointers if the array expression is
42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
43 // type 'array of type' is converted to an expression that has type 'pointer
44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
45 // that has type 'array of type' ...". The relevant change is "an lvalue"
46 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +000047 //
48 // C++ 4.2p1:
49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
50 // T" can be converted to an rvalue of type "pointer to T".
51 //
52 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
53 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner67d33d82008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattnere7a2e912008-07-25 21:10:04 +000056}
57
58/// UsualUnaryConversions - Performs various conversions that are common to most
59/// operators (C99 6.3). The conversions of array and function types are
60/// sometimes surpressed. For example, the array->pointer conversion doesn't
61/// apply if the array is an argument to the sizeof or address (&) operators.
62/// In these instances, this routine should *not* be called.
63Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
64 QualType Ty = Expr->getType();
65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
66
Chris Lattnere7a2e912008-07-25 21:10:04 +000067 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
68 ImpCastExprToType(Expr, Context.IntTy);
69 else
70 DefaultFunctionArrayConversion(Expr);
71
72 return Expr;
73}
74
Chris Lattner05faf172008-07-25 22:25:12 +000075/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
76/// do not have a prototype. Arguments that have type float are promoted to
77/// double. All other argument types are converted by UsualUnaryConversions().
78void Sema::DefaultArgumentPromotion(Expr *&Expr) {
79 QualType Ty = Expr->getType();
80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
81
82 // If this is a 'float' (CVR qualified or typedef) promote to double.
83 if (const BuiltinType *BT = Ty->getAsBuiltinType())
84 if (BT->getKind() == BuiltinType::Float)
85 return ImpCastExprToType(Expr, Context.DoubleTy);
86
87 UsualUnaryConversions(Expr);
88}
89
Chris Lattnere7a2e912008-07-25 21:10:04 +000090/// UsualArithmeticConversions - Performs various conversions that are common to
91/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
92/// routine returns the first non-arithmetic type found. The client is
93/// responsible for emitting appropriate error diagnostics.
94/// FIXME: verify the conversion rules for "complex int" are consistent with
95/// GCC.
96QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
97 bool isCompAssign) {
98 if (!isCompAssign) {
99 UsualUnaryConversions(lhsExpr);
100 UsualUnaryConversions(rhsExpr);
101 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000102
Chris Lattnere7a2e912008-07-25 21:10:04 +0000103 // For conversion purposes, we ignore any qualifiers.
104 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000105 QualType lhs =
106 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
107 QualType rhs =
108 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000109
110 // If both types are identical, no conversion is needed.
111 if (lhs == rhs)
112 return lhs;
113
114 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
115 // The caller can deal with this (e.g. pointer + int).
116 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
117 return lhs;
118
119 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
120 if (!isCompAssign) {
121 ImpCastExprToType(lhsExpr, destType);
122 ImpCastExprToType(rhsExpr, destType);
123 }
124 return destType;
125}
126
127QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
128 // Perform the usual unary conversions. We do this early so that
129 // integral promotions to "int" can allow us to exit early, in the
130 // lhs == rhs check. Also, for conversion purposes, we ignore any
131 // qualifiers. For example, "const float" and "float" are
132 // equivalent.
Douglas Gregorbf3af052008-11-13 20:12:29 +0000133 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
134 else lhs = lhs.getUnqualifiedType();
135 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
136 else rhs = rhs.getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000137
Chris Lattnere7a2e912008-07-25 21:10:04 +0000138 // If both types are identical, no conversion is needed.
139 if (lhs == rhs)
140 return lhs;
141
142 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
143 // The caller can deal with this (e.g. pointer + int).
144 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
145 return lhs;
146
147 // At this point, we have two different arithmetic types.
148
149 // Handle complex types first (C99 6.3.1.8p1).
150 if (lhs->isComplexType() || rhs->isComplexType()) {
151 // if we have an integer operand, the result is the complex type.
152 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
153 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000154 return lhs;
155 }
156 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
157 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000158 return rhs;
159 }
160 // This handles complex/complex, complex/float, or float/complex.
161 // When both operands are complex, the shorter operand is converted to the
162 // type of the longer, and that is the type of the result. This corresponds
163 // to what is done when combining two real floating-point operands.
164 // The fun begins when size promotion occur across type domains.
165 // From H&S 6.3.4: When one operand is complex and the other is a real
166 // floating-point type, the less precise type is converted, within it's
167 // real or complex domain, to the precision of the other type. For example,
168 // when combining a "long double" with a "double _Complex", the
169 // "double _Complex" is promoted to "long double _Complex".
170 int result = Context.getFloatingTypeOrder(lhs, rhs);
171
172 if (result > 0) { // The left side is bigger, convert rhs.
173 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000174 } else if (result < 0) { // The right side is bigger, convert lhs.
175 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000176 }
177 // At this point, lhs and rhs have the same rank/size. Now, make sure the
178 // domains match. This is a requirement for our implementation, C99
179 // does not require this promotion.
180 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
181 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattnere7a2e912008-07-25 21:10:04 +0000182 return rhs;
183 } else { // handle "_Complex double, double".
Chris Lattnere7a2e912008-07-25 21:10:04 +0000184 return lhs;
185 }
186 }
187 return lhs; // The domain/size match exactly.
188 }
189 // Now handle "real" floating types (i.e. float, double, long double).
190 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
191 // if we have an integer operand, the result is the real floating type.
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000192 if (rhs->isIntegerType()) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000193 // convert rhs to the lhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000194 return lhs;
195 }
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000196 if (rhs->isComplexIntegerType()) {
197 // convert rhs to the complex floating point type.
198 return Context.getComplexType(lhs);
199 }
200 if (lhs->isIntegerType()) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000201 // convert lhs to the rhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000202 return rhs;
203 }
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000204 if (lhs->isComplexIntegerType()) {
205 // convert lhs to the complex floating point type.
206 return Context.getComplexType(rhs);
207 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000208 // We have two real floating types, float/complex combos were handled above.
209 // Convert the smaller operand to the bigger result.
210 int result = Context.getFloatingTypeOrder(lhs, rhs);
211
212 if (result > 0) { // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000213 return lhs;
214 }
215 if (result < 0) { // convert the lhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000216 return rhs;
217 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000218 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattnere7a2e912008-07-25 21:10:04 +0000219 }
220 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
221 // Handle GCC complex int extension.
222 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
223 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
224
225 if (lhsComplexInt && rhsComplexInt) {
226 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
227 rhsComplexInt->getElementType()) >= 0) {
228 // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000229 return lhs;
230 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000231 return rhs;
232 } else if (lhsComplexInt && rhs->isIntegerType()) {
233 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000234 return lhs;
235 } else if (rhsComplexInt && lhs->isIntegerType()) {
236 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000237 return rhs;
238 }
239 }
240 // Finally, we have two differing integer types.
241 // The rules for this case are in C99 6.3.1.8
242 int compare = Context.getIntegerTypeOrder(lhs, rhs);
243 bool lhsSigned = lhs->isSignedIntegerType(),
244 rhsSigned = rhs->isSignedIntegerType();
245 QualType destType;
246 if (lhsSigned == rhsSigned) {
247 // Same signedness; use the higher-ranked type
248 destType = compare >= 0 ? lhs : rhs;
249 } else if (compare != (lhsSigned ? 1 : -1)) {
250 // The unsigned type has greater than or equal rank to the
251 // signed type, so use the unsigned type
252 destType = lhsSigned ? rhs : lhs;
253 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
254 // The two types are different widths; if we are here, that
255 // means the signed type is larger than the unsigned type, so
256 // use the signed type.
257 destType = lhsSigned ? lhs : rhs;
258 } else {
259 // The signed type is higher-ranked than the unsigned type,
260 // but isn't actually any bigger (like unsigned int and long
261 // on most 32-bit systems). Use the unsigned type corresponding
262 // to the signed type.
263 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
264 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000265 return destType;
266}
267
268//===----------------------------------------------------------------------===//
269// Semantic Analysis for various Expression Types
270//===----------------------------------------------------------------------===//
271
272
Steve Narofff69936d2007-09-16 03:34:24 +0000273/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000274/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
275/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
276/// multiple tokens. However, the common case is that StringToks points to one
277/// string.
278///
279Action::ExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000280Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 assert(NumStringToks && "Must have at least one string!");
282
283 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
284 if (Literal.hadError)
285 return ExprResult(true);
286
287 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
288 for (unsigned i = 0; i != NumStringToks; ++i)
289 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000290
291 // Verify that pascal strings aren't too large.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000292 if (Literal.Pascal && Literal.GetStringLength() > 256)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000293 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
294 << SourceRange(StringToks[0].getLocation(),
295 StringToks[NumStringToks-1].getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000296
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000297 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000298 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000299 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000300
301 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
302 if (getLangOptions().CPlusPlus)
303 StrTy.addConst();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000304
305 // Get an array type for the string, according to C99 6.4.5. This includes
306 // the nul terminator character as well as the string length for pascal
307 // strings.
308 StrTy = Context.getConstantArrayType(StrTy,
309 llvm::APInt(32, Literal.GetStringLength()+1),
310 ArrayType::Normal, 0);
311
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
313 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000314 Literal.AnyWide, StrTy,
Anders Carlssonee98ac52007-10-15 02:50:23 +0000315 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000316 StringToks[NumStringToks-1].getLocation());
317}
318
Chris Lattner639e2d32008-10-20 05:16:36 +0000319/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
320/// CurBlock to VD should cause it to be snapshotted (as we do for auto
321/// variables defined outside the block) or false if this is not needed (e.g.
322/// for values inside the block or for globals).
323///
324/// FIXME: This will create BlockDeclRefExprs for global variables,
325/// function references, etc which is suboptimal :) and breaks
326/// things like "integer constant expression" tests.
327static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
328 ValueDecl *VD) {
329 // If the value is defined inside the block, we couldn't snapshot it even if
330 // we wanted to.
331 if (CurBlock->TheDecl == VD->getDeclContext())
332 return false;
333
334 // If this is an enum constant or function, it is constant, don't snapshot.
335 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
336 return false;
337
338 // If this is a reference to an extern, static, or global variable, no need to
339 // snapshot it.
340 // FIXME: What about 'const' variables in C++?
341 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
342 return Var->hasLocalStorage();
343
344 return true;
345}
346
347
348
Steve Naroff08d92e42007-09-15 18:49:24 +0000349/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000350/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000351/// identifier is used in a function call context.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000352/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the
353/// class or namespace that the identifier must be a member of.
Steve Naroff08d92e42007-09-15 18:49:24 +0000354Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000355 IdentifierInfo &II,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000356 bool HasTrailingLParen,
357 const CXXScopeSpec *SS) {
Douglas Gregor10c42622008-11-18 15:03:34 +0000358 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
359}
360
Douglas Gregor1a49af92009-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 Gregorbcbffc42009-01-07 00:43:41 +0000374/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
375/// variable corresponding to the anonymous union or struct whose type
376/// is Record.
377static ScopedDecl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
378 assert(Record->isAnonymousStructOrUnion() &&
379 "Record must be an anonymous struct or union!");
380
381 // FIXME: Once ScopedDecls are directly linked together, this will
382 // be an O(1) operation rather than a slow walk through DeclContext's
383 // vector (which itself will be eliminated). DeclGroups might make
384 // this even better.
385 DeclContext *Ctx = Record->getDeclContext();
386 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
387 DEnd = Ctx->decls_end();
388 D != DEnd; ++D) {
389 if (*D == Record) {
390 // The object for the anonymous struct/union directly
391 // follows its type in the list of declarations.
392 ++D;
393 assert(D != DEnd && "Missing object for anonymous record");
394 assert(!cast<ScopedDecl>(*D)->getDeclName() && "Decl should be unnamed");
395 return *D;
396 }
397 }
398
399 assert(false && "Missing object for anonymous record");
400 return 0;
401}
402
403Sema::ExprResult
404Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
405 FieldDecl *Field,
406 Expr *BaseObjectExpr,
407 SourceLocation OpLoc) {
408 assert(Field->getDeclContext()->isRecord() &&
409 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
410 && "Field must be stored inside an anonymous struct or union");
411
412 // Construct the sequence of field member references
413 // we'll have to perform to get to the field in the anonymous
414 // union/struct. The list of members is built from the field
415 // outward, so traverse it backwards to go from an object in
416 // the current context to the field we found.
417 llvm::SmallVector<FieldDecl *, 4> AnonFields;
418 AnonFields.push_back(Field);
419 VarDecl *BaseObject = 0;
420 DeclContext *Ctx = Field->getDeclContext();
421 do {
422 RecordDecl *Record = cast<RecordDecl>(Ctx);
423 ScopedDecl *AnonObject = getObjectForAnonymousRecordDecl(Record);
424 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
425 AnonFields.push_back(AnonField);
426 else {
427 BaseObject = cast<VarDecl>(AnonObject);
428 break;
429 }
430 Ctx = Ctx->getParent();
431 } while (Ctx->isRecord() &&
432 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
433
434 // Build the expression that refers to the base object, from
435 // which we will build a sequence of member references to each
436 // of the anonymous union objects and, eventually, the field we
437 // found via name lookup.
438 bool BaseObjectIsPointer = false;
439 unsigned ExtraQuals = 0;
440 if (BaseObject) {
441 // BaseObject is an anonymous struct/union variable (and is,
442 // therefore, not part of another non-anonymous record).
443 delete BaseObjectExpr;
444
445 BaseObjectExpr = new DeclRefExpr(BaseObject, BaseObject->getType(),
446 SourceLocation());
447 ExtraQuals
448 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
449 } else if (BaseObjectExpr) {
450 // The caller provided the base object expression. Determine
451 // whether its a pointer and whether it adds any qualifiers to the
452 // anonymous struct/union fields we're looking into.
453 QualType ObjectType = BaseObjectExpr->getType();
454 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
455 BaseObjectIsPointer = true;
456 ObjectType = ObjectPtr->getPointeeType();
457 }
458 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
459 } else {
460 // We've found a member of an anonymous struct/union that is
461 // inside a non-anonymous struct/union, so in a well-formed
462 // program our base object expression is "this".
463 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
464 if (!MD->isStatic()) {
465 QualType AnonFieldType
466 = Context.getTagDeclType(
467 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
468 QualType ThisType = Context.getTagDeclType(MD->getParent());
469 if ((Context.getCanonicalType(AnonFieldType)
470 == Context.getCanonicalType(ThisType)) ||
471 IsDerivedFrom(ThisType, AnonFieldType)) {
472 // Our base object expression is "this".
473 BaseObjectExpr = new CXXThisExpr(SourceLocation(),
474 MD->getThisType(Context));
475 BaseObjectIsPointer = true;
476 }
477 } else {
478 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
479 << Field->getDeclName();
480 }
481 ExtraQuals = MD->getTypeQualifiers();
482 }
483
484 if (!BaseObjectExpr)
485 return Diag(Loc, diag::err_invalid_non_static_member_use)
486 << Field->getDeclName();
487 }
488
489 // Build the implicit member references to the field of the
490 // anonymous struct/union.
491 Expr *Result = BaseObjectExpr;
492 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
493 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
494 FI != FIEnd; ++FI) {
495 QualType MemberType = (*FI)->getType();
496 if (!(*FI)->isMutable()) {
497 unsigned combinedQualifiers
498 = MemberType.getCVRQualifiers() | ExtraQuals;
499 MemberType = MemberType.getQualifiedType(combinedQualifiers);
500 }
501 Result = new MemberExpr(Result, BaseObjectIsPointer, *FI,
502 OpLoc, MemberType);
503 BaseObjectIsPointer = false;
504 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
505 OpLoc = SourceLocation();
506 }
507
508 return Result;
509}
510
Douglas Gregor10c42622008-11-18 15:03:34 +0000511/// ActOnDeclarationNameExpr - The parser has read some kind of name
512/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
513/// performs lookup on that name and returns an expression that refers
514/// to that name. This routine isn't directly called from the parser,
515/// because the parser doesn't know about DeclarationName. Rather,
516/// this routine is called by ActOnIdentifierExpr,
517/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
518/// which form the DeclarationName from the corresponding syntactic
519/// forms.
520///
521/// HasTrailingLParen indicates whether this identifier is used in a
522/// function call context. LookupCtx is only used for a C++
523/// qualified-id (foo::bar) to indicate the class or namespace that
524/// the identifier must be a member of.
Douglas Gregor5c37de72008-12-06 00:22:45 +0000525///
526/// If ForceResolution is true, then we will attempt to resolve the
527/// name even if it looks like a dependent name. This option is off by
528/// default.
Douglas Gregor10c42622008-11-18 15:03:34 +0000529Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
530 DeclarationName Name,
531 bool HasTrailingLParen,
Douglas Gregor5c37de72008-12-06 00:22:45 +0000532 const CXXScopeSpec *SS,
533 bool ForceResolution) {
534 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
535 HasTrailingLParen && !SS && !ForceResolution) {
536 // We've seen something of the form
537 // identifier(
538 // and we are in a template, so it is likely that 's' is a
539 // dependent name. However, we won't know until we've parsed all
540 // of the call arguments. So, build a CXXDependentNameExpr node
541 // to represent this name. Then, if it turns out that none of the
542 // arguments are type-dependent, we'll force the resolution of the
543 // dependent name at that point.
544 return new CXXDependentNameExpr(Name.getAsIdentifierInfo(),
545 Context.DependentTy, Loc);
546 }
547
Chris Lattner8a934232008-03-31 00:36:02 +0000548 // Could be enum-constant, value decl, instance variable, etc.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000549 Decl *D;
550 if (SS && !SS->isEmpty()) {
551 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
552 if (DC == 0)
553 return true;
Douglas Gregor10c42622008-11-18 15:03:34 +0000554 D = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000555 } else
Douglas Gregor10c42622008-11-18 15:03:34 +0000556 D = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Douglas Gregor5c37de72008-12-06 00:22:45 +0000557
Chris Lattner8a934232008-03-31 00:36:02 +0000558 // If this reference is in an Objective-C method, then ivar lookup happens as
559 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000560 IdentifierInfo *II = Name.getAsIdentifierInfo();
561 if (II && getCurMethodDecl()) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000562 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattner8a934232008-03-31 00:36:02 +0000563 // There are two cases to handle here. 1) scoped lookup could have failed,
564 // in which case we should look for an ivar. 2) scoped lookup could have
565 // found a decl, but that decl is outside the current method (i.e. a global
566 // variable). In these two cases, we do a lookup for an ivar with this
567 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe8043c32008-04-01 23:04:06 +0000568 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000569 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregor10c42622008-11-18 15:03:34 +0000570 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner8a934232008-03-31 00:36:02 +0000571 // FIXME: This should use a new expr for a direct reference, don't turn
572 // this into Self->ivar, just return a BareIVarExpr or something.
573 IdentifierInfo &II = Context.Idents.get("self");
574 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +0000575 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), Loc,
576 static_cast<Expr*>(SelfExpr.Val), true, true);
577 Context.setFieldDecl(IFace, IV, MRef);
578 return MRef;
Chris Lattner8a934232008-03-31 00:36:02 +0000579 }
580 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000581 // Needed to implement property "super.method" notation.
Chris Lattner84692652008-11-20 05:35:30 +0000582 if (SD == 0 && II->isStr("super")) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000583 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000584 getCurMethodDecl()->getClassInterface()));
Douglas Gregorcd9b46e2008-11-04 14:56:14 +0000585 return new ObjCSuperExpr(Loc, T);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000586 }
Chris Lattner8a934232008-03-31 00:36:02 +0000587 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000588 if (D == 0) {
589 // Otherwise, this could be an implicitly declared function reference (legal
590 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000591 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000592 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000593 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 else {
595 // If this name wasn't predeclared and if this is not a function call,
596 // diagnose the problem.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000597 if (SS && !SS->isEmpty())
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000598 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattner08631c52008-11-23 21:45:46 +0000599 << Name << SS->getRange();
Douglas Gregor10c42622008-11-18 15:03:34 +0000600 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
601 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000602 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000603 else
Chris Lattner08631c52008-11-23 21:45:46 +0000604 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Reid Spencer5f016e22007-07-11 17:01:13 +0000605 }
606 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000607
608 // We may have found a field within an anonymous union or struct
609 // (C++ [class.union]).
610 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
611 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
612 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Chris Lattner8a934232008-03-31 00:36:02 +0000613
Douglas Gregor88a35142008-12-22 05:46:06 +0000614 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
615 if (!MD->isStatic()) {
616 // C++ [class.mfct.nonstatic]p2:
617 // [...] if name lookup (3.4.1) resolves the name in the
618 // id-expression to a nonstatic nontype member of class X or of
619 // a base class of X, the id-expression is transformed into a
620 // class member access expression (5.2.5) using (*this) (9.3.2)
621 // as the postfix-expression to the left of the '.' operator.
622 DeclContext *Ctx = 0;
623 QualType MemberType;
624 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
625 Ctx = FD->getDeclContext();
626 MemberType = FD->getType();
627
628 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
629 MemberType = RefType->getPointeeType();
630 else if (!FD->isMutable()) {
631 unsigned combinedQualifiers
632 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
633 MemberType = MemberType.getQualifiedType(combinedQualifiers);
634 }
635 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
636 if (!Method->isStatic()) {
637 Ctx = Method->getParent();
638 MemberType = Method->getType();
639 }
640 } else if (OverloadedFunctionDecl *Ovl
641 = dyn_cast<OverloadedFunctionDecl>(D)) {
642 for (OverloadedFunctionDecl::function_iterator
643 Func = Ovl->function_begin(),
644 FuncEnd = Ovl->function_end();
645 Func != FuncEnd; ++Func) {
646 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
647 if (!DMethod->isStatic()) {
648 Ctx = Ovl->getDeclContext();
649 MemberType = Context.OverloadTy;
650 break;
651 }
652 }
653 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000654
655 if (Ctx && Ctx->isRecord()) {
Douglas Gregor88a35142008-12-22 05:46:06 +0000656 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
657 QualType ThisType = Context.getTagDeclType(MD->getParent());
658 if ((Context.getCanonicalType(CtxType)
659 == Context.getCanonicalType(ThisType)) ||
660 IsDerivedFrom(ThisType, CtxType)) {
661 // Build the implicit member access expression.
662 Expr *This = new CXXThisExpr(SourceLocation(),
663 MD->getThisType(Context));
664 return new MemberExpr(This, true, cast<NamedDecl>(D),
665 SourceLocation(), MemberType);
666 }
667 }
668 }
669 }
670
Douglas Gregor44b43212008-12-11 16:49:14 +0000671 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000672 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
673 if (MD->isStatic())
674 // "invalid use of member 'x' in static member function"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000675 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000676 << FD->getDeclName();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000677 }
678
Douglas Gregor88a35142008-12-22 05:46:06 +0000679 // Any other ways we could have found the field in a well-formed
680 // program would have been turned into implicit member expressions
681 // above.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000682 return Diag(Loc, diag::err_invalid_non_static_member_use)
683 << FD->getDeclName();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000684 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000685
Reid Spencer5f016e22007-07-11 17:01:13 +0000686 if (isa<TypedefDecl>(D))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000687 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000688 if (isa<ObjCInterfaceDecl>(D))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000689 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000690 if (isa<NamespaceDecl>(D))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000691 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Reid Spencer5f016e22007-07-11 17:01:13 +0000692
Steve Naroffdd972f22008-09-05 22:11:13 +0000693 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000694 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Douglas Gregor1a49af92009-01-06 05:10:23 +0000695 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc, false, false, SS);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000696
Steve Naroffdd972f22008-09-05 22:11:13 +0000697 ValueDecl *VD = cast<ValueDecl>(D);
698
699 // check if referencing an identifier with __attribute__((deprecated)).
700 if (VD->getAttr<DeprecatedAttr>())
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000701 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000702
703 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
704 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
705 Scope *CheckS = S;
706 while (CheckS) {
707 if (CheckS->isWithinElse() &&
708 CheckS->getControlParent()->isDeclScope(Var)) {
709 if (Var->getType()->isBooleanType())
710 Diag(Loc, diag::warn_value_always_false) << Var->getDeclName();
711 else
712 Diag(Loc, diag::warn_value_always_zero) << Var->getDeclName();
713 break;
714 }
715
716 // Move up one more control parent to check again.
717 CheckS = CheckS->getControlParent();
718 if (CheckS)
719 CheckS = CheckS->getParent();
720 }
721 }
722 }
Steve Naroffdd972f22008-09-05 22:11:13 +0000723
724 // Only create DeclRefExpr's for valid Decl's.
725 if (VD->isInvalidDecl())
726 return true;
Chris Lattner639e2d32008-10-20 05:16:36 +0000727
728 // If the identifier reference is inside a block, and it refers to a value
729 // that is outside the block, create a BlockDeclRefExpr instead of a
730 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
731 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000732 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000733 // We do not do this for things like enum constants, global variables, etc,
734 // as they do not get snapshotted.
735 //
736 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff090276f2008-10-10 01:28:17 +0000737 // The BlocksAttr indicates the variable is bound by-reference.
738 if (VD->getAttr<BlocksAttr>())
Douglas Gregor9d293df2008-10-28 00:22:11 +0000739 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
740 Loc, true);
Steve Naroff090276f2008-10-10 01:28:17 +0000741
742 // Variable will be bound by-copy, make it const within the closure.
743 VD->getType().addConst();
Douglas Gregor9d293df2008-10-28 00:22:11 +0000744 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
745 Loc, false);
Steve Naroff090276f2008-10-10 01:28:17 +0000746 }
747 // If this reference is not in a block or if the referenced variable is
748 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +0000749
Douglas Gregor898574e2008-12-05 23:32:09 +0000750 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +0000751 bool ValueDependent = false;
752 if (getLangOptions().CPlusPlus) {
753 // C++ [temp.dep.expr]p3:
754 // An id-expression is type-dependent if it contains:
755 // - an identifier that was declared with a dependent type,
756 if (VD->getType()->isDependentType())
757 TypeDependent = true;
758 // - FIXME: a template-id that is dependent,
759 // - a conversion-function-id that specifies a dependent type,
760 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
761 Name.getCXXNameType()->isDependentType())
762 TypeDependent = true;
763 // - a nested-name-specifier that contains a class-name that
764 // names a dependent type.
765 else if (SS && !SS->isEmpty()) {
766 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
767 DC; DC = DC->getParent()) {
768 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000769 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +0000770 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
771 if (Context.getTypeDeclType(Record)->isDependentType()) {
772 TypeDependent = true;
773 break;
774 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000775 }
776 }
777 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000778
Douglas Gregor83f96f62008-12-10 20:57:37 +0000779 // C++ [temp.dep.constexpr]p2:
780 //
781 // An identifier is value-dependent if it is:
782 // - a name declared with a dependent type,
783 if (TypeDependent)
784 ValueDependent = true;
785 // - the name of a non-type template parameter,
786 else if (isa<NonTypeTemplateParmDecl>(VD))
787 ValueDependent = true;
788 // - a constant with integral or enumeration type and is
789 // initialized with an expression that is value-dependent
790 // (FIXME!).
791 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000792
Douglas Gregor1a49af92009-01-06 05:10:23 +0000793 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
794 TypeDependent, ValueDependent, SS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000795}
796
Chris Lattnerd9f69102008-08-10 01:53:14 +0000797Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000798 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000799 PredefinedExpr::IdentType IT;
Anders Carlsson22742662007-07-21 05:21:51 +0000800
Reid Spencer5f016e22007-07-11 17:01:13 +0000801 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000802 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000803 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
804 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
805 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000806 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000807
Chris Lattnerfa28b302008-01-12 08:14:25 +0000808 // Pre-defined identifiers are of type char[x], where x is the length of the
809 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000810 unsigned Length;
Chris Lattner371f2582008-12-04 23:50:19 +0000811 if (FunctionDecl *FD = getCurFunctionDecl())
812 Length = FD->getIdentifier()->getLength();
Chris Lattnerb0da9232008-12-12 05:05:20 +0000813 else if (ObjCMethodDecl *MD = getCurMethodDecl())
814 Length = MD->getSynthesizedMethodSize();
815 else {
816 Diag(Loc, diag::ext_predef_outside_function);
817 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
818 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
819 }
820
Chris Lattner1423ea42008-01-12 18:39:25 +0000821
Chris Lattner8f978d52008-01-12 19:32:28 +0000822 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000823 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000824 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerd9f69102008-08-10 01:53:14 +0000825 return new PredefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000826}
827
Steve Narofff69936d2007-09-16 03:34:24 +0000828Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000829 llvm::SmallString<16> CharBuffer;
830 CharBuffer.resize(Tok.getLength());
831 const char *ThisTokBegin = &CharBuffer[0];
832 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
833
834 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
835 Tok.getLocation(), PP);
836 if (Literal.hadError())
837 return ExprResult(true);
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000838
839 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
840
Chris Lattnerc250aae2008-06-07 22:35:38 +0000841 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
842 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000843}
844
Steve Narofff69936d2007-09-16 03:34:24 +0000845Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000846 // fast path for a single digit (which is quite common). A single digit
847 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
848 if (Tok.getLength() == 1) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000849 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000850
Chris Lattner98be4942008-03-05 18:54:05 +0000851 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000852 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +0000853 Context.IntTy,
854 Tok.getLocation()));
855 }
856 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000857 // Add padding so that NumericLiteralParser can overread by one character.
858 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000859 const char *ThisTokBegin = &IntegerBuffer[0];
860
861 // Get the spelling of the token, which eliminates trigraphs, etc.
862 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner28997ec2008-09-30 20:51:14 +0000863
Reid Spencer5f016e22007-07-11 17:01:13 +0000864 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
865 Tok.getLocation(), PP);
866 if (Literal.hadError)
867 return ExprResult(true);
868
Chris Lattner5d661452007-08-26 03:42:43 +0000869 Expr *Res;
870
871 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000872 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000873 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000874 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000875 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000876 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000877 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000878 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000879
880 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
881
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000882 // isExact will be set by GetFloatValue().
883 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000884 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000885 Ty, Tok.getLocation());
886
Chris Lattner5d661452007-08-26 03:42:43 +0000887 } else if (!Literal.isIntegerLiteral()) {
888 return ExprResult(true);
889 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000890 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000891
Neil Boothb9449512007-08-29 22:00:19 +0000892 // long long is a C99 feature.
893 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000894 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000895 Diag(Tok.getLocation(), diag::ext_longlong);
896
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000898 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000899
900 if (Literal.GetIntegerValue(ResultVal)) {
901 // If this value didn't fit into uintmax_t, warn and force to ull.
902 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000903 Ty = Context.UnsignedLongLongTy;
904 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000905 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000906 } else {
907 // If this value fits into a ULL, try to figure out what else it fits into
908 // according to the rules of C99 6.4.4.1p5.
909
910 // Octal, Hexadecimal, and integers with a U suffix are allowed to
911 // be an unsigned int.
912 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
913
914 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000915 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000916 if (!Literal.isLong && !Literal.isLongLong) {
917 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000918 unsigned IntSize = Context.Target.getIntWidth();
919
Reid Spencer5f016e22007-07-11 17:01:13 +0000920 // Does it fit in a unsigned int?
921 if (ResultVal.isIntN(IntSize)) {
922 // Does it fit in a signed int?
923 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000924 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000925 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000926 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000927 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000928 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000929 }
930
931 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000932 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000933 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000934
935 // Does it fit in a unsigned long?
936 if (ResultVal.isIntN(LongSize)) {
937 // Does it fit in a signed long?
938 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000939 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000940 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000941 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000942 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000943 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000944 }
945
946 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000947 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000948 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000949
950 // Does it fit in a unsigned long long?
951 if (ResultVal.isIntN(LongLongSize)) {
952 // Does it fit in a signed long long?
953 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000954 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000955 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000956 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000957 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000958 }
959 }
960
961 // If we still couldn't decide a type, we probably have something that
962 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000963 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000964 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000965 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000966 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000967 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000968
969 if (ResultVal.getBitWidth() != Width)
970 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000971 }
972
Chris Lattnerf0467b32008-04-02 04:24:33 +0000973 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000974 }
Chris Lattner5d661452007-08-26 03:42:43 +0000975
976 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
977 if (Literal.isImaginary)
978 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
979
980 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000981}
982
Steve Narofff69936d2007-09-16 03:34:24 +0000983Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000984 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000985 Expr *E = (Expr *)Val;
986 assert((E != 0) && "ActOnParenExpr() missing expr");
987 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +0000988}
989
990/// The UsualUnaryConversions() function is *not* called by this routine.
991/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl05189992008-11-11 17:56:53 +0000992bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
993 SourceLocation OpLoc,
994 const SourceRange &ExprRange,
995 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000996 // C99 6.5.3.4p1:
997 if (isa<FunctionType>(exprType) && isSizeof)
998 // alignof(function) is allowed.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000999 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Reid Spencer5f016e22007-07-11 17:01:13 +00001000 else if (exprType->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001001 Diag(OpLoc, diag::ext_sizeof_void_type)
1002 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1003 else if (exprType->isIncompleteType())
1004 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
1005 diag::err_alignof_incomplete_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00001006 << exprType << ExprRange;
Sebastian Redl05189992008-11-11 17:56:53 +00001007
1008 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001009}
1010
Sebastian Redl05189992008-11-11 17:56:53 +00001011/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1012/// the same for @c alignof and @c __alignof
1013/// Note that the ArgRange is invalid if isType is false.
1014Action::ExprResult
1015Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1016 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001017 // If error parsing type, ignore.
Sebastian Redl05189992008-11-11 17:56:53 +00001018 if (TyOrEx == 0) return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001019
Sebastian Redl05189992008-11-11 17:56:53 +00001020 QualType ArgTy;
1021 SourceRange Range;
1022 if (isType) {
1023 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1024 Range = ArgRange;
1025 } else {
1026 // Get the end location.
1027 Expr *ArgEx = (Expr *)TyOrEx;
1028 Range = ArgEx->getSourceRange();
1029 ArgTy = ArgEx->getType();
1030 }
1031
1032 // Verify that the operand is valid.
1033 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Reid Spencer5f016e22007-07-11 17:01:13 +00001034 return true;
Sebastian Redl05189992008-11-11 17:56:53 +00001035
1036 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1037 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
1038 OpLoc, Range.getEnd());
Reid Spencer5f016e22007-07-11 17:01:13 +00001039}
1040
Chris Lattner5d794252007-08-24 21:41:10 +00001041QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +00001042 DefaultFunctionArrayConversion(V);
1043
Chris Lattnercc26ed72007-08-26 05:39:26 +00001044 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +00001045 if (const ComplexType *CT = V->getType()->getAsComplexType())
1046 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001047
1048 // Otherwise they pass through real integer and floating point types here.
1049 if (V->getType()->isArithmeticType())
1050 return V->getType();
1051
1052 // Reject anything else.
Chris Lattnerd1625842008-11-24 06:25:27 +00001053 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001054 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001055}
1056
1057
Reid Spencer5f016e22007-07-11 17:01:13 +00001058
Douglas Gregor74253732008-11-19 15:42:04 +00001059Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001060 tok::TokenKind Kind,
1061 ExprTy *Input) {
Douglas Gregor74253732008-11-19 15:42:04 +00001062 Expr *Arg = (Expr *)Input;
1063
Reid Spencer5f016e22007-07-11 17:01:13 +00001064 UnaryOperator::Opcode Opc;
1065 switch (Kind) {
1066 default: assert(0 && "Unknown unary op!");
1067 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1068 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1069 }
Douglas Gregor74253732008-11-19 15:42:04 +00001070
1071 if (getLangOptions().CPlusPlus &&
1072 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1073 // Which overloaded operator?
1074 OverloadedOperatorKind OverOp =
1075 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1076
1077 // C++ [over.inc]p1:
1078 //
1079 // [...] If the function is a member function with one
1080 // parameter (which shall be of type int) or a non-member
1081 // function with two parameters (the second of which shall be
1082 // of type int), it defines the postfix increment operator ++
1083 // for objects of that type. When the postfix increment is
1084 // called as a result of using the ++ operator, the int
1085 // argument will have value zero.
1086 Expr *Args[2] = {
1087 Arg,
1088 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1089 /*isSigned=*/true),
1090 Context.IntTy, SourceLocation())
1091 };
1092
1093 // Build the candidate set for overloading
1094 OverloadCandidateSet CandidateSet;
1095 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
1096
1097 // Perform overload resolution.
1098 OverloadCandidateSet::iterator Best;
1099 switch (BestViableFunction(CandidateSet, Best)) {
1100 case OR_Success: {
1101 // We found a built-in operator or an overloaded operator.
1102 FunctionDecl *FnDecl = Best->Function;
1103
1104 if (FnDecl) {
1105 // We matched an overloaded operator. Build a call to that
1106 // operator.
1107
1108 // Convert the arguments.
1109 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1110 if (PerformObjectArgumentInitialization(Arg, Method))
1111 return true;
1112 } else {
1113 // Convert the arguments.
1114 if (PerformCopyInitialization(Arg,
1115 FnDecl->getParamDecl(0)->getType(),
1116 "passing"))
1117 return true;
1118 }
1119
1120 // Determine the result type
1121 QualType ResultTy
1122 = FnDecl->getType()->getAsFunctionType()->getResultType();
1123 ResultTy = ResultTy.getNonReferenceType();
1124
1125 // Build the actual expression node.
1126 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1127 SourceLocation());
1128 UsualUnaryConversions(FnExpr);
1129
1130 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
1131 } else {
1132 // We matched a built-in operator. Convert the arguments, then
1133 // break out so that we will build the appropriate built-in
1134 // operator node.
1135 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1136 "passing"))
1137 return true;
1138
1139 break;
1140 }
1141 }
1142
1143 case OR_No_Viable_Function:
1144 // No viable function; fall through to handling this as a
1145 // built-in operator, which will produce an error message for us.
1146 break;
1147
1148 case OR_Ambiguous:
1149 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1150 << UnaryOperator::getOpcodeStr(Opc)
1151 << Arg->getSourceRange();
1152 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1153 return true;
1154 }
1155
1156 // Either we found no viable overloaded operator or we matched a
1157 // built-in operator. In either case, fall through to trying to
1158 // build a built-in operation.
1159 }
1160
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00001161 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1162 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001163 if (result.isNull())
1164 return true;
Douglas Gregor74253732008-11-19 15:42:04 +00001165 return new UnaryOperator(Arg, Opc, result, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001166}
1167
1168Action::ExprResult Sema::
Douglas Gregor337c6b92008-11-19 17:17:41 +00001169ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001170 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +00001171 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +00001172
Douglas Gregor337c6b92008-11-19 17:17:41 +00001173 if (getLangOptions().CPlusPlus &&
Eli Friedman03f332a2008-12-15 22:34:21 +00001174 (LHSExp->getType()->isRecordType() ||
1175 LHSExp->getType()->isEnumeralType() ||
1176 RHSExp->getType()->isRecordType() ||
1177 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor337c6b92008-11-19 17:17:41 +00001178 // Add the appropriate overloaded operators (C++ [over.match.oper])
1179 // to the candidate set.
1180 OverloadCandidateSet CandidateSet;
1181 Expr *Args[2] = { LHSExp, RHSExp };
1182 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
1183
1184 // Perform overload resolution.
1185 OverloadCandidateSet::iterator Best;
1186 switch (BestViableFunction(CandidateSet, Best)) {
1187 case OR_Success: {
1188 // We found a built-in operator or an overloaded operator.
1189 FunctionDecl *FnDecl = Best->Function;
1190
1191 if (FnDecl) {
1192 // We matched an overloaded operator. Build a call to that
1193 // operator.
1194
1195 // Convert the arguments.
1196 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1197 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1198 PerformCopyInitialization(RHSExp,
1199 FnDecl->getParamDecl(0)->getType(),
1200 "passing"))
1201 return true;
1202 } else {
1203 // Convert the arguments.
1204 if (PerformCopyInitialization(LHSExp,
1205 FnDecl->getParamDecl(0)->getType(),
1206 "passing") ||
1207 PerformCopyInitialization(RHSExp,
1208 FnDecl->getParamDecl(1)->getType(),
1209 "passing"))
1210 return true;
1211 }
1212
1213 // Determine the result type
1214 QualType ResultTy
1215 = FnDecl->getType()->getAsFunctionType()->getResultType();
1216 ResultTy = ResultTy.getNonReferenceType();
1217
1218 // Build the actual expression node.
1219 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1220 SourceLocation());
1221 UsualUnaryConversions(FnExpr);
1222
1223 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
1224 } else {
1225 // We matched a built-in operator. Convert the arguments, then
1226 // break out so that we will build the appropriate built-in
1227 // operator node.
1228 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1229 "passing") ||
1230 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1231 "passing"))
1232 return true;
1233
1234 break;
1235 }
1236 }
1237
1238 case OR_No_Viable_Function:
1239 // No viable function; fall through to handling this as a
1240 // built-in operator, which will produce an error message for us.
1241 break;
1242
1243 case OR_Ambiguous:
1244 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1245 << "[]"
1246 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1247 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1248 return true;
1249 }
1250
1251 // Either we found no viable overloaded operator or we matched a
1252 // built-in operator. In either case, fall through to trying to
1253 // build a built-in operation.
1254 }
1255
Chris Lattner12d9ff62007-07-16 00:14:47 +00001256 // Perform default conversions.
1257 DefaultFunctionArrayConversion(LHSExp);
1258 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +00001259
Chris Lattner12d9ff62007-07-16 00:14:47 +00001260 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001261
Reid Spencer5f016e22007-07-11 17:01:13 +00001262 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001263 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +00001264 // in the subscript position. As a result, we need to derive the array base
1265 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001266 Expr *BaseExpr, *IndexExpr;
1267 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +00001268 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001269 BaseExpr = LHSExp;
1270 IndexExpr = RHSExp;
1271 // FIXME: need to deal with const...
1272 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +00001273 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001274 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001275 BaseExpr = RHSExp;
1276 IndexExpr = LHSExp;
1277 // FIXME: need to deal with const...
1278 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +00001279 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1280 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001281 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +00001282
1283 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +00001284 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1285 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001286 return Diag(LLoc, diag::err_ext_vector_component_access)
1287 << SourceRange(LLoc, RLoc);
Chris Lattner12d9ff62007-07-16 00:14:47 +00001288 // FIXME: need to deal with const...
1289 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001290 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001291 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
1292 << RHSExp->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 }
1294 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +00001295 if (!IndexExpr->getType()->isIntegerType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001296 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
1297 << IndexExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001298
Chris Lattner12d9ff62007-07-16 00:14:47 +00001299 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1300 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001301 // void (*)(int)) and pointers to incomplete types. Functions are not
1302 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001303 if (!ResultType->isObjectType())
1304 return Diag(BaseExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001305 diag::err_typecheck_subscript_not_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00001306 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner12d9ff62007-07-16 00:14:47 +00001307
1308 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001309}
1310
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001311QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001312CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001313 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001314 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001315
1316 // This flag determines whether or not the component is to be treated as a
1317 // special name, or a regular GLSL-style component access.
1318 bool SpecialComponent = false;
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001319
1320 // The vector accessor can't exceed the number of elements.
1321 const char *compStr = CompName.getName();
1322 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001323 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattnerd1625842008-11-24 06:25:27 +00001324 << baseType << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001325 return QualType();
1326 }
Nate Begeman8a997642008-05-09 06:41:27 +00001327
1328 // Check that we've found one of the special components, or that the component
1329 // names must come from the same set.
1330 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1331 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1332 SpecialComponent = true;
1333 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001334 do
1335 compStr++;
1336 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1337 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1338 do
1339 compStr++;
1340 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1341 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1342 do
1343 compStr++;
1344 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1345 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001346
Nate Begeman8a997642008-05-09 06:41:27 +00001347 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001348 // We didn't get to the end of the string. This means the component names
1349 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001350 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1351 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001352 return QualType();
1353 }
1354 // Each component accessor can't exceed the vector type.
1355 compStr = CompName.getName();
1356 while (*compStr) {
1357 if (vecType->isAccessorWithinNumElements(*compStr))
1358 compStr++;
1359 else
1360 break;
1361 }
Nate Begeman8a997642008-05-09 06:41:27 +00001362 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001363 // We didn't get to the end of the string. This means a component accessor
1364 // exceeds the number of elements in the vector.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001365 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattnerd1625842008-11-24 06:25:27 +00001366 << baseType << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001367 return QualType();
1368 }
Nate Begeman8a997642008-05-09 06:41:27 +00001369
1370 // If we have a special component name, verify that the current vector length
1371 // is an even number, since all special component names return exactly half
1372 // the elements.
1373 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001374 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001375 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001376 return QualType();
1377 }
1378
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001379 // The component accessor looks fine - now we need to compute the actual type.
1380 // The vector type is implied by the component accessor. For example,
1381 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001382 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1383 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner3c73c412008-11-19 08:23:25 +00001384 : CompName.getLength();
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001385 if (CompSize == 1)
1386 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +00001387
Nate Begeman213541a2008-04-18 23:10:10 +00001388 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +00001389 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001390 // diagostics look bad. We want extended vector types to appear built-in.
1391 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1392 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1393 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001394 }
1395 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001396}
1397
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001398/// constructSetterName - Return the setter name for the given
1399/// identifier, i.e. "set" + Name where the initial character of Name
1400/// has been capitalized.
1401// FIXME: Merge with same routine in Parser. But where should this
1402// live?
1403static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1404 const IdentifierInfo *Name) {
1405 llvm::SmallString<100> SelectorName;
1406 SelectorName = "set";
1407 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1408 SelectorName[3] = toupper(SelectorName[3]);
1409 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1410}
1411
Reid Spencer5f016e22007-07-11 17:01:13 +00001412Action::ExprResult Sema::
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001413ActOnMemberReferenceExpr(Scope *S, ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001414 tok::TokenKind OpKind, SourceLocation MemberLoc,
1415 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001416 Expr *BaseExpr = static_cast<Expr *>(Base);
1417 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +00001418
1419 // Perform default conversions.
1420 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001421
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001422 QualType BaseType = BaseExpr->getType();
1423 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00001424
Chris Lattner68a057b2008-07-21 04:36:39 +00001425 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1426 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001427 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +00001428 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001429 BaseType = PT->getPointeeType();
Douglas Gregor8ba10742008-11-20 16:27:02 +00001430 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001431 return BuildOverloadedArrowExpr(S, BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001432 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001433 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00001434 << BaseType << BaseExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001435 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001436
Chris Lattner68a057b2008-07-21 04:36:39 +00001437 // Handle field access to simple records. This also handles access to fields
1438 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +00001439 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001440 RecordDecl *RDecl = RTy->getDecl();
1441 if (RTy->isIncompleteType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001442 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001443 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001444 // The record definition is complete, now make sure the member is valid.
Douglas Gregor44b43212008-12-11 16:49:14 +00001445 // FIXME: Qualified name lookup for C++ is a bit more complicated
1446 // than this.
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001447 Decl *MemberDecl = LookupDecl(DeclarationName(&Member), Decl::IDNS_Ordinary,
1448 S, RDecl, false, false);
1449 if (!MemberDecl)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001450 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner3c73c412008-11-19 08:23:25 +00001451 << &Member << BaseExpr->getSourceRange();
Douglas Gregor44b43212008-12-11 16:49:14 +00001452
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001453 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001454 // We may have found a field within an anonymous union or struct
1455 // (C++ [class.union]).
1456 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1457 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
1458 BaseExpr, OpLoc);
1459
Douglas Gregor86f19402008-12-20 23:49:58 +00001460 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1461 // FIXME: Handle address space modifiers
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001462 QualType MemberType = FD->getType();
Douglas Gregor86f19402008-12-20 23:49:58 +00001463 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1464 MemberType = Ref->getPointeeType();
1465 else {
1466 unsigned combinedQualifiers =
1467 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001468 if (FD->isMutable())
Douglas Gregor86f19402008-12-20 23:49:58 +00001469 combinedQualifiers &= ~QualType::Const;
1470 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1471 }
Eli Friedman51019072008-02-06 22:48:16 +00001472
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001473 return new MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
Douglas Gregor86f19402008-12-20 23:49:58 +00001474 MemberLoc, MemberType);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001475 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Douglas Gregor86f19402008-12-20 23:49:58 +00001476 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Var, MemberLoc,
1477 Var->getType().getNonReferenceType());
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001478 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Douglas Gregor86f19402008-12-20 23:49:58 +00001479 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberFn, MemberLoc,
1480 MemberFn->getType());
1481 else if (OverloadedFunctionDecl *Ovl
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001482 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Douglas Gregor86f19402008-12-20 23:49:58 +00001483 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl, MemberLoc,
1484 Context.OverloadTy);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001485 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Douglas Gregor86f19402008-12-20 23:49:58 +00001486 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Enum, MemberLoc,
1487 Enum->getType());
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001488 else if (isa<TypeDecl>(MemberDecl))
Douglas Gregor86f19402008-12-20 23:49:58 +00001489 return Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1490 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Eli Friedman51019072008-02-06 22:48:16 +00001491
Douglas Gregor86f19402008-12-20 23:49:58 +00001492 // We found a declaration kind that we didn't expect. This is a
1493 // generic error message that tells the user that she can't refer
1494 // to this member with '.' or '->'.
1495 return Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1496 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001497 }
1498
Chris Lattnera38e6b12008-07-21 04:59:05 +00001499 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1500 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +00001501 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001502 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +00001503 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc,
1504 BaseExpr,
1505 OpKind == tok::arrow);
1506 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
1507 return MRef;
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001508 }
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001509 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001510 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001511 << BaseExpr->getSourceRange();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001512 }
1513
Chris Lattnera38e6b12008-07-21 04:59:05 +00001514 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1515 // pointer to a (potentially qualified) interface type.
1516 const PointerType *PTy;
1517 const ObjCInterfaceType *IFTy;
1518 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1519 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1520 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001521
Daniel Dunbar2307d312008-09-03 01:05:41 +00001522 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +00001523 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1524 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1525
Daniel Dunbar2307d312008-09-03 01:05:41 +00001526 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00001527 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1528 E = IFTy->qual_end(); I != E; ++I)
1529 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1530 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +00001531
1532 // If that failed, look for an "implicit" property by seeing if the nullary
1533 // selector is implemented.
1534
1535 // FIXME: The logic for looking up nullary and unary selectors should be
1536 // shared with the code in ActOnInstanceMessage.
1537
1538 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1539 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1540
1541 // If this reference is in an @implementation, check for 'private' methods.
1542 if (!Getter)
1543 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1544 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1545 if (ObjCImplementationDecl *ImpDecl =
1546 ObjCImplementations[ClassDecl->getIdentifier()])
1547 Getter = ImpDecl->getInstanceMethod(Sel);
1548
Steve Naroff7692ed62008-10-22 19:16:27 +00001549 // Look through local category implementations associated with the class.
1550 if (!Getter) {
1551 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1552 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1553 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1554 }
1555 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001556 if (Getter) {
1557 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001558 // will look for the matching setter, in case it is needed.
1559 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1560 &Member);
1561 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1562 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1563 if (!Setter) {
1564 // If this reference is in an @implementation, also check for 'private'
1565 // methods.
1566 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1567 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1568 if (ObjCImplementationDecl *ImpDecl =
1569 ObjCImplementations[ClassDecl->getIdentifier()])
1570 Setter = ImpDecl->getInstanceMethod(SetterSel);
1571 }
1572 // Look through local category implementations associated with the class.
1573 if (!Setter) {
1574 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1575 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1576 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1577 }
1578 }
1579
1580 // FIXME: we must check that the setter has property type.
1581 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00001582 MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +00001583 }
Anders Carlsson00165a22008-12-19 17:27:57 +00001584
1585 return Diag(MemberLoc, diag::err_property_not_found) <<
1586 &Member << BaseType;
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001587 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001588 // Handle properties on qualified "id" protocols.
1589 const ObjCQualifiedIdType *QIdTy;
1590 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1591 // Check protocols on qualified interfaces.
1592 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001593 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroff18bc1642008-10-20 22:53:06 +00001594 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1595 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001596 // Also must look for a getter name which uses property syntax.
1597 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1598 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1599 return new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(), OMD,
1600 OpLoc, MemberLoc, NULL, 0);
1601 }
1602 }
Anders Carlsson00165a22008-12-19 17:27:57 +00001603
1604 return Diag(MemberLoc, diag::err_property_not_found) <<
1605 &Member << BaseType;
Steve Naroff18bc1642008-10-20 22:53:06 +00001606 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001607 // Handle 'field access' to vectors, such as 'V.xx'.
1608 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1609 // Component access limited to variables (reject vec4.rg.g).
1610 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1611 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001612 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1613 << BaseExpr->getSourceRange();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001614 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1615 if (ret.isNull())
1616 return true;
1617 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1618 }
1619
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001620 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattnerd1625842008-11-24 06:25:27 +00001621 << BaseType << BaseExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001622}
1623
Douglas Gregor88a35142008-12-22 05:46:06 +00001624/// ConvertArgumentsForCall - Converts the arguments specified in
1625/// Args/NumArgs to the parameter types of the function FDecl with
1626/// function prototype Proto. Call is the call expression itself, and
1627/// Fn is the function expression. For a C++ member function, this
1628/// routine does not attempt to convert the object argument. Returns
1629/// true if the call is ill-formed.
1630bool
1631Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1632 FunctionDecl *FDecl,
1633 const FunctionTypeProto *Proto,
1634 Expr **Args, unsigned NumArgs,
1635 SourceLocation RParenLoc) {
1636 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1637 // assignment, to the types of the corresponding parameter, ...
1638 unsigned NumArgsInProto = Proto->getNumArgs();
1639 unsigned NumArgsToCheck = NumArgs;
1640
1641 // If too few arguments are available (and we don't have default
1642 // arguments for the remaining parameters), don't make the call.
1643 if (NumArgs < NumArgsInProto) {
1644 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1645 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1646 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1647 // Use default arguments for missing arguments
1648 NumArgsToCheck = NumArgsInProto;
1649 Call->setNumArgs(NumArgsInProto);
1650 }
1651
1652 // If too many are passed and not variadic, error on the extras and drop
1653 // them.
1654 if (NumArgs > NumArgsInProto) {
1655 if (!Proto->isVariadic()) {
1656 Diag(Args[NumArgsInProto]->getLocStart(),
1657 diag::err_typecheck_call_too_many_args)
1658 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1659 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1660 Args[NumArgs-1]->getLocEnd());
1661 // This deletes the extra arguments.
1662 Call->setNumArgs(NumArgsInProto);
1663 }
1664 NumArgsToCheck = NumArgsInProto;
1665 }
1666
1667 // Continue to check argument types (even if we have too few/many args).
1668 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1669 QualType ProtoArgType = Proto->getArgType(i);
1670
1671 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00001672 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001673 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00001674
1675 // Pass the argument.
1676 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1677 return true;
1678 } else
1679 // We already type-checked the argument, so we know it works.
Douglas Gregor88a35142008-12-22 05:46:06 +00001680 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
1681 QualType ArgType = Arg->getType();
Douglas Gregor61366e92008-12-24 00:01:03 +00001682
Douglas Gregor88a35142008-12-22 05:46:06 +00001683 Call->setArg(i, Arg);
1684 }
1685
1686 // If this is a variadic call, handle args passed through "...".
1687 if (Proto->isVariadic()) {
1688 // Promote the arguments (C99 6.5.2.2p7).
1689 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1690 Expr *Arg = Args[i];
Anders Carlsson906fed02009-01-13 05:48:52 +00001691 if (!Arg->getType()->isPODType()) {
1692 int CallType = 0;
1693 if (Fn->getType()->isBlockPointerType())
1694 CallType = 1; // Block
1695 else if (isa<MemberExpr>(Fn))
1696 CallType = 2;
1697
1698 Diag(Arg->getLocStart(),
1699 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
1700 Arg->getType() << CallType;
1701 }
Douglas Gregor88a35142008-12-22 05:46:06 +00001702 DefaultArgumentPromotion(Arg);
1703 Call->setArg(i, Arg);
1704 }
1705 }
1706
1707 return false;
1708}
1709
Steve Narofff69936d2007-09-16 03:34:24 +00001710/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001711/// This provides the location of the left/right parens and a list of comma
1712/// locations.
Douglas Gregor88a35142008-12-22 05:46:06 +00001713Action::ExprResult
1714Sema::ActOnCallExpr(Scope *S, ExprTy *fn, SourceLocation LParenLoc,
1715 ExprTy **args, unsigned NumArgs,
1716 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +00001717 Expr *Fn = static_cast<Expr *>(fn);
1718 Expr **Args = reinterpret_cast<Expr**>(args);
1719 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001720 FunctionDecl *FDecl = NULL;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001721 OverloadedFunctionDecl *Ovl = NULL;
1722
Douglas Gregor5c37de72008-12-06 00:22:45 +00001723 // Determine whether this is a dependent call inside a C++ template,
1724 // in which case we won't do any semantic analysis now.
1725 bool Dependent = false;
1726 if (Fn->isTypeDependent()) {
1727 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1728 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1729 Dependent = true;
1730 else {
1731 // Resolve the CXXDependentNameExpr to an actual identifier;
1732 // it wasn't really a dependent name after all.
1733 ExprResult Resolved
1734 = ActOnDeclarationNameExpr(S, FnName->getLocation(), FnName->getName(),
1735 /*HasTrailingLParen=*/true,
1736 /*SS=*/0,
1737 /*ForceResolution=*/true);
1738 if (Resolved.isInvalid)
1739 return true;
1740 else {
1741 delete Fn;
1742 Fn = (Expr *)Resolved.Val;
1743 }
1744 }
1745 } else
1746 Dependent = true;
1747 } else
1748 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1749
Douglas Gregor898574e2008-12-05 23:32:09 +00001750 // FIXME: Will need to cache the results of name lookup (including
1751 // ADL) in Fn.
Douglas Gregor5c37de72008-12-06 00:22:45 +00001752 if (Dependent)
Douglas Gregor898574e2008-12-05 23:32:09 +00001753 return new CallExpr(Fn, Args, NumArgs, Context.DependentTy, RParenLoc);
1754
Douglas Gregor88a35142008-12-22 05:46:06 +00001755 // Determine whether this is a call to an object (C++ [over.call.object]).
1756 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
1757 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1758 CommaLocs, RParenLoc);
1759
1760 // Determine whether this is a call to a member function.
1761 if (getLangOptions().CPlusPlus) {
1762 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1763 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1764 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
1765 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1766 CommaLocs, RParenLoc);
1767 }
1768
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001769 // If we're directly calling a function or a set of overloaded
1770 // functions, get the appropriate declaration.
Douglas Gregor1a49af92009-01-06 05:10:23 +00001771 DeclRefExpr *DRExpr = NULL;
1772 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1773 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1774 else
1775 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1776
1777 if (DRExpr) {
1778 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1779 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001780 }
1781
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001782 if (Ovl) {
Douglas Gregor0a396682008-11-26 06:01:48 +00001783 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1784 RParenLoc);
1785 if (!FDecl)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001786 return true;
1787
Douglas Gregor0a396682008-11-26 06:01:48 +00001788 // Update Fn to refer to the actual function selected.
Douglas Gregor1a49af92009-01-06 05:10:23 +00001789 Expr *NewFn = 0;
1790 if (QualifiedDeclRefExpr *QDRExpr = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
1791 NewFn = new QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1792 QDRExpr->getLocation(), false, false,
1793 QDRExpr->getSourceRange().getBegin());
1794 else
1795 NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1796 Fn->getSourceRange().getBegin());
Douglas Gregor0a396682008-11-26 06:01:48 +00001797 Fn->Destroy(Context);
1798 Fn = NewFn;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001799 }
Chris Lattner04421082008-04-08 04:40:51 +00001800
1801 // Promote the function operand.
1802 UsualUnaryConversions(Fn);
1803
Chris Lattner925e60d2007-12-28 05:29:59 +00001804 // Make the call expr early, before semantic checks. This guarantees cleanup
1805 // of arguments and function on error.
Chris Lattner8123a952008-04-10 02:22:51 +00001806 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001807 Context.BoolTy, RParenLoc));
Douglas Gregor898574e2008-12-05 23:32:09 +00001808
Steve Naroffdd972f22008-09-05 22:11:13 +00001809 const FunctionType *FuncT;
1810 if (!Fn->getType()->isBlockPointerType()) {
1811 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1812 // have type pointer to function".
1813 const PointerType *PT = Fn->getType()->getAsPointerType();
1814 if (PT == 0)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001815 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattnerd1625842008-11-24 06:25:27 +00001816 << Fn->getType() << Fn->getSourceRange();
Steve Naroffdd972f22008-09-05 22:11:13 +00001817 FuncT = PT->getPointeeType()->getAsFunctionType();
1818 } else { // This is a block call.
1819 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1820 getAsFunctionType();
1821 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001822 if (FuncT == 0)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001823 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattnerd1625842008-11-24 06:25:27 +00001824 << Fn->getType() << Fn->getSourceRange();
Chris Lattner925e60d2007-12-28 05:29:59 +00001825
1826 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001827 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001828
Chris Lattner925e60d2007-12-28 05:29:59 +00001829 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001830 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1831 RParenLoc))
1832 return true;
Chris Lattner925e60d2007-12-28 05:29:59 +00001833 } else {
1834 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1835
Steve Naroffb291ab62007-08-28 23:30:39 +00001836 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001837 for (unsigned i = 0; i != NumArgs; i++) {
1838 Expr *Arg = Args[i];
1839 DefaultArgumentPromotion(Arg);
1840 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001841 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001842 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001843
Douglas Gregor88a35142008-12-22 05:46:06 +00001844 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1845 if (!Method->isStatic())
1846 return Diag(LParenLoc, diag::err_member_call_without_object)
1847 << Fn->getSourceRange();
1848
Chris Lattner59907c42007-08-10 20:18:51 +00001849 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001850 if (FDecl)
1851 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001852
Chris Lattner925e60d2007-12-28 05:29:59 +00001853 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001854}
1855
1856Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001857ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +00001858 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001859 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001860 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001861 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001862 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +00001863 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +00001864
Eli Friedman6223c222008-05-20 05:22:08 +00001865 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001866 if (literalType->isVariableArrayType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001867 return Diag(LParenLoc, diag::err_variable_object_no_init)
1868 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman6223c222008-05-20 05:22:08 +00001869 } else if (literalType->isIncompleteType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001870 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001871 << literalType
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001872 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman6223c222008-05-20 05:22:08 +00001873 }
1874
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001875 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001876 DeclarationName()))
Steve Naroff58d18212008-01-09 20:58:06 +00001877 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +00001878
Chris Lattner371f2582008-12-04 23:50:19 +00001879 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00001880 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001881 if (CheckForConstantInitializer(literalExpr, literalType))
1882 return true;
1883 }
Chris Lattner220ad7c2008-10-26 23:35:51 +00001884 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1885 isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001886}
1887
1888Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001889ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattner220ad7c2008-10-26 23:35:51 +00001890 InitListDesignations &Designators,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001891 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +00001892 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001893
Steve Naroff08d92e42007-09-15 18:49:24 +00001894 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001895 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001896
Chris Lattner418f6c72008-10-26 23:43:26 +00001897 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1898 Designators.hasAnyDesignators());
Chris Lattnerf0467b32008-04-02 04:24:33 +00001899 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1900 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001901}
1902
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001903/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001904bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001905 UsualUnaryConversions(castExpr);
1906
1907 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1908 // type needs to be scalar.
1909 if (castType->isVoidType()) {
1910 // Cast to void allows any expr type.
Douglas Gregor898574e2008-12-05 23:32:09 +00001911 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1912 // We can't check any more until template instantiation time.
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001913 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1914 // GCC struct/union extension: allow cast to self.
1915 if (Context.getCanonicalType(castType) !=
1916 Context.getCanonicalType(castExpr->getType()) ||
1917 (!castType->isStructureType() && !castType->isUnionType())) {
1918 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001919 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00001920 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001921 }
1922
1923 // accept this, but emit an ext-warn.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001924 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00001925 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001926 } else if (!castExpr->getType()->isScalarType() &&
1927 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001928 return Diag(castExpr->getLocStart(),
1929 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00001930 << castExpr->getType() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001931 } else if (castExpr->getType()->isVectorType()) {
1932 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1933 return true;
1934 } else if (castType->isVectorType()) {
1935 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1936 return true;
1937 }
1938 return false;
1939}
1940
Chris Lattnerfe23e212007-12-20 00:44:32 +00001941bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00001942 assert(VectorTy->isVectorType() && "Not a vector type!");
1943
1944 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00001945 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00001946 return Diag(R.getBegin(),
1947 Ty->isVectorType() ?
1948 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001949 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00001950 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00001951 } else
1952 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001953 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00001954 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00001955
1956 return false;
1957}
1958
Steve Naroff4aa88f82007-07-19 01:06:55 +00001959Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001960ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +00001961 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +00001962 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00001963
1964 Expr *castExpr = static_cast<Expr*>(Op);
1965 QualType castType = QualType::getFromOpaquePtr(Ty);
1966
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001967 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1968 return true;
Steve Naroffb2f9e512008-11-03 23:29:32 +00001969 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001970}
1971
Chris Lattnera21ddb32007-11-26 01:40:58 +00001972/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1973/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00001974inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00001975 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001976 UsualUnaryConversions(cond);
1977 UsualUnaryConversions(lex);
1978 UsualUnaryConversions(rex);
1979 QualType condT = cond->getType();
1980 QualType lexT = lex->getType();
1981 QualType rexT = rex->getType();
1982
Reid Spencer5f016e22007-07-11 17:01:13 +00001983 // first, check the condition.
Douglas Gregor898574e2008-12-05 23:32:09 +00001984 if (!cond->isTypeDependent()) {
1985 if (!condT->isScalarType()) { // C99 6.5.15p2
1986 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
1987 return QualType();
1988 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001989 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001990
1991 // Now check the two expressions.
Douglas Gregor898574e2008-12-05 23:32:09 +00001992 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
1993 return Context.DependentTy;
1994
Chris Lattner70d67a92008-01-06 22:42:25 +00001995 // If both operands have arithmetic type, do the usual arithmetic conversions
1996 // to find a common type: C99 6.5.15p3,5.
1997 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00001998 UsualArithmeticConversions(lex, rex);
1999 return lex->getType();
2000 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002001
2002 // If both operands are the same structure or union type, the result is that
2003 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002004 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00002005 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00002006 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00002007 // "If both the operands have structure or union type, the result has
2008 // that type." This implies that CV qualifiers are dropped.
2009 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002010 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002011
2012 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00002013 // The following || allows only one side to be void (a GCC-ism).
2014 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00002015 if (!lexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002016 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2017 << rex->getSourceRange();
Steve Naroffe701c0a2008-05-12 21:44:38 +00002018 if (!rexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002019 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2020 << lex->getSourceRange();
Eli Friedman0e724012008-06-04 19:47:51 +00002021 ImpCastExprToType(lex, Context.VoidTy);
2022 ImpCastExprToType(rex, Context.VoidTy);
2023 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00002024 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00002025 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2026 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002027 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2028 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002029 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002030 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002031 return lexT;
2032 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002033 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2034 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002035 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002036 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002037 return rexT;
2038 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00002039 // Handle the case where both operands are pointers before we handle null
2040 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002041 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2042 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2043 // get the "pointed to" types
2044 QualType lhptee = LHSPT->getPointeeType();
2045 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002046
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002047 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2048 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00002049 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002050 // Figure out necessary qualifiers (C99 6.5.15p6)
2051 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002052 QualType destType = Context.getPointerType(destPointee);
2053 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2054 ImpCastExprToType(rex, destType); // promote to void*
2055 return destType;
2056 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00002057 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002058 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002059 QualType destType = Context.getPointerType(destPointee);
2060 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2061 ImpCastExprToType(rex, destType); // promote to void*
2062 return destType;
2063 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002064
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002065 QualType compositeType = lexT;
2066
2067 // If either type is an Objective-C object type then check
2068 // compatibility according to Objective-C.
2069 if (Context.isObjCObjectPointerType(lexT) ||
2070 Context.isObjCObjectPointerType(rexT)) {
2071 // If both operands are interfaces and either operand can be
2072 // assigned to the other, use that type as the composite
2073 // type. This allows
2074 // xxx ? (A*) a : (B*) b
2075 // where B is a subclass of A.
2076 //
2077 // Additionally, as for assignment, if either type is 'id'
2078 // allow silent coercion. Finally, if the types are
2079 // incompatible then make sure to use 'id' as the composite
2080 // type so the result is acceptable for sending messages to.
2081
2082 // FIXME: This code should not be localized to here. Also this
2083 // should use a compatible check instead of abusing the
2084 // canAssignObjCInterfaces code.
2085 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2086 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2087 if (LHSIface && RHSIface &&
2088 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2089 compositeType = lexT;
2090 } else if (LHSIface && RHSIface &&
Douglas Gregor7ffd0de2008-11-26 06:43:45 +00002091 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002092 compositeType = rexT;
2093 } else if (Context.isObjCIdType(lhptee) ||
2094 Context.isObjCIdType(rhptee)) {
2095 // FIXME: This code looks wrong, because isObjCIdType checks
2096 // the struct but getObjCIdType returns the pointer to
2097 // struct. This is horrible and should be fixed.
2098 compositeType = Context.getObjCIdType();
2099 } else {
2100 QualType incompatTy = Context.getObjCIdType();
2101 ImpCastExprToType(lex, incompatTy);
2102 ImpCastExprToType(rex, incompatTy);
2103 return incompatTy;
2104 }
2105 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2106 rhptee.getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002107 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002108 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002109 // In this situation, we assume void* type. No especially good
2110 // reason, but this is what gcc does, and we do have to pick
2111 // to get a consistent AST.
2112 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00002113 ImpCastExprToType(lex, incompatTy);
2114 ImpCastExprToType(rex, incompatTy);
2115 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002116 }
2117 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002118 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2119 // differently qualified versions of compatible types, the result type is
2120 // a pointer to an appropriately qualified version of the *composite*
2121 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00002122 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00002123 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00002124 ImpCastExprToType(lex, compositeType);
2125 ImpCastExprToType(rex, compositeType);
2126 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002127 }
2128 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002129 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2130 // evaluates to "struct objc_object *" (and is handled above when comparing
2131 // id with statically typed objects).
2132 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2133 // GCC allows qualified id and any Objective-C type to devolve to
2134 // id. Currently localizing to here until clear this should be
2135 // part of ObjCQualifiedIdTypesAreCompatible.
2136 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2137 (lexT->isObjCQualifiedIdType() &&
2138 Context.isObjCObjectPointerType(rexT)) ||
2139 (rexT->isObjCQualifiedIdType() &&
2140 Context.isObjCObjectPointerType(lexT))) {
2141 // FIXME: This is not the correct composite type. This only
2142 // happens to work because id can more or less be used anywhere,
2143 // however this may change the type of method sends.
2144 // FIXME: gcc adds some type-checking of the arguments and emits
2145 // (confusing) incompatible comparison warnings in some
2146 // cases. Investigate.
2147 QualType compositeType = Context.getObjCIdType();
2148 ImpCastExprToType(lex, compositeType);
2149 ImpCastExprToType(rex, compositeType);
2150 return compositeType;
2151 }
2152 }
2153
Steve Naroff61f40a22008-09-10 19:17:48 +00002154 // Selection between block pointer types is ok as long as they are the same.
2155 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2156 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2157 return lexT;
2158
Chris Lattner70d67a92008-01-06 22:42:25 +00002159 // Otherwise, the operands are not compatible.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002160 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattnerd1625842008-11-24 06:25:27 +00002161 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002162 return QualType();
2163}
2164
Steve Narofff69936d2007-09-16 03:34:24 +00002165/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00002166/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00002167Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00002168 SourceLocation ColonLoc,
2169 ExprTy *Cond, ExprTy *LHS,
2170 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00002171 Expr *CondExpr = (Expr *) Cond;
2172 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00002173
2174 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2175 // was the condition.
2176 bool isLHSNull = LHSExpr == 0;
2177 if (isLHSNull)
2178 LHSExpr = CondExpr;
2179
Chris Lattner26824902007-07-16 21:39:03 +00002180 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
2181 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002182 if (result.isNull())
2183 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00002184 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
2185 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002186}
2187
Reid Spencer5f016e22007-07-11 17:01:13 +00002188
2189// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2190// being closely modeled after the C99 spec:-). The odd characteristic of this
2191// routine is it effectively iqnores the qualifiers on the top level pointee.
2192// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2193// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00002194Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002195Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2196 QualType lhptee, rhptee;
2197
2198 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002199 lhptee = lhsType->getAsPointerType()->getPointeeType();
2200 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002201
2202 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00002203 lhptee = Context.getCanonicalType(lhptee);
2204 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00002205
Chris Lattner5cf216b2008-01-04 18:04:52 +00002206 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002207
2208 // C99 6.5.16.1p1: This following citation is common to constraints
2209 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2210 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00002211 // FIXME: Handle ASQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00002212 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00002213 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00002214
2215 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2216 // incomplete type and the other is a pointer to a qualified or unqualified
2217 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002218 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002219 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002220 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002221
2222 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002223 assert(rhptee->isFunctionType());
2224 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002225 }
2226
2227 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002228 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002229 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002230
2231 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002232 assert(lhptee->isFunctionType());
2233 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002234 }
Eli Friedman3d815e72008-08-22 00:56:42 +00002235
2236 // Check for ObjC interfaces
2237 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2238 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2239 if (LHSIface && RHSIface &&
2240 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2241 return ConvTy;
2242
2243 // ID acts sort of like void* for ObjC interfaces
2244 if (LHSIface && Context.isObjCIdType(rhptee))
2245 return ConvTy;
2246 if (RHSIface && Context.isObjCIdType(lhptee))
2247 return ConvTy;
2248
Reid Spencer5f016e22007-07-11 17:01:13 +00002249 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2250 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002251 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2252 rhptee.getUnqualifiedType()))
2253 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00002254 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002255}
2256
Steve Naroff1c7d0672008-09-04 15:10:53 +00002257/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2258/// block pointer types are compatible or whether a block and normal pointer
2259/// are compatible. It is more restrict than comparing two function pointer
2260// types.
2261Sema::AssignConvertType
2262Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2263 QualType rhsType) {
2264 QualType lhptee, rhptee;
2265
2266 // get the "pointed to" type (ignoring qualifiers at the top level)
2267 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2268 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2269
2270 // make sure we operate on the canonical type
2271 lhptee = Context.getCanonicalType(lhptee);
2272 rhptee = Context.getCanonicalType(rhptee);
2273
2274 AssignConvertType ConvTy = Compatible;
2275
2276 // For blocks we enforce that qualifiers are identical.
2277 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2278 ConvTy = CompatiblePointerDiscardsQualifiers;
2279
2280 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2281 return IncompatibleBlockPointer;
2282 return ConvTy;
2283}
2284
Reid Spencer5f016e22007-07-11 17:01:13 +00002285/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2286/// has code to accommodate several GCC extensions when type checking
2287/// pointers. Here are some objectionable examples that GCC considers warnings:
2288///
2289/// int a, *pint;
2290/// short *pshort;
2291/// struct foo *pfoo;
2292///
2293/// pint = pshort; // warning: assignment from incompatible pointer type
2294/// a = pint; // warning: assignment makes integer from pointer without a cast
2295/// pint = a; // warning: assignment makes pointer from integer without a cast
2296/// pint = pfoo; // warning: assignment from incompatible pointer type
2297///
2298/// As a result, the code for dealing with pointers is more complex than the
2299/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00002300///
Chris Lattner5cf216b2008-01-04 18:04:52 +00002301Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002302Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00002303 // Get canonical types. We're not formatting these types, just comparing
2304 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002305 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2306 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002307
2308 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00002309 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00002310
Douglas Gregor9d293df2008-10-28 00:22:11 +00002311 // If the left-hand side is a reference type, then we are in a
2312 // (rare!) case where we've allowed the use of references in C,
2313 // e.g., as a parameter type in a built-in function. In this case,
2314 // just make sure that the type referenced is compatible with the
2315 // right-hand side type. The caller is responsible for adjusting
2316 // lhsType so that the resulting expression does not have reference
2317 // type.
2318 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2319 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00002320 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002321 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002322 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002323
Chris Lattnereca7be62008-04-07 05:30:13 +00002324 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2325 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002326 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00002327 // Relax integer conversions like we do for pointers below.
2328 if (rhsType->isIntegerType())
2329 return IntToPointer;
2330 if (lhsType->isIntegerType())
2331 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00002332 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002333 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00002334
Nate Begemanbe2341d2008-07-14 18:02:46 +00002335 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002336 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00002337 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2338 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00002339 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002340
Nate Begemanbe2341d2008-07-14 18:02:46 +00002341 // If we are allowing lax vector conversions, and LHS and RHS are both
2342 // vectors, the total size only needs to be the same. This is a bitcast;
2343 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00002344 if (getLangOptions().LaxVectorConversions &&
2345 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002346 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2347 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00002348 }
2349 return Incompatible;
2350 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002351
Chris Lattnere8b3e962008-01-04 23:32:24 +00002352 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002353 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002354
Chris Lattner78eca282008-04-07 06:49:41 +00002355 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002356 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002357 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002358
Chris Lattner78eca282008-04-07 06:49:41 +00002359 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002360 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002361
Steve Naroffb4406862008-09-29 18:10:17 +00002362 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00002363 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002364 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00002365
2366 // Treat block pointers as objects.
2367 if (getLangOptions().ObjC1 &&
2368 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2369 return Compatible;
2370 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002371 return Incompatible;
2372 }
2373
2374 if (isa<BlockPointerType>(lhsType)) {
2375 if (rhsType->isIntegerType())
2376 return IntToPointer;
2377
Steve Naroffb4406862008-09-29 18:10:17 +00002378 // Treat block pointers as objects.
2379 if (getLangOptions().ObjC1 &&
2380 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2381 return Compatible;
2382
Steve Naroff1c7d0672008-09-04 15:10:53 +00002383 if (rhsType->isBlockPointerType())
2384 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2385
2386 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2387 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002388 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002389 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00002390 return Incompatible;
2391 }
2392
Chris Lattner78eca282008-04-07 06:49:41 +00002393 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002394 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002395 if (lhsType == Context.BoolTy)
2396 return Compatible;
2397
2398 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002399 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00002400
Chris Lattner78eca282008-04-07 06:49:41 +00002401 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002402 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002403
2404 if (isa<BlockPointerType>(lhsType) &&
2405 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002406 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002407 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002408 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002409
Chris Lattnerfc144e22008-01-04 23:18:45 +00002410 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00002411 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002412 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002413 }
2414 return Incompatible;
2415}
2416
Chris Lattner5cf216b2008-01-04 18:04:52 +00002417Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002418Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002419 if (getLangOptions().CPlusPlus) {
2420 if (!lhsType->isRecordType()) {
2421 // C++ 5.17p3: If the left operand is not of class type, the
2422 // expression is implicitly converted (C++ 4) to the
2423 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00002424 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2425 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002426 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002427 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00002428 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002429 }
2430
2431 // FIXME: Currently, we fall through and treat C++ classes like C
2432 // structures.
2433 }
2434
Steve Naroff529a4ad2007-11-27 17:58:44 +00002435 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2436 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00002437 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2438 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00002439 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002440 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00002441 return Compatible;
2442 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002443
2444 // We don't allow conversion of non-null-pointer constants to integers.
2445 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2446 return IntToBlockPointer;
2447
Chris Lattner943140e2007-10-16 02:55:40 +00002448 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00002449 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00002450 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00002451 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00002452 //
Douglas Gregor9d293df2008-10-28 00:22:11 +00002453 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00002454 if (!lhsType->isReferenceType())
2455 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00002456
Chris Lattner5cf216b2008-01-04 18:04:52 +00002457 Sema::AssignConvertType result =
2458 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00002459
2460 // C99 6.5.16.1p2: The value of the right operand is converted to the
2461 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00002462 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2463 // so that we can use references in built-in functions even in C.
2464 // The getNonReferenceType() call makes sure that the resulting expression
2465 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00002466 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00002467 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00002468 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00002469}
2470
Chris Lattner5cf216b2008-01-04 18:04:52 +00002471Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002472Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2473 return CheckAssignmentConstraints(lhsType, rhsType);
2474}
2475
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002476QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002477 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00002478 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002479 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00002480 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002481}
2482
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002483inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00002484 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00002485 // For conversion purposes, we ignore any qualifiers.
2486 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002487 QualType lhsType =
2488 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2489 QualType rhsType =
2490 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002491
Nate Begemanbe2341d2008-07-14 18:02:46 +00002492 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00002493 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002494 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00002495
Nate Begemanbe2341d2008-07-14 18:02:46 +00002496 // Handle the case of a vector & extvector type of the same size and element
2497 // type. It would be nice if we only had one vector type someday.
2498 if (getLangOptions().LaxVectorConversions)
2499 if (const VectorType *LV = lhsType->getAsVectorType())
2500 if (const VectorType *RV = rhsType->getAsVectorType())
2501 if (LV->getElementType() == RV->getElementType() &&
2502 LV->getNumElements() == RV->getNumElements())
2503 return lhsType->isExtVectorType() ? lhsType : rhsType;
2504
2505 // If the lhs is an extended vector and the rhs is a scalar of the same type
2506 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002507 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002508 QualType eltType = V->getElementType();
2509
2510 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2511 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2512 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002513 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002514 return lhsType;
2515 }
2516 }
2517
Nate Begemanbe2341d2008-07-14 18:02:46 +00002518 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00002519 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002520 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002521 QualType eltType = V->getElementType();
2522
2523 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2524 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2525 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002526 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002527 return rhsType;
2528 }
2529 }
2530
Reid Spencer5f016e22007-07-11 17:01:13 +00002531 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002532 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00002533 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002534 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002535 return QualType();
2536}
2537
2538inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002539 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002540{
Daniel Dunbar69d1d002009-01-05 22:42:10 +00002541 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002542 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002543
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002544 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002545
Steve Naroffa4332e22007-07-17 00:58:39 +00002546 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002547 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002548 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002549}
2550
2551inline QualType Sema::CheckRemainderOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002552 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002553{
Daniel Dunbar523aa602009-01-05 22:55:36 +00002554 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2555 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2556 return CheckVectorOperands(Loc, lex, rex);
2557 return InvalidOperands(Loc, lex, rex);
2558 }
Steve Naroff90045e82007-07-13 23:32:42 +00002559
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002560 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002561
Steve Naroffa4332e22007-07-17 00:58:39 +00002562 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002563 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002564 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002565}
2566
2567inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002568 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002569{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002570 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002571 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002572
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002573 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00002574
Reid Spencer5f016e22007-07-11 17:01:13 +00002575 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002576 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002577 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002578
Eli Friedmand72d16e2008-05-18 18:08:51 +00002579 // Put any potential pointer into PExp
2580 Expr* PExp = lex, *IExp = rex;
2581 if (IExp->getType()->isPointerType())
2582 std::swap(PExp, IExp);
2583
2584 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2585 if (IExp->getType()->isIntegerType()) {
2586 // Check for arithmetic on pointers to incomplete types
2587 if (!PTy->getPointeeType()->isObjectType()) {
2588 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002589 Diag(Loc, diag::ext_gnu_void_ptr)
2590 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002591 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002592 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00002593 << lex->getType() << lex->getSourceRange();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002594 return QualType();
2595 }
2596 }
2597 return PExp->getType();
2598 }
2599 }
2600
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002601 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002602}
2603
Chris Lattnereca7be62008-04-07 05:30:13 +00002604// C99 6.5.6
2605QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002606 SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00002607 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002608 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002609
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002610 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002611
Chris Lattner6e4ab612007-12-09 21:53:25 +00002612 // Enforce type constraints: C99 6.5.6p3.
2613
2614 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002615 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002616 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00002617
2618 // Either ptr - int or ptr - ptr.
2619 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00002620 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00002621
Chris Lattner6e4ab612007-12-09 21:53:25 +00002622 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00002623 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002624 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002625 if (lpointee->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002626 Diag(Loc, diag::ext_gnu_void_ptr)
2627 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002628 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002629 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002630 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002631 return QualType();
2632 }
2633 }
2634
2635 // The result type of a pointer-int computation is the pointer type.
2636 if (rex->getType()->isIntegerType())
2637 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00002638
Chris Lattner6e4ab612007-12-09 21:53:25 +00002639 // Handle pointer-pointer subtractions.
2640 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00002641 QualType rpointee = RHSPTy->getPointeeType();
2642
Chris Lattner6e4ab612007-12-09 21:53:25 +00002643 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00002644 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002645 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002646 if (rpointee->isVoidType()) {
2647 if (!lpointee->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002648 Diag(Loc, diag::ext_gnu_void_ptr)
2649 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002650 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002651 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002652 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002653 return QualType();
2654 }
2655 }
2656
2657 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00002658 if (!Context.typesAreCompatible(
2659 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2660 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002661 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattnerd1625842008-11-24 06:25:27 +00002662 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002663 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002664 return QualType();
2665 }
2666
2667 return Context.getPointerDiffType();
2668 }
2669 }
2670
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002671 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002672}
2673
Chris Lattnereca7be62008-04-07 05:30:13 +00002674// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002675QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002676 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002677 // C99 6.5.7p2: Each of the operands shall have integer type.
2678 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002679 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002680
Chris Lattnerca5eede2007-12-12 05:47:28 +00002681 // Shifts don't perform usual arithmetic conversions, they just do integer
2682 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002683 if (!isCompAssign)
2684 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002685 UsualUnaryConversions(rex);
2686
2687 // "The type of the result is that of the promoted left operand."
2688 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002689}
2690
Eli Friedman3d815e72008-08-22 00:56:42 +00002691static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2692 ASTContext& Context) {
2693 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2694 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2695 // ID acts sort of like void* for ObjC interfaces
2696 if (LHSIface && Context.isObjCIdType(RHS))
2697 return true;
2698 if (RHSIface && Context.isObjCIdType(LHS))
2699 return true;
2700 if (!LHSIface || !RHSIface)
2701 return false;
2702 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2703 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2704}
2705
Chris Lattnereca7be62008-04-07 05:30:13 +00002706// C99 6.5.8
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002707QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002708 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002709 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002710 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002711
Chris Lattnera5937dd2007-08-26 01:18:55 +00002712 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002713 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2714 UsualArithmeticConversions(lex, rex);
2715 else {
2716 UsualUnaryConversions(lex);
2717 UsualUnaryConversions(rex);
2718 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002719 QualType lType = lex->getType();
2720 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002721
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002722 // For non-floating point types, check for self-comparisons of the form
2723 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2724 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002725 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002726 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2727 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002728 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002729 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002730 }
2731
Douglas Gregor447b69e2008-11-19 03:25:36 +00002732 // The result of comparisons is 'bool' in C++, 'int' in C.
2733 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2734
Chris Lattnera5937dd2007-08-26 01:18:55 +00002735 if (isRelational) {
2736 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002737 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002738 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002739 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002740 if (lType->isFloatingType()) {
2741 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002742 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002743 }
2744
Chris Lattnera5937dd2007-08-26 01:18:55 +00002745 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002746 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002747 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002748
Chris Lattnerd28f8152007-08-26 01:10:14 +00002749 bool LHSIsNull = lex->isNullPointerConstant(Context);
2750 bool RHSIsNull = rex->isNullPointerConstant(Context);
2751
Chris Lattnera5937dd2007-08-26 01:18:55 +00002752 // All of the following pointer related warnings are GCC extensions, except
2753 // when handling null pointer constants. One day, we can consider making them
2754 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002755 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002756 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002757 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002758 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002759 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002760
Steve Naroff66296cb2007-11-13 14:57:38 +00002761 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002762 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2763 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002764 RCanPointeeTy.getUnqualifiedType()) &&
2765 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002766 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002767 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002768 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002769 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002770 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002771 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002772 // Handle block pointer types.
2773 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2774 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2775 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2776
2777 if (!LHSIsNull && !RHSIsNull &&
2778 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002779 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002780 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00002781 }
2782 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002783 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002784 }
Steve Naroff59f53942008-09-28 01:11:11 +00002785 // Allow block pointers to be compared with null pointer constants.
2786 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2787 (lType->isPointerType() && rType->isBlockPointerType())) {
2788 if (!LHSIsNull && !RHSIsNull) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002789 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002790 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00002791 }
2792 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002793 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00002794 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002795
Steve Naroff20373222008-06-03 14:04:54 +00002796 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00002797 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00002798 const PointerType *LPT = lType->getAsPointerType();
2799 const PointerType *RPT = rType->getAsPointerType();
2800 bool LPtrToVoid = LPT ?
2801 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2802 bool RPtrToVoid = RPT ?
2803 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2804
2805 if (!LPtrToVoid && !RPtrToVoid &&
2806 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002807 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002808 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00002809 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002810 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00002811 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002812 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002813 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00002814 }
Steve Naroff20373222008-06-03 14:04:54 +00002815 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2816 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002817 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002818 } else {
2819 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002820 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002821 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002822 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002823 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002824 }
Steve Naroff20373222008-06-03 14:04:54 +00002825 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00002826 }
Steve Naroff20373222008-06-03 14:04:54 +00002827 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2828 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002829 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002830 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002831 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002832 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002833 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002834 }
Steve Naroff20373222008-06-03 14:04:54 +00002835 if (lType->isIntegerType() &&
2836 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002837 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002838 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002839 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002840 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002841 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002842 }
Steve Naroff39218df2008-09-04 16:56:14 +00002843 // Handle block pointers.
2844 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2845 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002846 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002847 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002848 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002849 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00002850 }
2851 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2852 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002853 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002854 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002855 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002856 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00002857 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002858 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002859}
2860
Nate Begemanbe2341d2008-07-14 18:02:46 +00002861/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2862/// operates on extended vector types. Instead of producing an IntTy result,
2863/// like a scalar comparison, a vector comparison produces a vector of integer
2864/// types.
2865QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002866 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00002867 bool isRelational) {
2868 // Check to make sure we're operating on vectors of the same type and width,
2869 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002870 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002871 if (vType.isNull())
2872 return vType;
2873
2874 QualType lType = lex->getType();
2875 QualType rType = rex->getType();
2876
2877 // For non-floating point types, check for self-comparisons of the form
2878 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2879 // often indicate logic errors in the program.
2880 if (!lType->isFloatingType()) {
2881 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2882 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2883 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002884 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002885 }
2886
2887 // Check for comparisons of floating point operands using != and ==.
2888 if (!isRelational && lType->isFloatingType()) {
2889 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002890 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002891 }
2892
2893 // Return the type for the comparison, which is the same as vector type for
2894 // integer vectors, or an integer type of identical size and number of
2895 // elements for floating point vectors.
2896 if (lType->isIntegerType())
2897 return lType;
2898
2899 const VectorType *VTy = lType->getAsVectorType();
2900
2901 // FIXME: need to deal with non-32b int / non-64b long long
2902 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2903 if (TypeSize == 32) {
2904 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2905 }
2906 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2907 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2908}
2909
Reid Spencer5f016e22007-07-11 17:01:13 +00002910inline QualType Sema::CheckBitwiseOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002911 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002912{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002913 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002914 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002915
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002916 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002917
Steve Naroffa4332e22007-07-17 00:58:39 +00002918 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002919 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002920 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002921}
2922
2923inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002924 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00002925{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002926 UsualUnaryConversions(lex);
2927 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002928
Eli Friedman5773a6c2008-05-13 20:16:47 +00002929 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002930 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002931 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002932}
2933
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00002934/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
2935/// is a read-only property; return true if so. A readonly property expression
2936/// depends on various declarations and thus must be treated specially.
2937///
2938static bool IsReadonlyProperty(Expr *E, Sema &S)
2939{
2940 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
2941 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
2942 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
2943 QualType BaseType = PropExpr->getBase()->getType();
2944 if (const PointerType *PTy = BaseType->getAsPointerType())
2945 if (const ObjCInterfaceType *IFTy =
2946 PTy->getPointeeType()->getAsObjCInterfaceType())
2947 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
2948 if (S.isPropertyReadonly(PDecl, IFace))
2949 return true;
2950 }
2951 }
2952 return false;
2953}
2954
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002955/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2956/// emit an error and return true. If so, return false.
2957static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00002958 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2959 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
2960 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002961 if (IsLV == Expr::MLV_Valid)
2962 return false;
2963
2964 unsigned Diag = 0;
2965 bool NeedType = false;
2966 switch (IsLV) { // C99 6.5.16p2
2967 default: assert(0 && "Unknown result from isModifiableLvalue!");
2968 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002969 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002970 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2971 NeedType = true;
2972 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002973 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002974 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2975 NeedType = true;
2976 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00002977 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002978 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2979 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002980 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002981 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2982 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002983 case Expr::MLV_IncompleteType:
2984 case Expr::MLV_IncompleteVoidType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002985 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2986 NeedType = true;
2987 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002988 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002989 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2990 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00002991 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002992 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2993 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00002994 case Expr::MLV_ReadonlyProperty:
2995 Diag = diag::error_readonly_property_assignment;
2996 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00002997 case Expr::MLV_NoSetterProperty:
2998 Diag = diag::error_nosetter_property_assignment;
2999 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003000 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00003001
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003002 if (NeedType)
Chris Lattnerd1625842008-11-24 06:25:27 +00003003 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003004 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003005 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003006 return true;
3007}
3008
3009
3010
3011// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003012QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3013 SourceLocation Loc,
3014 QualType CompoundType) {
3015 // Verify that LHS is a modifiable lvalue, and emit error if not.
3016 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003017 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003018
3019 QualType LHSType = LHS->getType();
3020 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003021
Chris Lattner5cf216b2008-01-04 18:04:52 +00003022 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003023 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00003024 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003025 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner2c156472008-08-21 18:04:13 +00003026
3027 // If the RHS is a unary plus or minus, check to see if they = and + are
3028 // right next to each other. If so, the user may have typo'd "x =+ 4"
3029 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003030 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00003031 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3032 RHSCheck = ICE->getSubExpr();
3033 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3034 if ((UO->getOpcode() == UnaryOperator::Plus ||
3035 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003036 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00003037 // Only if the two operators are exactly adjacent.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003038 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003039 Diag(Loc, diag::warn_not_compound_assign)
3040 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3041 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner2c156472008-08-21 18:04:13 +00003042 }
3043 } else {
3044 // Compound assignment "x += y"
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003045 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00003046 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003047
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003048 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3049 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003050 return QualType();
3051
Reid Spencer5f016e22007-07-11 17:01:13 +00003052 // C99 6.5.16p3: The type of an assignment expression is the type of the
3053 // left operand unless the left operand has qualified type, in which case
3054 // it is the unqualified version of the type of the left operand.
3055 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3056 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003057 // C++ 5.17p1: the type of the assignment expression is that of its left
3058 // oprdu.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003059 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003060}
3061
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003062// C99 6.5.17
3063QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3064 // FIXME: what is required for LHS?
Chris Lattner53fcaa92008-07-25 20:54:07 +00003065
3066 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003067 DefaultFunctionArrayConversion(RHS);
3068 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003069}
3070
Steve Naroff49b45262007-07-13 16:58:59 +00003071/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3072/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003073QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3074 bool isInc) {
Chris Lattner3528d352008-11-21 07:05:48 +00003075 QualType ResType = Op->getType();
3076 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003077
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003078 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3079 // Decrement of bool is not allowed.
3080 if (!isInc) {
3081 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3082 return QualType();
3083 }
3084 // Increment of bool sets it to true, but is deprecated.
3085 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3086 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00003087 // OK!
3088 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3089 // C99 6.5.2.4p2, 6.5.6p2
3090 if (PT->getPointeeType()->isObjectType()) {
3091 // Pointer to object is ok!
3092 } else if (PT->getPointeeType()->isVoidType()) {
3093 // Pointer to void is extension.
3094 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
3095 } else {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003096 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00003097 << ResType << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003098 return QualType();
3099 }
Chris Lattner3528d352008-11-21 07:05:48 +00003100 } else if (ResType->isComplexType()) {
3101 // C99 does not support ++/-- on complex types, we allow as an extension.
3102 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003103 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003104 } else {
3105 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00003106 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003107 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003108 }
Steve Naroffdd10e022007-08-23 21:37:33 +00003109 // At this point, we know we have a real, complex or pointer type.
3110 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00003111 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00003112 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00003113 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00003114}
3115
Anders Carlsson369dee42008-02-01 07:15:58 +00003116/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00003117/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003118/// where the declaration is needed for type checking. We only need to
3119/// handle cases when the expression references a function designator
3120/// or is an lvalue. Here are some examples:
3121/// - &(x) => x
3122/// - &*****f => f for f a function designator.
3123/// - &s.xx => s
3124/// - &s.zz[1].yy -> s, if zz is an array
3125/// - *(x + 1) -> x, if x is an array
3126/// - &"123"[2] -> 0
3127/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003128static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003129 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003130 case Stmt::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +00003131 case Stmt::QualifiedDeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003132 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003133 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00003134 // Fields cannot be declared with a 'register' storage class.
3135 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003136 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00003137 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00003138 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00003139 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003140 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00003141
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003142 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00003143 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00003144 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00003145 return 0;
3146 else
3147 return VD;
3148 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003149 case Stmt::UnaryOperatorClass: {
3150 UnaryOperator *UO = cast<UnaryOperator>(E);
3151
3152 switch(UO->getOpcode()) {
3153 case UnaryOperator::Deref: {
3154 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003155 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3156 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3157 if (!VD || VD->getType()->isPointerType())
3158 return 0;
3159 return VD;
3160 }
3161 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003162 }
3163 case UnaryOperator::Real:
3164 case UnaryOperator::Imag:
3165 case UnaryOperator::Extension:
3166 return getPrimaryDecl(UO->getSubExpr());
3167 default:
3168 return 0;
3169 }
3170 }
3171 case Stmt::BinaryOperatorClass: {
3172 BinaryOperator *BO = cast<BinaryOperator>(E);
3173
3174 // Handle cases involving pointer arithmetic. The result of an
3175 // Assign or AddAssign is not an lvalue so they can be ignored.
3176
3177 // (x + n) or (n + x) => x
3178 if (BO->getOpcode() == BinaryOperator::Add) {
3179 if (BO->getLHS()->getType()->isPointerType()) {
3180 return getPrimaryDecl(BO->getLHS());
3181 } else if (BO->getRHS()->getType()->isPointerType()) {
3182 return getPrimaryDecl(BO->getRHS());
3183 }
3184 }
3185
3186 return 0;
3187 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003188 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003189 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00003190 case Stmt::ImplicitCastExprClass:
3191 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003192 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00003193 default:
3194 return 0;
3195 }
3196}
3197
3198/// CheckAddressOfOperand - The operand of & must be either a function
3199/// designator or an lvalue designating an object. If it is an lvalue, the
3200/// object cannot be declared with storage class register or be a bit field.
3201/// Note: The usual conversions are *not* applied to the operand of the &
3202/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor904eed32008-11-10 20:40:00 +00003203/// In C++, the operand might be an overloaded function name, in which case
3204/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00003205QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregor9103bb22008-12-17 22:52:20 +00003206 if (op->isTypeDependent())
3207 return Context.DependentTy;
3208
Steve Naroff08f19672008-01-13 17:10:08 +00003209 if (getLangOptions().C99) {
3210 // Implement C99-only parts of addressof rules.
3211 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3212 if (uOp->getOpcode() == UnaryOperator::Deref)
3213 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3214 // (assuming the deref expression is valid).
3215 return uOp->getSubExpr()->getType();
3216 }
3217 // Technically, there should be a check for array subscript
3218 // expressions here, but the result of one is always an lvalue anyway.
3219 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003220 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00003221 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00003222
Reid Spencer5f016e22007-07-11 17:01:13 +00003223 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00003224 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3225 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003226 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3227 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003228 return QualType();
3229 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003230 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor86f19402008-12-20 23:49:58 +00003231 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3232 if (Field->isBitField()) {
3233 Diag(OpLoc, diag::err_typecheck_address_of)
3234 << "bit-field" << op->getSourceRange();
3235 return QualType();
3236 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003237 }
3238 // Check for Apple extension for accessing vector components.
3239 } else if (isa<ArraySubscriptExpr>(op) &&
3240 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003241 Diag(OpLoc, diag::err_typecheck_address_of)
3242 << "vector" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00003243 return QualType();
3244 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00003245 // We have an lvalue with a decl. Make sure the decl is not declared
3246 // with the register storage-class specifier.
3247 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3248 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003249 Diag(OpLoc, diag::err_typecheck_address_of)
3250 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003251 return QualType();
3252 }
Douglas Gregor29882052008-12-10 21:26:49 +00003253 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003254 return Context.OverloadTy;
Douglas Gregor29882052008-12-10 21:26:49 +00003255 } else if (isa<FieldDecl>(dcl)) {
3256 // Okay: we can take the address of a field.
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003257 } else if (isa<FunctionDecl>(dcl)) {
3258 // Okay: we can take the address of a function.
Douglas Gregor29882052008-12-10 21:26:49 +00003259 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003260 else
Reid Spencer5f016e22007-07-11 17:01:13 +00003261 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003262 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00003263
Reid Spencer5f016e22007-07-11 17:01:13 +00003264 // If the operand has type "type", the result has type "pointer to type".
3265 return Context.getPointerType(op->getType());
3266}
3267
Chris Lattner22caddc2008-11-23 09:13:29 +00003268QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3269 UsualUnaryConversions(Op);
3270 QualType Ty = Op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003271
Chris Lattner22caddc2008-11-23 09:13:29 +00003272 // Note that per both C89 and C99, this is always legal, even if ptype is an
3273 // incomplete type or void. It would be possible to warn about dereferencing
3274 // a void pointer, but it's completely well-defined, and such a warning is
3275 // unlikely to catch any mistakes.
3276 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff08f19672008-01-13 17:10:08 +00003277 return PT->getPointeeType();
Chris Lattner22caddc2008-11-23 09:13:29 +00003278
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003279 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00003280 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003281 return QualType();
3282}
3283
3284static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3285 tok::TokenKind Kind) {
3286 BinaryOperator::Opcode Opc;
3287 switch (Kind) {
3288 default: assert(0 && "Unknown binop!");
3289 case tok::star: Opc = BinaryOperator::Mul; break;
3290 case tok::slash: Opc = BinaryOperator::Div; break;
3291 case tok::percent: Opc = BinaryOperator::Rem; break;
3292 case tok::plus: Opc = BinaryOperator::Add; break;
3293 case tok::minus: Opc = BinaryOperator::Sub; break;
3294 case tok::lessless: Opc = BinaryOperator::Shl; break;
3295 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3296 case tok::lessequal: Opc = BinaryOperator::LE; break;
3297 case tok::less: Opc = BinaryOperator::LT; break;
3298 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3299 case tok::greater: Opc = BinaryOperator::GT; break;
3300 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3301 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3302 case tok::amp: Opc = BinaryOperator::And; break;
3303 case tok::caret: Opc = BinaryOperator::Xor; break;
3304 case tok::pipe: Opc = BinaryOperator::Or; break;
3305 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3306 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3307 case tok::equal: Opc = BinaryOperator::Assign; break;
3308 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3309 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3310 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3311 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3312 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3313 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3314 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3315 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3316 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3317 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3318 case tok::comma: Opc = BinaryOperator::Comma; break;
3319 }
3320 return Opc;
3321}
3322
3323static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3324 tok::TokenKind Kind) {
3325 UnaryOperator::Opcode Opc;
3326 switch (Kind) {
3327 default: assert(0 && "Unknown unary op!");
3328 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3329 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3330 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3331 case tok::star: Opc = UnaryOperator::Deref; break;
3332 case tok::plus: Opc = UnaryOperator::Plus; break;
3333 case tok::minus: Opc = UnaryOperator::Minus; break;
3334 case tok::tilde: Opc = UnaryOperator::Not; break;
3335 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003336 case tok::kw___real: Opc = UnaryOperator::Real; break;
3337 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3338 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3339 }
3340 return Opc;
3341}
3342
Douglas Gregoreaebc752008-11-06 23:29:22 +00003343/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3344/// operator @p Opc at location @c TokLoc. This routine only supports
3345/// built-in operations; ActOnBinOp handles overloaded operators.
3346Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3347 unsigned Op,
3348 Expr *lhs, Expr *rhs) {
3349 QualType ResultTy; // Result type of the binary operator.
3350 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3351 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3352
3353 switch (Opc) {
3354 default:
3355 assert(0 && "Unknown binary expr!");
3356 case BinaryOperator::Assign:
3357 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3358 break;
3359 case BinaryOperator::Mul:
3360 case BinaryOperator::Div:
3361 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3362 break;
3363 case BinaryOperator::Rem:
3364 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3365 break;
3366 case BinaryOperator::Add:
3367 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3368 break;
3369 case BinaryOperator::Sub:
3370 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3371 break;
3372 case BinaryOperator::Shl:
3373 case BinaryOperator::Shr:
3374 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3375 break;
3376 case BinaryOperator::LE:
3377 case BinaryOperator::LT:
3378 case BinaryOperator::GE:
3379 case BinaryOperator::GT:
3380 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3381 break;
3382 case BinaryOperator::EQ:
3383 case BinaryOperator::NE:
3384 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3385 break;
3386 case BinaryOperator::And:
3387 case BinaryOperator::Xor:
3388 case BinaryOperator::Or:
3389 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3390 break;
3391 case BinaryOperator::LAnd:
3392 case BinaryOperator::LOr:
3393 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3394 break;
3395 case BinaryOperator::MulAssign:
3396 case BinaryOperator::DivAssign:
3397 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3398 if (!CompTy.isNull())
3399 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3400 break;
3401 case BinaryOperator::RemAssign:
3402 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3403 if (!CompTy.isNull())
3404 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3405 break;
3406 case BinaryOperator::AddAssign:
3407 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3408 if (!CompTy.isNull())
3409 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3410 break;
3411 case BinaryOperator::SubAssign:
3412 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3413 if (!CompTy.isNull())
3414 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3415 break;
3416 case BinaryOperator::ShlAssign:
3417 case BinaryOperator::ShrAssign:
3418 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3419 if (!CompTy.isNull())
3420 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3421 break;
3422 case BinaryOperator::AndAssign:
3423 case BinaryOperator::XorAssign:
3424 case BinaryOperator::OrAssign:
3425 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3426 if (!CompTy.isNull())
3427 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3428 break;
3429 case BinaryOperator::Comma:
3430 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3431 break;
3432 }
3433 if (ResultTy.isNull())
3434 return true;
3435 if (CompTy.isNull())
3436 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
3437 else
3438 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
3439}
3440
Reid Spencer5f016e22007-07-11 17:01:13 +00003441// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003442Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3443 tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00003444 ExprTy *LHS, ExprTy *RHS) {
3445 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3446 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
3447
Steve Narofff69936d2007-09-16 03:34:24 +00003448 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3449 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003450
Douglas Gregor898574e2008-12-05 23:32:09 +00003451 // If either expression is type-dependent, just build the AST.
3452 // FIXME: We'll need to perform some caching of the result of name
3453 // lookup for operator+.
3454 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3455 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3456 return new CompoundAssignOperator(lhs, rhs, Opc, Context.DependentTy,
3457 Context.DependentTy, TokLoc);
3458 else
3459 return new BinaryOperator(lhs, rhs, Opc, Context.DependentTy, TokLoc);
3460 }
3461
Douglas Gregoreaebc752008-11-06 23:29:22 +00003462 if (getLangOptions().CPlusPlus &&
3463 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3464 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003465 // If this is one of the assignment operators, we only perform
3466 // overload resolution if the left-hand side is a class or
3467 // enumeration type (C++ [expr.ass]p3).
3468 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3469 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3470 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3471 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003472
3473 // Determine which overloaded operator we're dealing with.
3474 static const OverloadedOperatorKind OverOps[] = {
3475 OO_Star, OO_Slash, OO_Percent,
3476 OO_Plus, OO_Minus,
3477 OO_LessLess, OO_GreaterGreater,
3478 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3479 OO_EqualEqual, OO_ExclaimEqual,
3480 OO_Amp,
3481 OO_Caret,
3482 OO_Pipe,
3483 OO_AmpAmp,
3484 OO_PipePipe,
3485 OO_Equal, OO_StarEqual,
3486 OO_SlashEqual, OO_PercentEqual,
3487 OO_PlusEqual, OO_MinusEqual,
3488 OO_LessLessEqual, OO_GreaterGreaterEqual,
3489 OO_AmpEqual, OO_CaretEqual,
3490 OO_PipeEqual,
3491 OO_Comma
3492 };
3493 OverloadedOperatorKind OverOp = OverOps[Opc];
3494
Douglas Gregor96176b32008-11-18 23:14:02 +00003495 // Add the appropriate overloaded operators (C++ [over.match.oper])
3496 // to the candidate set.
Douglas Gregor74253732008-11-19 15:42:04 +00003497 OverloadCandidateSet CandidateSet;
Douglas Gregoreaebc752008-11-06 23:29:22 +00003498 Expr *Args[2] = { lhs, rhs };
Douglas Gregor96176b32008-11-18 23:14:02 +00003499 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregoreaebc752008-11-06 23:29:22 +00003500
3501 // Perform overload resolution.
3502 OverloadCandidateSet::iterator Best;
3503 switch (BestViableFunction(CandidateSet, Best)) {
3504 case OR_Success: {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003505 // We found a built-in operator or an overloaded operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003506 FunctionDecl *FnDecl = Best->Function;
3507
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003508 if (FnDecl) {
3509 // We matched an overloaded operator. Build a call to that
3510 // operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003511
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003512 // Convert the arguments.
Douglas Gregor96176b32008-11-18 23:14:02 +00003513 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3514 if (PerformObjectArgumentInitialization(lhs, Method) ||
3515 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3516 "passing"))
3517 return true;
3518 } else {
3519 // Convert the arguments.
3520 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3521 "passing") ||
3522 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3523 "passing"))
3524 return true;
3525 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003526
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003527 // Determine the result type
3528 QualType ResultTy
3529 = FnDecl->getType()->getAsFunctionType()->getResultType();
3530 ResultTy = ResultTy.getNonReferenceType();
3531
3532 // Build the actual expression node.
Douglas Gregorb4609802008-11-14 16:09:21 +00003533 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3534 SourceLocation());
3535 UsualUnaryConversions(FnExpr);
3536
Douglas Gregorb4609802008-11-14 16:09:21 +00003537 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003538 } else {
3539 // We matched a built-in operator. Convert the arguments, then
3540 // break out so that we will build the appropriate built-in
3541 // operator node.
3542 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
3543 "passing") ||
3544 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
3545 "passing"))
3546 return true;
3547
3548 break;
3549 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003550 }
3551
3552 case OR_No_Viable_Function:
3553 // No viable function; fall through to handling this as a
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003554 // built-in operator, which will produce an error message for us.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003555 break;
3556
3557 case OR_Ambiguous:
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003558 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3559 << BinaryOperator::getOpcodeStr(Opc)
3560 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003561 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3562 return true;
3563 }
3564
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003565 // Either we found no viable overloaded operator or we matched a
3566 // built-in operator. In either case, fall through to trying to
3567 // build a built-in operation.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003568 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003569
Douglas Gregoreaebc752008-11-06 23:29:22 +00003570 // Build a built-in binary operation.
3571 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00003572}
3573
3574// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor74253732008-11-19 15:42:04 +00003575Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3576 tok::TokenKind Op, ExprTy *input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003577 Expr *Input = (Expr*)input;
3578 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor74253732008-11-19 15:42:04 +00003579
3580 if (getLangOptions().CPlusPlus &&
3581 (Input->getType()->isRecordType()
3582 || Input->getType()->isEnumeralType())) {
3583 // Determine which overloaded operator we're dealing with.
3584 static const OverloadedOperatorKind OverOps[] = {
3585 OO_None, OO_None,
3586 OO_PlusPlus, OO_MinusMinus,
3587 OO_Amp, OO_Star,
3588 OO_Plus, OO_Minus,
3589 OO_Tilde, OO_Exclaim,
3590 OO_None, OO_None,
3591 OO_None,
3592 OO_None
3593 };
3594 OverloadedOperatorKind OverOp = OverOps[Opc];
3595
3596 // Add the appropriate overloaded operators (C++ [over.match.oper])
3597 // to the candidate set.
3598 OverloadCandidateSet CandidateSet;
3599 if (OverOp != OO_None)
3600 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3601
3602 // Perform overload resolution.
3603 OverloadCandidateSet::iterator Best;
3604 switch (BestViableFunction(CandidateSet, Best)) {
3605 case OR_Success: {
3606 // We found a built-in operator or an overloaded operator.
3607 FunctionDecl *FnDecl = Best->Function;
3608
3609 if (FnDecl) {
3610 // We matched an overloaded operator. Build a call to that
3611 // operator.
3612
3613 // Convert the arguments.
3614 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3615 if (PerformObjectArgumentInitialization(Input, Method))
3616 return true;
3617 } else {
3618 // Convert the arguments.
3619 if (PerformCopyInitialization(Input,
3620 FnDecl->getParamDecl(0)->getType(),
3621 "passing"))
3622 return true;
3623 }
3624
3625 // Determine the result type
3626 QualType ResultTy
3627 = FnDecl->getType()->getAsFunctionType()->getResultType();
3628 ResultTy = ResultTy.getNonReferenceType();
3629
3630 // Build the actual expression node.
3631 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3632 SourceLocation());
3633 UsualUnaryConversions(FnExpr);
3634
3635 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3636 } else {
3637 // We matched a built-in operator. Convert the arguments, then
3638 // break out so that we will build the appropriate built-in
3639 // operator node.
3640 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0],
3641 "passing"))
3642 return true;
3643
3644 break;
3645 }
3646 }
3647
3648 case OR_No_Viable_Function:
3649 // No viable function; fall through to handling this as a
3650 // built-in operator, which will produce an error message for us.
3651 break;
3652
3653 case OR_Ambiguous:
3654 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3655 << UnaryOperator::getOpcodeStr(Opc)
3656 << Input->getSourceRange();
3657 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3658 return true;
3659 }
3660
3661 // Either we found no viable overloaded operator or we matched a
3662 // built-in operator. In either case, fall through to trying to
3663 // build a built-in operation.
3664 }
3665
Reid Spencer5f016e22007-07-11 17:01:13 +00003666 QualType resultType;
3667 switch (Opc) {
3668 default:
3669 assert(0 && "Unimplemented unary expr!");
3670 case UnaryOperator::PreInc:
3671 case UnaryOperator::PreDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003672 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3673 Opc == UnaryOperator::PreInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003674 break;
3675 case UnaryOperator::AddrOf:
3676 resultType = CheckAddressOfOperand(Input, OpLoc);
3677 break;
3678 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00003679 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003680 resultType = CheckIndirectionOperand(Input, OpLoc);
3681 break;
3682 case UnaryOperator::Plus:
3683 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003684 UsualUnaryConversions(Input);
3685 resultType = Input->getType();
Douglas Gregor74253732008-11-19 15:42:04 +00003686 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3687 break;
3688 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3689 resultType->isEnumeralType())
3690 break;
3691 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3692 Opc == UnaryOperator::Plus &&
3693 resultType->isPointerType())
3694 break;
3695
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003696 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattnerd1625842008-11-24 06:25:27 +00003697 << resultType << Input->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003698 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003699 UsualUnaryConversions(Input);
3700 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00003701 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3702 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3703 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003704 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003705 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00003706 else if (!resultType->isIntegerType())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003707 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattnerd1625842008-11-24 06:25:27 +00003708 << resultType << Input->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003709 break;
3710 case UnaryOperator::LNot: // logical negation
3711 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003712 DefaultFunctionArrayConversion(Input);
3713 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003714 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003715 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattnerd1625842008-11-24 06:25:27 +00003716 << resultType << Input->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003717 // LNot always has type int. C99 6.5.3.3p5.
3718 resultType = Context.IntTy;
3719 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00003720 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00003721 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00003722 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00003723 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003724 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00003725 resultType = Input->getType();
3726 break;
3727 }
3728 if (resultType.isNull())
3729 return true;
3730 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3731}
3732
Steve Naroff1b273c42007-09-16 14:56:35 +00003733/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3734Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00003735 SourceLocation LabLoc,
3736 IdentifierInfo *LabelII) {
3737 // Look up the record for this label identifier.
3738 LabelStmt *&LabelDecl = LabelMap[LabelII];
3739
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00003740 // If we haven't seen this label yet, create a forward reference. It
3741 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00003742 if (LabelDecl == 0)
3743 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3744
3745 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00003746 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3747 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00003748}
3749
Steve Naroff1b273c42007-09-16 14:56:35 +00003750Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003751 SourceLocation RPLoc) { // "({..})"
3752 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3753 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3754 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3755
3756 // FIXME: there are a variety of strange constraints to enforce here, for
3757 // example, it is not possible to goto into a stmt expression apparently.
3758 // More semantic analysis is needed.
3759
3760 // FIXME: the last statement in the compount stmt has its value used. We
3761 // should not warn about it being unused.
3762
3763 // If there are sub stmts in the compound stmt, take the type of the last one
3764 // as the type of the stmtexpr.
3765 QualType Ty = Context.VoidTy;
3766
Chris Lattner611b2ec2008-07-26 19:51:01 +00003767 if (!Compound->body_empty()) {
3768 Stmt *LastStmt = Compound->body_back();
3769 // If LastStmt is a label, skip down through into the body.
3770 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3771 LastStmt = Label->getSubStmt();
3772
3773 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003774 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00003775 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003776
3777 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3778}
Steve Naroffd34e9152007-08-01 22:05:33 +00003779
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003780Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3781 SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003782 SourceLocation TypeLoc,
3783 TypeTy *argty,
3784 OffsetOfComponent *CompPtr,
3785 unsigned NumComponents,
3786 SourceLocation RPLoc) {
3787 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3788 assert(!ArgTy.isNull() && "Missing type argument!");
3789
3790 // We must have at least one component that refers to the type, and the first
3791 // one is known to be a field designator. Verify that the ArgTy represents
3792 // a struct/union/class.
3793 if (!ArgTy->isRecordType())
Chris Lattnerd1625842008-11-24 06:25:27 +00003794 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003795
3796 // Otherwise, create a compound literal expression as the base, and
3797 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00003798 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003799
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003800 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3801 // GCC extension, diagnose them.
3802 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003803 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3804 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003805
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003806 for (unsigned i = 0; i != NumComponents; ++i) {
3807 const OffsetOfComponent &OC = CompPtr[i];
3808 if (OC.isBrackets) {
3809 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003810 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003811 if (!AT) {
3812 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00003813 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003814 }
3815
Chris Lattner704fe352007-08-30 17:59:59 +00003816 // FIXME: C++: Verify that operator[] isn't overloaded.
3817
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003818 // C99 6.5.2.1p1
3819 Expr *Idx = static_cast<Expr*>(OC.U.E);
3820 if (!Idx->getType()->isIntegerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003821 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3822 << Idx->getSourceRange();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003823
3824 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3825 continue;
3826 }
3827
3828 const RecordType *RC = Res->getType()->getAsRecordType();
3829 if (!RC) {
3830 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00003831 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003832 }
3833
3834 // Get the decl corresponding to this.
3835 RecordDecl *RD = RC->getDecl();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003836 FieldDecl *MemberDecl
3837 = dyn_cast_or_null<FieldDecl>(LookupDecl(OC.U.IdentInfo,
3838 Decl::IDNS_Ordinary,
3839 S, RD, false, false));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003840 if (!MemberDecl)
Chris Lattner3c73c412008-11-19 08:23:25 +00003841 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3842 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner704fe352007-08-30 17:59:59 +00003843
3844 // FIXME: C++: Verify that MemberDecl isn't a static field.
3845 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00003846 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3847 // matter here.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003848 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3849 MemberDecl->getType().getNonReferenceType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003850 }
3851
3852 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3853 BuiltinLoc);
3854}
3855
3856
Steve Naroff1b273c42007-09-16 14:56:35 +00003857Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00003858 TypeTy *arg1, TypeTy *arg2,
3859 SourceLocation RPLoc) {
3860 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3861 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3862
3863 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3864
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003865 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00003866}
3867
Steve Naroff1b273c42007-09-16 14:56:35 +00003868Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00003869 ExprTy *expr1, ExprTy *expr2,
3870 SourceLocation RPLoc) {
3871 Expr *CondExpr = static_cast<Expr*>(cond);
3872 Expr *LHSExpr = static_cast<Expr*>(expr1);
3873 Expr *RHSExpr = static_cast<Expr*>(expr2);
3874
3875 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3876
3877 // The conditional expression is required to be a constant expression.
3878 llvm::APSInt condEval(32);
3879 SourceLocation ExpLoc;
3880 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003881 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3882 << CondExpr->getSourceRange();
Steve Naroffd04fdd52007-08-03 21:21:27 +00003883
3884 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3885 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3886 RHSExpr->getType();
3887 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3888}
3889
Steve Naroff4eb206b2008-09-03 18:15:37 +00003890//===----------------------------------------------------------------------===//
3891// Clang Extensions.
3892//===----------------------------------------------------------------------===//
3893
3894/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00003895void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00003896 // Analyze block parameters.
3897 BlockSemaInfo *BSI = new BlockSemaInfo();
3898
3899 // Add BSI to CurBlock.
3900 BSI->PrevBlockInfo = CurBlock;
3901 CurBlock = BSI;
3902
3903 BSI->ReturnType = 0;
3904 BSI->TheScope = BlockScope;
3905
Steve Naroff090276f2008-10-10 01:28:17 +00003906 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00003907 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00003908}
3909
3910void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00003911 // Analyze arguments to block.
3912 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3913 "Not a function declarator!");
3914 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3915
Steve Naroff090276f2008-10-10 01:28:17 +00003916 CurBlock->hasPrototype = FTI.hasPrototype;
3917 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003918
3919 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3920 // no arguments, not a function that takes a single void argument.
3921 if (FTI.hasPrototype &&
3922 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3923 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3924 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3925 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00003926 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003927 } else if (FTI.hasPrototype) {
3928 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00003929 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3930 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003931 }
Steve Naroff090276f2008-10-10 01:28:17 +00003932 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3933
3934 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3935 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3936 // If this has an identifier, add it to the scope stack.
3937 if ((*AI)->getIdentifier())
3938 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003939}
3940
3941/// ActOnBlockError - If there is an error parsing a block, this callback
3942/// is invoked to pop the information about the block from the action impl.
3943void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3944 // Ensure that CurBlock is deleted.
3945 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3946
3947 // Pop off CurBlock, handle nested blocks.
3948 CurBlock = CurBlock->PrevBlockInfo;
3949
3950 // FIXME: Delete the ParmVarDecl objects as well???
3951
3952}
3953
3954/// ActOnBlockStmtExpr - This is called when the body of a block statement
3955/// literal was successfully completed. ^(int x){...}
3956Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3957 Scope *CurScope) {
3958 // Ensure that CurBlock is deleted.
3959 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3960 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3961
Steve Naroff090276f2008-10-10 01:28:17 +00003962 PopDeclContext();
3963
Steve Naroff4eb206b2008-09-03 18:15:37 +00003964 // Pop off CurBlock, handle nested blocks.
3965 CurBlock = CurBlock->PrevBlockInfo;
3966
3967 QualType RetTy = Context.VoidTy;
3968 if (BSI->ReturnType)
3969 RetTy = QualType(BSI->ReturnType, 0);
3970
3971 llvm::SmallVector<QualType, 8> ArgTypes;
3972 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3973 ArgTypes.push_back(BSI->Params[i]->getType());
3974
3975 QualType BlockTy;
3976 if (!BSI->hasPrototype)
3977 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3978 else
3979 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003980 BSI->isVariadic, 0);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003981
3982 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00003983
Steve Naroff1c90bfc2008-10-08 18:44:00 +00003984 BSI->TheDecl->setBody(Body.take());
3985 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003986}
3987
Nate Begeman67295d02008-01-30 20:50:20 +00003988/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00003989/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00003990/// The number of arguments has already been validated to match the number of
3991/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003992static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3993 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00003994 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00003995 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00003996 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3997 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00003998
3999 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00004000 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00004001 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004002 return true;
4003}
4004
4005Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4006 SourceLocation *CommaLocs,
4007 SourceLocation BuiltinLoc,
4008 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00004009 // __builtin_overload requires at least 2 arguments
4010 if (NumArgs < 2)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004011 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4012 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004013
Nate Begemane2ce1d92008-01-17 17:46:27 +00004014 // The first argument is required to be a constant expression. It tells us
4015 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00004016 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004017 Expr *NParamsExpr = Args[0];
4018 llvm::APSInt constEval(32);
4019 SourceLocation ExpLoc;
4020 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004021 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4022 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004023
4024 // Verify that the number of parameters is > 0
4025 unsigned NumParams = constEval.getZExtValue();
4026 if (NumParams == 0)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004027 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4028 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004029 // Verify that we have at least 1 + NumParams arguments to the builtin.
4030 if ((NumParams + 1) > NumArgs)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004031 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4032 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004033
4034 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00004035 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00004036 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004037 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4038 // UsualUnaryConversions will convert the function DeclRefExpr into a
4039 // pointer to function.
4040 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00004041 const FunctionTypeProto *FnType = 0;
4042 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4043 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004044
4045 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4046 // parameters, and the number of parameters must match the value passed to
4047 // the builtin.
4048 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004049 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4050 << Fn->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004051
4052 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00004053 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00004054 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004055 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00004056 if (OE)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004057 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4058 << OE->getFn()->getSourceRange();
Nate Begeman796ef3d2008-01-31 05:38:29 +00004059 // Remember our match, and continue processing the remaining arguments
4060 // to catch any errors.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004061 OE = new OverloadExpr(Args, NumArgs, i,
4062 FnType->getResultType().getNonReferenceType(),
Nate Begeman796ef3d2008-01-31 05:38:29 +00004063 BuiltinLoc, RParenLoc);
4064 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004065 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00004066 // Return the newly created OverloadExpr node, if we succeded in matching
4067 // exactly one of the candidate functions.
4068 if (OE)
4069 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004070
4071 // If we didn't find a matching function Expr in the __builtin_overload list
4072 // the return an error.
4073 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00004074 for (unsigned i = 0; i != NumParams; ++i) {
4075 if (i != 0) typeNames += ", ";
4076 typeNames += Args[i+1]->getType().getAsString();
4077 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004078
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004079 return Diag(BuiltinLoc, diag::err_overload_no_match)
4080 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004081}
4082
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004083Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4084 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00004085 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004086 Expr *E = static_cast<Expr*>(expr);
4087 QualType T = QualType::getFromOpaquePtr(type);
4088
4089 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004090
4091 // Get the va_list type
4092 QualType VaListType = Context.getBuiltinVaListType();
4093 // Deal with implicit array decay; for example, on x86-64,
4094 // va_list is an array, but it's supposed to decay to
4095 // a pointer for va_arg.
4096 if (VaListType->isArrayType())
4097 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00004098 // Make sure the input expression also decays appropriately.
4099 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004100
4101 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004102 return Diag(E->getLocStart(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004103 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00004104 << E->getType() << E->getSourceRange();
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004105
4106 // FIXME: Warn if a non-POD type is passed in.
4107
Douglas Gregor9d293df2008-10-28 00:22:11 +00004108 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004109}
4110
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004111Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4112 // The type of __null will be int or long, depending on the size of
4113 // pointers on the target.
4114 QualType Ty;
4115 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4116 Ty = Context.IntTy;
4117 else
4118 Ty = Context.LongTy;
4119
4120 return new GNUNullExpr(Ty, TokenLoc);
4121}
4122
Chris Lattner5cf216b2008-01-04 18:04:52 +00004123bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4124 SourceLocation Loc,
4125 QualType DstType, QualType SrcType,
4126 Expr *SrcExpr, const char *Flavor) {
4127 // Decode the result (notice that AST's are still created for extensions).
4128 bool isInvalid = false;
4129 unsigned DiagKind;
4130 switch (ConvTy) {
4131 default: assert(0 && "Unknown conversion type");
4132 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004133 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00004134 DiagKind = diag::ext_typecheck_convert_pointer_int;
4135 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004136 case IntToPointer:
4137 DiagKind = diag::ext_typecheck_convert_int_pointer;
4138 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004139 case IncompatiblePointer:
4140 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4141 break;
4142 case FunctionVoidPointer:
4143 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4144 break;
4145 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00004146 // If the qualifiers lost were because we were applying the
4147 // (deprecated) C++ conversion from a string literal to a char*
4148 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4149 // Ideally, this check would be performed in
4150 // CheckPointerTypesForAssignment. However, that would require a
4151 // bit of refactoring (so that the second argument is an
4152 // expression, rather than a type), which should be done as part
4153 // of a larger effort to fix CheckPointerTypesForAssignment for
4154 // C++ semantics.
4155 if (getLangOptions().CPlusPlus &&
4156 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4157 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004158 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4159 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004160 case IntToBlockPointer:
4161 DiagKind = diag::err_int_to_block_pointer;
4162 break;
4163 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00004164 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004165 break;
Steve Naroff39579072008-10-14 22:18:38 +00004166 case IncompatibleObjCQualifiedId:
4167 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4168 // it can give a more specific diagnostic.
4169 DiagKind = diag::warn_incompatible_qualified_id;
4170 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004171 case Incompatible:
4172 DiagKind = diag::err_typecheck_convert_incompatible;
4173 isInvalid = true;
4174 break;
4175 }
4176
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004177 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4178 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00004179 return isInvalid;
4180}
Anders Carlssone21555e2008-11-30 19:50:32 +00004181
4182bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4183{
4184 Expr::EvalResult EvalResult;
4185
4186 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4187 EvalResult.HasSideEffects) {
4188 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4189
4190 if (EvalResult.Diag) {
4191 // We only show the note if it's not the usual "invalid subexpression"
4192 // or if it's actually in a subexpression.
4193 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4194 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4195 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4196 }
4197
4198 return true;
4199 }
4200
4201 if (EvalResult.Diag) {
4202 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4203 E->getSourceRange();
4204
4205 // Print the reason it's not a constant.
4206 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4207 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4208 }
4209
4210 if (Result)
4211 *Result = EvalResult.Val.getInt();
4212 return false;
4213}