blob: d638b8dc98085505ab36f8626b6a90383f3be2de [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Chris Lattner299b8842008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattner299b8842008-07-25 21:10:04 +000033/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
34void Sema::DefaultFunctionArrayConversion(Expr *&E) {
35 QualType Ty = E->getType();
36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
37
Chris Lattner299b8842008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000040 else if (Ty->isArrayType()) {
41 // In C90 mode, arrays only promote to pointers if the array expression is
42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
43 // type 'array of type' is converted to an expression that has type 'pointer
44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
45 // that has type 'array of type' ...". The relevant change is "an lvalue"
46 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000047 //
48 // C++ 4.2p1:
49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
50 // T" can be converted to an rvalue of type "pointer to T".
51 //
52 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
53 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattner299b8842008-07-25 21:10:04 +000056}
57
58/// UsualUnaryConversions - Performs various conversions that are common to most
59/// operators (C99 6.3). The conversions of array and function types are
60/// sometimes surpressed. For example, the array->pointer conversion doesn't
61/// apply if the array is an argument to the sizeof or address (&) operators.
62/// In these instances, this routine should *not* be called.
63Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
64 QualType Ty = Expr->getType();
65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
66
Chris Lattner299b8842008-07-25 21:10:04 +000067 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
68 ImpCastExprToType(Expr, Context.IntTy);
69 else
70 DefaultFunctionArrayConversion(Expr);
71
72 return Expr;
73}
74
Chris Lattner9305c3d2008-07-25 22:25:12 +000075/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
76/// do not have a prototype. Arguments that have type float are promoted to
77/// double. All other argument types are converted by UsualUnaryConversions().
78void Sema::DefaultArgumentPromotion(Expr *&Expr) {
79 QualType Ty = Expr->getType();
80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
81
82 // If this is a 'float' (CVR qualified or typedef) promote to double.
83 if (const BuiltinType *BT = Ty->getAsBuiltinType())
84 if (BT->getKind() == BuiltinType::Float)
85 return ImpCastExprToType(Expr, Context.DoubleTy);
86
87 UsualUnaryConversions(Expr);
88}
89
Chris Lattner299b8842008-07-25 21:10:04 +000090/// UsualArithmeticConversions - Performs various conversions that are common to
91/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
92/// routine returns the first non-arithmetic type found. The client is
93/// responsible for emitting appropriate error diagnostics.
94/// FIXME: verify the conversion rules for "complex int" are consistent with
95/// GCC.
96QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
97 bool isCompAssign) {
98 if (!isCompAssign) {
99 UsualUnaryConversions(lhsExpr);
100 UsualUnaryConversions(rhsExpr);
101 }
102 // For conversion purposes, we ignore any qualifiers.
103 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000104 QualType lhs =
105 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
106 QualType rhs =
107 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattner299b8842008-07-25 21:10:04 +0000108
109 // If both types are identical, no conversion is needed.
110 if (lhs == rhs)
111 return lhs;
112
113 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
114 // The caller can deal with this (e.g. pointer + int).
115 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
116 return lhs;
117
118 // At this point, we have two different arithmetic types.
119
120 // Handle complex types first (C99 6.3.1.8p1).
121 if (lhs->isComplexType() || rhs->isComplexType()) {
122 // if we have an integer operand, the result is the complex type.
123 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
124 // convert the rhs to the lhs complex type.
125 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
126 return lhs;
127 }
128 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
129 // convert the lhs to the rhs complex type.
130 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
131 return rhs;
132 }
133 // This handles complex/complex, complex/float, or float/complex.
134 // When both operands are complex, the shorter operand is converted to the
135 // type of the longer, and that is the type of the result. This corresponds
136 // to what is done when combining two real floating-point operands.
137 // The fun begins when size promotion occur across type domains.
138 // From H&S 6.3.4: When one operand is complex and the other is a real
139 // floating-point type, the less precise type is converted, within it's
140 // real or complex domain, to the precision of the other type. For example,
141 // when combining a "long double" with a "double _Complex", the
142 // "double _Complex" is promoted to "long double _Complex".
143 int result = Context.getFloatingTypeOrder(lhs, rhs);
144
145 if (result > 0) { // The left side is bigger, convert rhs.
146 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
147 if (!isCompAssign)
148 ImpCastExprToType(rhsExpr, rhs);
149 } else if (result < 0) { // The right side is bigger, convert lhs.
150 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
151 if (!isCompAssign)
152 ImpCastExprToType(lhsExpr, lhs);
153 }
154 // At this point, lhs and rhs have the same rank/size. Now, make sure the
155 // domains match. This is a requirement for our implementation, C99
156 // does not require this promotion.
157 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
158 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
159 if (!isCompAssign)
160 ImpCastExprToType(lhsExpr, rhs);
161 return rhs;
162 } else { // handle "_Complex double, double".
163 if (!isCompAssign)
164 ImpCastExprToType(rhsExpr, lhs);
165 return lhs;
166 }
167 }
168 return lhs; // The domain/size match exactly.
169 }
170 // Now handle "real" floating types (i.e. float, double, long double).
171 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
172 // if we have an integer operand, the result is the real floating type.
173 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
174 // convert rhs to the lhs floating point type.
175 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
176 return lhs;
177 }
178 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
179 // convert lhs to the rhs floating point type.
180 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
181 return rhs;
182 }
183 // We have two real floating types, float/complex combos were handled above.
184 // Convert the smaller operand to the bigger result.
185 int result = Context.getFloatingTypeOrder(lhs, rhs);
186
187 if (result > 0) { // convert the rhs
188 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
189 return lhs;
190 }
191 if (result < 0) { // convert the lhs
192 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
193 return rhs;
194 }
195 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
196 }
197 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
198 // Handle GCC complex int extension.
199 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
200 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
201
202 if (lhsComplexInt && rhsComplexInt) {
203 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
204 rhsComplexInt->getElementType()) >= 0) {
205 // convert the rhs
206 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
207 return lhs;
208 }
209 if (!isCompAssign)
210 ImpCastExprToType(lhsExpr, rhs); // convert the lhs
211 return rhs;
212 } else if (lhsComplexInt && rhs->isIntegerType()) {
213 // convert the rhs to the lhs complex type.
214 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
215 return lhs;
216 } else if (rhsComplexInt && lhs->isIntegerType()) {
217 // convert the lhs to the rhs complex type.
218 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
219 return rhs;
220 }
221 }
222 // Finally, we have two differing integer types.
223 // The rules for this case are in C99 6.3.1.8
224 int compare = Context.getIntegerTypeOrder(lhs, rhs);
225 bool lhsSigned = lhs->isSignedIntegerType(),
226 rhsSigned = rhs->isSignedIntegerType();
227 QualType destType;
228 if (lhsSigned == rhsSigned) {
229 // Same signedness; use the higher-ranked type
230 destType = compare >= 0 ? lhs : rhs;
231 } else if (compare != (lhsSigned ? 1 : -1)) {
232 // The unsigned type has greater than or equal rank to the
233 // signed type, so use the unsigned type
234 destType = lhsSigned ? rhs : lhs;
235 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
236 // The two types are different widths; if we are here, that
237 // means the signed type is larger than the unsigned type, so
238 // use the signed type.
239 destType = lhsSigned ? lhs : rhs;
240 } else {
241 // The signed type is higher-ranked than the unsigned type,
242 // but isn't actually any bigger (like unsigned int and long
243 // on most 32-bit systems). Use the unsigned type corresponding
244 // to the signed type.
245 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
246 }
247 if (!isCompAssign) {
248 ImpCastExprToType(lhsExpr, destType);
249 ImpCastExprToType(rhsExpr, destType);
250 }
251 return destType;
252}
253
254//===----------------------------------------------------------------------===//
255// Semantic Analysis for various Expression Types
256//===----------------------------------------------------------------------===//
257
258
Steve Naroff87d58b42007-09-16 03:34:24 +0000259/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000260/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
261/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
262/// multiple tokens. However, the common case is that StringToks points to one
263/// string.
264///
265Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000266Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000267 assert(NumStringToks && "Must have at least one string!");
268
269 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
270 if (Literal.hadError)
271 return ExprResult(true);
272
273 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
274 for (unsigned i = 0; i != NumStringToks; ++i)
275 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000276
277 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000278 if (Literal.Pascal && Literal.GetStringLength() > 256)
279 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
280 SourceRange(StringToks[0].getLocation(),
281 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000282
Chris Lattnera6dcce32008-02-11 00:02:17 +0000283 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000284 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000285 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000286
287 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
288 if (getLangOptions().CPlusPlus)
289 StrTy.addConst();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000290
291 // Get an array type for the string, according to C99 6.4.5. This includes
292 // the nul terminator character as well as the string length for pascal
293 // strings.
294 StrTy = Context.getConstantArrayType(StrTy,
295 llvm::APInt(32, Literal.GetStringLength()+1),
296 ArrayType::Normal, 0);
297
Chris Lattner4b009652007-07-25 00:24:17 +0000298 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
299 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000300 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000301 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000302 StringToks[NumStringToks-1].getLocation());
303}
304
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000305/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
306/// CurBlock to VD should cause it to be snapshotted (as we do for auto
307/// variables defined outside the block) or false if this is not needed (e.g.
308/// for values inside the block or for globals).
309///
310/// FIXME: This will create BlockDeclRefExprs for global variables,
311/// function references, etc which is suboptimal :) and breaks
312/// things like "integer constant expression" tests.
313static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
314 ValueDecl *VD) {
315 // If the value is defined inside the block, we couldn't snapshot it even if
316 // we wanted to.
317 if (CurBlock->TheDecl == VD->getDeclContext())
318 return false;
319
320 // If this is an enum constant or function, it is constant, don't snapshot.
321 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
322 return false;
323
324 // If this is a reference to an extern, static, or global variable, no need to
325 // snapshot it.
326 // FIXME: What about 'const' variables in C++?
327 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
328 return Var->hasLocalStorage();
329
330 return true;
331}
332
333
334
Steve Naroff0acc9c92007-09-15 18:49:24 +0000335/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000336/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000337/// identifier is used in a function call context.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000338Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000339 IdentifierInfo &II,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000340 bool HasTrailingLParen,
341 const CXXScopeSpec *SS) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000342 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +0000343 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000344
345 // If this reference is in an Objective-C method, then ivar lookup happens as
346 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000347 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000348 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000349 // There are two cases to handle here. 1) scoped lookup could have failed,
350 // in which case we should look for an ivar. 2) scoped lookup could have
351 // found a decl, but that decl is outside the current method (i.e. a global
352 // variable). In these two cases, we do a lookup for an ivar with this
353 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000354 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000355 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattnered94f762008-07-21 04:44:44 +0000356 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000357 // FIXME: This should use a new expr for a direct reference, don't turn
358 // this into Self->ivar, just return a BareIVarExpr or something.
359 IdentifierInfo &II = Context.Idents.get("self");
360 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
361 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
362 static_cast<Expr*>(SelfExpr.Val), true, true);
363 }
364 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000365 // Needed to implement property "super.method" notation.
Daniel Dunbar4837ae72008-08-14 22:04:54 +0000366 if (SD == 0 && &II == SuperID) {
Steve Naroff6f786252008-06-02 23:03:37 +0000367 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000368 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000369 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000370 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000371 }
Chris Lattner4b009652007-07-25 00:24:17 +0000372 if (D == 0) {
373 // Otherwise, this could be an implicitly declared function reference (legal
374 // in C90, extension in C99).
375 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000376 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000377 D = ImplicitlyDefineFunction(Loc, II, S);
378 else {
379 // If this name wasn't predeclared and if this is not a function call,
380 // diagnose the problem.
381 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
382 }
383 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000384
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000385 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
386 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
387 if (MD->isStatic())
388 // "invalid use of member 'x' in static member function"
389 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
390 FD->getName());
391 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
392 // "invalid use of nonstatic data member 'x'"
393 return Diag(Loc, diag::err_invalid_non_static_member_use,
394 FD->getName());
395
396 if (FD->isInvalidDecl())
397 return true;
398
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +0000399 // FIXME: Handle 'mutable'.
400 return new DeclRefExpr(FD,
401 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000402 }
403
404 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
405 }
Chris Lattner4b009652007-07-25 00:24:17 +0000406 if (isa<TypedefDecl>(D))
407 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000408 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000409 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000410 if (isa<NamespaceDecl>(D))
411 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000412
Steve Naroffd6163f32008-09-05 22:11:13 +0000413 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000414 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
415 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
416
Steve Naroffd6163f32008-09-05 22:11:13 +0000417 ValueDecl *VD = cast<ValueDecl>(D);
418
419 // check if referencing an identifier with __attribute__((deprecated)).
420 if (VD->getAttr<DeprecatedAttr>())
421 Diag(Loc, diag::warn_deprecated, VD->getName());
422
423 // Only create DeclRefExpr's for valid Decl's.
424 if (VD->isInvalidDecl())
425 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000426
427 // If the identifier reference is inside a block, and it refers to a value
428 // that is outside the block, create a BlockDeclRefExpr instead of a
429 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
430 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000431 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000432 // We do not do this for things like enum constants, global variables, etc,
433 // as they do not get snapshotted.
434 //
435 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000436 // The BlocksAttr indicates the variable is bound by-reference.
437 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000438 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
439 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000440
441 // Variable will be bound by-copy, make it const within the closure.
442 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000443 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
444 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000445 }
446 // If this reference is not in a block or if the referenced variable is
447 // within the block, create a normal DeclRefExpr.
Douglas Gregor3fb675a2008-10-22 04:14:44 +0000448 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Chris Lattner4b009652007-07-25 00:24:17 +0000449}
450
Chris Lattner69909292008-08-10 01:53:14 +0000451Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000452 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000453 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000454
455 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000456 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000457 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
458 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
459 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000460 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000461
462 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000463 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000464 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000465
Chris Lattner7e637512008-01-12 08:14:25 +0000466 // Pre-defined identifiers are of type char[x], where x is the length of the
467 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000468 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000469 if (getCurFunctionDecl())
470 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000471 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000472 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000473
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000474 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000475 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000476 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000477 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000478}
479
Steve Naroff87d58b42007-09-16 03:34:24 +0000480Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000481 llvm::SmallString<16> CharBuffer;
482 CharBuffer.resize(Tok.getLength());
483 const char *ThisTokBegin = &CharBuffer[0];
484 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
485
486 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
487 Tok.getLocation(), PP);
488 if (Literal.hadError())
489 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000490
491 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
492
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000493 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
494 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000495}
496
Steve Naroff87d58b42007-09-16 03:34:24 +0000497Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000498 // fast path for a single digit (which is quite common). A single digit
499 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
500 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000501 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000502
Chris Lattner8cd0e932008-03-05 18:54:05 +0000503 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000504 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000505 Context.IntTy,
506 Tok.getLocation()));
507 }
508 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000509 // Add padding so that NumericLiteralParser can overread by one character.
510 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000511 const char *ThisTokBegin = &IntegerBuffer[0];
512
513 // Get the spelling of the token, which eliminates trigraphs, etc.
514 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000515
Chris Lattner4b009652007-07-25 00:24:17 +0000516 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
517 Tok.getLocation(), PP);
518 if (Literal.hadError)
519 return ExprResult(true);
520
Chris Lattner1de66eb2007-08-26 03:42:43 +0000521 Expr *Res;
522
523 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000524 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000525 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000526 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000527 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000528 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000529 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000530 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000531
532 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
533
Ted Kremenekddedbe22007-11-29 00:56:49 +0000534 // isExact will be set by GetFloatValue().
535 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000536 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000537 Ty, Tok.getLocation());
538
Chris Lattner1de66eb2007-08-26 03:42:43 +0000539 } else if (!Literal.isIntegerLiteral()) {
540 return ExprResult(true);
541 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000542 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000543
Neil Booth7421e9c2007-08-29 22:00:19 +0000544 // long long is a C99 feature.
545 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000546 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000547 Diag(Tok.getLocation(), diag::ext_longlong);
548
Chris Lattner4b009652007-07-25 00:24:17 +0000549 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000550 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000551
552 if (Literal.GetIntegerValue(ResultVal)) {
553 // If this value didn't fit into uintmax_t, warn and force to ull.
554 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000555 Ty = Context.UnsignedLongLongTy;
556 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000557 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000558 } else {
559 // If this value fits into a ULL, try to figure out what else it fits into
560 // according to the rules of C99 6.4.4.1p5.
561
562 // Octal, Hexadecimal, and integers with a U suffix are allowed to
563 // be an unsigned int.
564 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
565
566 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000567 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000568 if (!Literal.isLong && !Literal.isLongLong) {
569 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000570 unsigned IntSize = Context.Target.getIntWidth();
571
Chris Lattner4b009652007-07-25 00:24:17 +0000572 // Does it fit in a unsigned int?
573 if (ResultVal.isIntN(IntSize)) {
574 // Does it fit in a signed int?
575 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000576 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000577 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000578 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000579 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000580 }
Chris Lattner4b009652007-07-25 00:24:17 +0000581 }
582
583 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000584 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000585 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000586
587 // Does it fit in a unsigned long?
588 if (ResultVal.isIntN(LongSize)) {
589 // Does it fit in a signed long?
590 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000591 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000592 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000593 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000594 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000595 }
Chris Lattner4b009652007-07-25 00:24:17 +0000596 }
597
598 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000599 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000600 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000601
602 // Does it fit in a unsigned long long?
603 if (ResultVal.isIntN(LongLongSize)) {
604 // Does it fit in a signed long long?
605 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000606 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000607 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000608 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000609 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000610 }
611 }
612
613 // If we still couldn't decide a type, we probably have something that
614 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000615 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000616 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000617 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000618 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000619 }
Chris Lattnere4068872008-05-09 05:59:00 +0000620
621 if (ResultVal.getBitWidth() != Width)
622 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000623 }
624
Chris Lattner48d7f382008-04-02 04:24:33 +0000625 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000626 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000627
628 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
629 if (Literal.isImaginary)
630 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
631
632 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000633}
634
Steve Naroff87d58b42007-09-16 03:34:24 +0000635Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000636 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000637 Expr *E = (Expr *)Val;
638 assert((E != 0) && "ActOnParenExpr() missing expr");
639 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000640}
641
642/// The UsualUnaryConversions() function is *not* called by this routine.
643/// See C99 6.3.2.1p[2-4] for more details.
644QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerf814d882008-07-25 21:45:37 +0000645 SourceLocation OpLoc,
646 const SourceRange &ExprRange,
647 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000648 // C99 6.5.3.4p1:
649 if (isa<FunctionType>(exprType) && isSizeof)
650 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000651 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000652 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000653 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
654 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000655 else if (exprType->isIncompleteType()) {
656 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
657 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000658 exprType.getAsString(), ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000659 return QualType(); // error
660 }
661 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
662 return Context.getSizeType();
663}
664
665Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000666ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000667 SourceLocation LPLoc, TypeTy *Ty,
668 SourceLocation RPLoc) {
669 // If error parsing type, ignore.
670 if (Ty == 0) return true;
671
672 // Verify that this is a valid expression.
673 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
674
Chris Lattnerf814d882008-07-25 21:45:37 +0000675 QualType resultType =
676 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Chris Lattner4b009652007-07-25 00:24:17 +0000677
678 if (resultType.isNull())
679 return true;
680 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
681}
682
Chris Lattner5110ad52007-08-24 21:41:10 +0000683QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000684 DefaultFunctionArrayConversion(V);
685
Chris Lattnera16e42d2007-08-26 05:39:26 +0000686 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000687 if (const ComplexType *CT = V->getType()->getAsComplexType())
688 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000689
690 // Otherwise they pass through real integer and floating point types here.
691 if (V->getType()->isArithmeticType())
692 return V->getType();
693
694 // Reject anything else.
695 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
696 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000697}
698
699
Chris Lattner4b009652007-07-25 00:24:17 +0000700
Steve Naroff87d58b42007-09-16 03:34:24 +0000701Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000702 tok::TokenKind Kind,
703 ExprTy *Input) {
704 UnaryOperator::Opcode Opc;
705 switch (Kind) {
706 default: assert(0 && "Unknown unary op!");
707 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
708 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
709 }
710 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
711 if (result.isNull())
712 return true;
713 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
714}
715
716Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000717ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000718 ExprTy *Idx, SourceLocation RLoc) {
719 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
720
721 // Perform default conversions.
722 DefaultFunctionArrayConversion(LHSExp);
723 DefaultFunctionArrayConversion(RHSExp);
724
725 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
726
727 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000728 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000729 // in the subscript position. As a result, we need to derive the array base
730 // and index from the expression types.
731 Expr *BaseExpr, *IndexExpr;
732 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000733 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000734 BaseExpr = LHSExp;
735 IndexExpr = RHSExp;
736 // FIXME: need to deal with const...
737 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000738 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000739 // Handle the uncommon case of "123[Ptr]".
740 BaseExpr = RHSExp;
741 IndexExpr = LHSExp;
742 // FIXME: need to deal with const...
743 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000744 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
745 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000746 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000747
748 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000749 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
750 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000751 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000752 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000753 // FIXME: need to deal with const...
754 ResultType = VTy->getElementType();
755 } else {
756 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
757 RHSExp->getSourceRange());
758 }
759 // C99 6.5.2.1p1
760 if (!IndexExpr->getType()->isIntegerType())
761 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
762 IndexExpr->getSourceRange());
763
764 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
765 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000766 // void (*)(int)) and pointers to incomplete types. Functions are not
767 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000768 if (!ResultType->isObjectType())
769 return Diag(BaseExpr->getLocStart(),
770 diag::err_typecheck_subscript_not_object,
771 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
772
773 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
774}
775
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000776QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000777CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000778 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000779 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000780
781 // This flag determines whether or not the component is to be treated as a
782 // special name, or a regular GLSL-style component access.
783 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000784
785 // The vector accessor can't exceed the number of elements.
786 const char *compStr = CompName.getName();
787 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000788 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000789 baseType.getAsString(), SourceRange(CompLoc));
790 return QualType();
791 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000792
793 // Check that we've found one of the special components, or that the component
794 // names must come from the same set.
795 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
796 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
797 SpecialComponent = true;
798 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000799 do
800 compStr++;
801 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
802 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
803 do
804 compStr++;
805 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
806 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
807 do
808 compStr++;
809 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
810 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000811
Nate Begemanc8e51f82008-05-09 06:41:27 +0000812 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000813 // We didn't get to the end of the string. This means the component names
814 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000815 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000816 std::string(compStr,compStr+1), SourceRange(CompLoc));
817 return QualType();
818 }
819 // Each component accessor can't exceed the vector type.
820 compStr = CompName.getName();
821 while (*compStr) {
822 if (vecType->isAccessorWithinNumElements(*compStr))
823 compStr++;
824 else
825 break;
826 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000827 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000828 // We didn't get to the end of the string. This means a component accessor
829 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000830 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000831 baseType.getAsString(), SourceRange(CompLoc));
832 return QualType();
833 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000834
835 // If we have a special component name, verify that the current vector length
836 // is an even number, since all special component names return exactly half
837 // the elements.
838 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Daniel Dunbar45a91802008-09-30 17:22:47 +0000839 Diag(OpLoc, diag::err_ext_vector_component_requires_even,
840 baseType.getAsString(), SourceRange(CompLoc));
Nate Begemanc8e51f82008-05-09 06:41:27 +0000841 return QualType();
842 }
843
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000844 // The component accessor looks fine - now we need to compute the actual type.
845 // The vector type is implied by the component accessor. For example,
846 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000847 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
848 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
849 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000850 if (CompSize == 1)
851 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000852
Nate Begemanaf6ed502008-04-18 23:10:10 +0000853 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000854 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000855 // diagostics look bad. We want extended vector types to appear built-in.
856 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
857 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
858 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000859 }
860 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000861}
862
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000863/// constructSetterName - Return the setter name for the given
864/// identifier, i.e. "set" + Name where the initial character of Name
865/// has been capitalized.
866// FIXME: Merge with same routine in Parser. But where should this
867// live?
868static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
869 const IdentifierInfo *Name) {
870 unsigned N = Name->getLength();
871 char *SelectorName = new char[3 + N];
872 memcpy(SelectorName, "set", 3);
873 memcpy(&SelectorName[3], Name->getName(), N);
874 SelectorName[3] = toupper(SelectorName[3]);
875
876 IdentifierInfo *Setter =
877 &Idents.get(SelectorName, &SelectorName[3 + N]);
878 delete[] SelectorName;
879 return Setter;
880}
881
Chris Lattner4b009652007-07-25 00:24:17 +0000882Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000883ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000884 tok::TokenKind OpKind, SourceLocation MemberLoc,
885 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000886 Expr *BaseExpr = static_cast<Expr *>(Base);
887 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000888
889 // Perform default conversions.
890 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000891
Steve Naroff2cb66382007-07-26 03:11:44 +0000892 QualType BaseType = BaseExpr->getType();
893 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000894
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000895 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
896 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000897 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000898 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000899 BaseType = PT->getPointeeType();
900 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000901 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
902 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000903 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000904
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000905 // Handle field access to simple records. This also handles access to fields
906 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000907 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000908 RecordDecl *RDecl = RTy->getDecl();
909 if (RTy->isIncompleteType())
910 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
911 BaseExpr->getSourceRange());
912 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000913 FieldDecl *MemberDecl = RDecl->getMember(&Member);
914 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000915 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
916 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000917
918 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000919 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000920 QualType MemberType = MemberDecl->getType();
921 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000922 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000923 MemberType = MemberType.getQualifiedType(combinedQualifiers);
924
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000925 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000926 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000927 }
928
Chris Lattnere9d71612008-07-21 04:59:05 +0000929 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
930 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000931 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
932 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000933 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000934 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000935 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000936 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000937 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000938 }
939
Chris Lattnere9d71612008-07-21 04:59:05 +0000940 // Handle Objective-C property access, which is "Obj.property" where Obj is a
941 // pointer to a (potentially qualified) interface type.
942 const PointerType *PTy;
943 const ObjCInterfaceType *IFTy;
944 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
945 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
946 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +0000947
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000948 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +0000949 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
950 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
951
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000952 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000953 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
954 E = IFTy->qual_end(); I != E; ++I)
955 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
956 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000957
958 // If that failed, look for an "implicit" property by seeing if the nullary
959 // selector is implemented.
960
961 // FIXME: The logic for looking up nullary and unary selectors should be
962 // shared with the code in ActOnInstanceMessage.
963
964 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
965 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
966
967 // If this reference is in an @implementation, check for 'private' methods.
968 if (!Getter)
969 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
970 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
971 if (ObjCImplementationDecl *ImpDecl =
972 ObjCImplementations[ClassDecl->getIdentifier()])
973 Getter = ImpDecl->getInstanceMethod(Sel);
974
Steve Naroff04151f32008-10-22 19:16:27 +0000975 // Look through local category implementations associated with the class.
976 if (!Getter) {
977 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
978 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
979 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
980 }
981 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000982 if (Getter) {
983 // If we found a getter then this may be a valid dot-reference, we
984 // need to also look for the matching setter.
985 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
986 &Member);
987 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
988 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
989
990 if (!Setter) {
991 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
992 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
993 if (ObjCImplementationDecl *ImpDecl =
994 ObjCImplementations[ClassDecl->getIdentifier()])
995 Setter = ImpDecl->getInstanceMethod(SetterSel);
996 }
997
998 // FIXME: There are some issues here. First, we are not
999 // diagnosing accesses to read-only properties because we do not
1000 // know if this is a getter or setter yet. Second, we are
1001 // checking that the type of the setter matches the type we
1002 // expect.
1003 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1004 MemberLoc, BaseExpr);
1005 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001006 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001007 // Handle properties on qualified "id" protocols.
1008 const ObjCQualifiedIdType *QIdTy;
1009 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1010 // Check protocols on qualified interfaces.
1011 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1012 E = QIdTy->qual_end(); I != E; ++I)
1013 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1014 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1015 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001016 // Handle 'field access' to vectors, such as 'V.xx'.
1017 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1018 // Component access limited to variables (reject vec4.rg.g).
1019 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1020 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +00001021 return Diag(MemberLoc, diag::err_ext_vector_component_access,
1022 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001023 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1024 if (ret.isNull())
1025 return true;
1026 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1027 }
1028
Chris Lattner7d5a8762008-07-21 05:35:34 +00001029 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1030 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001031}
1032
Steve Naroff87d58b42007-09-16 03:34:24 +00001033/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001034/// This provides the location of the left/right parens and a list of comma
1035/// locations.
1036Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001037ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001038 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001039 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1040 Expr *Fn = static_cast<Expr *>(fn);
1041 Expr **Args = reinterpret_cast<Expr**>(args);
1042 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001043 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001044 OverloadedFunctionDecl *Ovl = NULL;
1045
1046 // If we're directly calling a function or a set of overloaded
1047 // functions, get the appropriate declaration.
1048 {
1049 DeclRefExpr *DRExpr = NULL;
1050 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1051 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1052 else
1053 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1054
1055 if (DRExpr) {
1056 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1057 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1058 }
1059 }
1060
1061 // If we have a set of overloaded functions, perform overload
1062 // resolution to pick the function.
1063 if (Ovl) {
1064 OverloadCandidateSet CandidateSet;
1065 OverloadCandidateSet::iterator Best;
1066 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
1067 switch (BestViableFunction(CandidateSet, Best)) {
1068 case OR_Success:
1069 {
1070 // Success! Let the remainder of this function build a call to
1071 // the function selected by overload resolution.
1072 FDecl = Best->Function;
1073 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1074 Fn->getSourceRange().getBegin());
1075 delete Fn;
1076 Fn = NewFn;
1077 }
1078 break;
1079
1080 case OR_No_Viable_Function:
1081 if (CandidateSet.empty())
1082 Diag(Fn->getSourceRange().getBegin(),
1083 diag::err_ovl_no_viable_function_in_call, Ovl->getName(),
1084 Fn->getSourceRange());
1085 else {
1086 Diag(Fn->getSourceRange().getBegin(),
1087 diag::err_ovl_no_viable_function_in_call_with_cands,
1088 Ovl->getName(), Fn->getSourceRange());
1089 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1090 }
1091 return true;
1092
1093 case OR_Ambiguous:
1094 Diag(Fn->getSourceRange().getBegin(),
1095 diag::err_ovl_ambiguous_call, Ovl->getName(),
1096 Fn->getSourceRange());
1097 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1098 return true;
1099 }
1100 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001101
1102 // Promote the function operand.
1103 UsualUnaryConversions(Fn);
1104
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001105 // Make the call expr early, before semantic checks. This guarantees cleanup
1106 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001107 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001108 Context.BoolTy, RParenLoc));
Steve Naroffd6163f32008-09-05 22:11:13 +00001109 const FunctionType *FuncT;
1110 if (!Fn->getType()->isBlockPointerType()) {
1111 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1112 // have type pointer to function".
1113 const PointerType *PT = Fn->getType()->getAsPointerType();
1114 if (PT == 0)
1115 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1116 Fn->getSourceRange());
1117 FuncT = PT->getPointeeType()->getAsFunctionType();
1118 } else { // This is a block call.
1119 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1120 getAsFunctionType();
1121 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001122 if (FuncT == 0)
Chris Lattner61000b12008-08-14 04:33:24 +00001123 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1124 Fn->getSourceRange());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001125
1126 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001127 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001128
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001129 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001130 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1131 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001132 unsigned NumArgsInProto = Proto->getNumArgs();
1133 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001134
Chris Lattner3e254fb2008-04-08 04:40:51 +00001135 // If too few arguments are available (and we don't have default
1136 // arguments for the remaining parameters), don't make the call.
1137 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +00001138 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001139 // Use default arguments for missing arguments
1140 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +00001141 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001142 } else
Steve Naroffd6163f32008-09-05 22:11:13 +00001143 return Diag(RParenLoc,
1144 !Fn->getType()->isBlockPointerType()
1145 ? diag::err_typecheck_call_too_few_args
1146 : diag::err_typecheck_block_too_few_args,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001147 Fn->getSourceRange());
1148 }
1149
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001150 // If too many are passed and not variadic, error on the extras and drop
1151 // them.
1152 if (NumArgs > NumArgsInProto) {
1153 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001154 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffd6163f32008-09-05 22:11:13 +00001155 !Fn->getType()->isBlockPointerType()
1156 ? diag::err_typecheck_call_too_many_args
1157 : diag::err_typecheck_block_too_many_args,
1158 Fn->getSourceRange(),
Chris Lattner4b009652007-07-25 00:24:17 +00001159 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001160 Args[NumArgs-1]->getLocEnd()));
1161 // This deletes the extra arguments.
1162 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001163 }
1164 NumArgsToCheck = NumArgsInProto;
1165 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001166
Chris Lattner4b009652007-07-25 00:24:17 +00001167 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001168 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001169 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001170
1171 Expr *Arg;
1172 if (i < NumArgs)
1173 Arg = Args[i];
1174 else
1175 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001176 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001177
Douglas Gregor81c29152008-10-29 00:13:59 +00001178 // Pass the argument.
1179 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner005ed752008-01-04 18:04:52 +00001180 return true;
Douglas Gregor81c29152008-10-29 00:13:59 +00001181
1182 TheCall->setArg(i, Arg);
Chris Lattner4b009652007-07-25 00:24:17 +00001183 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001184
1185 // If this is a variadic call, handle args passed through "...".
1186 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001187 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001188 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1189 Expr *Arg = Args[i];
1190 DefaultArgumentPromotion(Arg);
1191 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001192 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001193 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001194 } else {
1195 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1196
Steve Naroffdb65e052007-08-28 23:30:39 +00001197 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001198 for (unsigned i = 0; i != NumArgs; i++) {
1199 Expr *Arg = Args[i];
1200 DefaultArgumentPromotion(Arg);
1201 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001202 }
Chris Lattner4b009652007-07-25 00:24:17 +00001203 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001204
Chris Lattner2e64c072007-08-10 20:18:51 +00001205 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001206 if (FDecl)
1207 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001208
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001209 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001210}
1211
1212Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001213ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001214 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001215 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001216 QualType literalType = QualType::getFromOpaquePtr(Ty);
1217 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001218 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001219 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001220
Eli Friedman8c2173d2008-05-20 05:22:08 +00001221 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001222 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001223 return Diag(LParenLoc,
1224 diag::err_variable_object_no_init,
1225 SourceRange(LParenLoc,
1226 literalExpr->getSourceRange().getEnd()));
1227 } else if (literalType->isIncompleteType()) {
1228 return Diag(LParenLoc,
1229 diag::err_typecheck_decl_incomplete_type,
1230 literalType.getAsString(),
1231 SourceRange(LParenLoc,
1232 literalExpr->getSourceRange().getEnd()));
1233 }
1234
Douglas Gregor6428e762008-11-05 15:29:30 +00001235 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
1236 "temporary"))
Steve Naroff92590f92008-01-09 20:58:06 +00001237 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001238
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001239 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001240 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001241 if (CheckForConstantInitializer(literalExpr, literalType))
1242 return true;
1243 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001244 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1245 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001246}
1247
1248Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001249ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001250 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001251 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001252 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001253
Steve Naroff0acc9c92007-09-15 18:49:24 +00001254 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001255 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001256
Chris Lattner71ca8c82008-10-26 23:43:26 +00001257 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1258 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001259 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1260 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001261}
1262
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001263/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001264bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001265 UsualUnaryConversions(castExpr);
1266
1267 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1268 // type needs to be scalar.
1269 if (castType->isVoidType()) {
1270 // Cast to void allows any expr type.
1271 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1272 // GCC struct/union extension: allow cast to self.
1273 if (Context.getCanonicalType(castType) !=
1274 Context.getCanonicalType(castExpr->getType()) ||
1275 (!castType->isStructureType() && !castType->isUnionType())) {
1276 // Reject any other conversions to non-scalar types.
1277 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1278 castType.getAsString(), castExpr->getSourceRange());
1279 }
1280
1281 // accept this, but emit an ext-warn.
1282 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1283 castType.getAsString(), castExpr->getSourceRange());
1284 } else if (!castExpr->getType()->isScalarType() &&
1285 !castExpr->getType()->isVectorType()) {
1286 return Diag(castExpr->getLocStart(),
1287 diag::err_typecheck_expect_scalar_operand,
1288 castExpr->getType().getAsString(),castExpr->getSourceRange());
1289 } else if (castExpr->getType()->isVectorType()) {
1290 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1291 return true;
1292 } else if (castType->isVectorType()) {
1293 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1294 return true;
1295 }
1296 return false;
1297}
1298
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001299bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001300 assert(VectorTy->isVectorType() && "Not a vector type!");
1301
1302 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001303 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001304 return Diag(R.getBegin(),
1305 Ty->isVectorType() ?
1306 diag::err_invalid_conversion_between_vectors :
1307 diag::err_invalid_conversion_between_vector_and_integer,
1308 VectorTy.getAsString().c_str(),
1309 Ty.getAsString().c_str(), R);
1310 } else
1311 return Diag(R.getBegin(),
1312 diag::err_invalid_conversion_between_vector_and_scalar,
1313 VectorTy.getAsString().c_str(),
1314 Ty.getAsString().c_str(), R);
1315
1316 return false;
1317}
1318
Chris Lattner4b009652007-07-25 00:24:17 +00001319Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001320ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001321 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001322 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001323
1324 Expr *castExpr = static_cast<Expr*>(Op);
1325 QualType castType = QualType::getFromOpaquePtr(Ty);
1326
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001327 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1328 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00001329 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001330}
1331
Chris Lattner98a425c2007-11-26 01:40:58 +00001332/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1333/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001334inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1335 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1336 UsualUnaryConversions(cond);
1337 UsualUnaryConversions(lex);
1338 UsualUnaryConversions(rex);
1339 QualType condT = cond->getType();
1340 QualType lexT = lex->getType();
1341 QualType rexT = rex->getType();
1342
1343 // first, check the condition.
1344 if (!condT->isScalarType()) { // C99 6.5.15p2
1345 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1346 condT.getAsString());
1347 return QualType();
1348 }
Chris Lattner992ae932008-01-06 22:42:25 +00001349
1350 // Now check the two expressions.
1351
1352 // If both operands have arithmetic type, do the usual arithmetic conversions
1353 // to find a common type: C99 6.5.15p3,5.
1354 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001355 UsualArithmeticConversions(lex, rex);
1356 return lex->getType();
1357 }
Chris Lattner992ae932008-01-06 22:42:25 +00001358
1359 // If both operands are the same structure or union type, the result is that
1360 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001361 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001362 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001363 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001364 // "If both the operands have structure or union type, the result has
1365 // that type." This implies that CV qualifiers are dropped.
1366 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001367 }
Chris Lattner992ae932008-01-06 22:42:25 +00001368
1369 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001370 // The following || allows only one side to be void (a GCC-ism).
1371 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001372 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001373 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1374 rex->getSourceRange());
1375 if (!rexT->isVoidType())
1376 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001377 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001378 ImpCastExprToType(lex, Context.VoidTy);
1379 ImpCastExprToType(rex, Context.VoidTy);
1380 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001381 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001382 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1383 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001384 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1385 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001386 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001387 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001388 return lexT;
1389 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001390 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1391 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001392 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001393 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001394 return rexT;
1395 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001396 // Handle the case where both operands are pointers before we handle null
1397 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001398 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1399 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1400 // get the "pointed to" types
1401 QualType lhptee = LHSPT->getPointeeType();
1402 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001403
Chris Lattner71225142007-07-31 21:27:01 +00001404 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1405 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001406 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001407 // Figure out necessary qualifiers (C99 6.5.15p6)
1408 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001409 QualType destType = Context.getPointerType(destPointee);
1410 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1411 ImpCastExprToType(rex, destType); // promote to void*
1412 return destType;
1413 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001414 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001415 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001416 QualType destType = Context.getPointerType(destPointee);
1417 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1418 ImpCastExprToType(rex, destType); // promote to void*
1419 return destType;
1420 }
Chris Lattner4b009652007-07-25 00:24:17 +00001421
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001422 QualType compositeType = lexT;
1423
1424 // If either type is an Objective-C object type then check
1425 // compatibility according to Objective-C.
1426 if (Context.isObjCObjectPointerType(lexT) ||
1427 Context.isObjCObjectPointerType(rexT)) {
1428 // If both operands are interfaces and either operand can be
1429 // assigned to the other, use that type as the composite
1430 // type. This allows
1431 // xxx ? (A*) a : (B*) b
1432 // where B is a subclass of A.
1433 //
1434 // Additionally, as for assignment, if either type is 'id'
1435 // allow silent coercion. Finally, if the types are
1436 // incompatible then make sure to use 'id' as the composite
1437 // type so the result is acceptable for sending messages to.
1438
1439 // FIXME: This code should not be localized to here. Also this
1440 // should use a compatible check instead of abusing the
1441 // canAssignObjCInterfaces code.
1442 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1443 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1444 if (LHSIface && RHSIface &&
1445 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1446 compositeType = lexT;
1447 } else if (LHSIface && RHSIface &&
1448 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1449 compositeType = rexT;
1450 } else if (Context.isObjCIdType(lhptee) ||
1451 Context.isObjCIdType(rhptee)) {
1452 // FIXME: This code looks wrong, because isObjCIdType checks
1453 // the struct but getObjCIdType returns the pointer to
1454 // struct. This is horrible and should be fixed.
1455 compositeType = Context.getObjCIdType();
1456 } else {
1457 QualType incompatTy = Context.getObjCIdType();
1458 ImpCastExprToType(lex, incompatTy);
1459 ImpCastExprToType(rex, incompatTy);
1460 return incompatTy;
1461 }
1462 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1463 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001464 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001465 lexT.getAsString(), rexT.getAsString(),
1466 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001467 // In this situation, we assume void* type. No especially good
1468 // reason, but this is what gcc does, and we do have to pick
1469 // to get a consistent AST.
1470 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001471 ImpCastExprToType(lex, incompatTy);
1472 ImpCastExprToType(rex, incompatTy);
1473 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001474 }
1475 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001476 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1477 // differently qualified versions of compatible types, the result type is
1478 // a pointer to an appropriately qualified version of the *composite*
1479 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001480 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001481 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001482 ImpCastExprToType(lex, compositeType);
1483 ImpCastExprToType(rex, compositeType);
1484 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001485 }
Chris Lattner4b009652007-07-25 00:24:17 +00001486 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001487 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1488 // evaluates to "struct objc_object *" (and is handled above when comparing
1489 // id with statically typed objects).
1490 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1491 // GCC allows qualified id and any Objective-C type to devolve to
1492 // id. Currently localizing to here until clear this should be
1493 // part of ObjCQualifiedIdTypesAreCompatible.
1494 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1495 (lexT->isObjCQualifiedIdType() &&
1496 Context.isObjCObjectPointerType(rexT)) ||
1497 (rexT->isObjCQualifiedIdType() &&
1498 Context.isObjCObjectPointerType(lexT))) {
1499 // FIXME: This is not the correct composite type. This only
1500 // happens to work because id can more or less be used anywhere,
1501 // however this may change the type of method sends.
1502 // FIXME: gcc adds some type-checking of the arguments and emits
1503 // (confusing) incompatible comparison warnings in some
1504 // cases. Investigate.
1505 QualType compositeType = Context.getObjCIdType();
1506 ImpCastExprToType(lex, compositeType);
1507 ImpCastExprToType(rex, compositeType);
1508 return compositeType;
1509 }
1510 }
1511
Steve Naroff3eac7692008-09-10 19:17:48 +00001512 // Selection between block pointer types is ok as long as they are the same.
1513 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1514 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1515 return lexT;
1516
Chris Lattner992ae932008-01-06 22:42:25 +00001517 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001518 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1519 lexT.getAsString(), rexT.getAsString(),
1520 lex->getSourceRange(), rex->getSourceRange());
1521 return QualType();
1522}
1523
Steve Naroff87d58b42007-09-16 03:34:24 +00001524/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001525/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001526Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001527 SourceLocation ColonLoc,
1528 ExprTy *Cond, ExprTy *LHS,
1529 ExprTy *RHS) {
1530 Expr *CondExpr = (Expr *) Cond;
1531 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001532
1533 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1534 // was the condition.
1535 bool isLHSNull = LHSExpr == 0;
1536 if (isLHSNull)
1537 LHSExpr = CondExpr;
1538
Chris Lattner4b009652007-07-25 00:24:17 +00001539 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1540 RHSExpr, QuestionLoc);
1541 if (result.isNull())
1542 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001543 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1544 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001545}
1546
Chris Lattner4b009652007-07-25 00:24:17 +00001547
1548// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1549// being closely modeled after the C99 spec:-). The odd characteristic of this
1550// routine is it effectively iqnores the qualifiers on the top level pointee.
1551// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1552// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001553Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001554Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1555 QualType lhptee, rhptee;
1556
1557 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001558 lhptee = lhsType->getAsPointerType()->getPointeeType();
1559 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001560
1561 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001562 lhptee = Context.getCanonicalType(lhptee);
1563 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001564
Chris Lattner005ed752008-01-04 18:04:52 +00001565 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001566
1567 // C99 6.5.16.1p1: This following citation is common to constraints
1568 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1569 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001570 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001571 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001572 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001573
1574 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1575 // incomplete type and the other is a pointer to a qualified or unqualified
1576 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001577 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001578 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001579 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001580
1581 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001582 assert(rhptee->isFunctionType());
1583 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001584 }
1585
1586 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001587 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001588 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001589
1590 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001591 assert(lhptee->isFunctionType());
1592 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001593 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001594
1595 // Check for ObjC interfaces
1596 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1597 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1598 if (LHSIface && RHSIface &&
1599 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1600 return ConvTy;
1601
1602 // ID acts sort of like void* for ObjC interfaces
1603 if (LHSIface && Context.isObjCIdType(rhptee))
1604 return ConvTy;
1605 if (RHSIface && Context.isObjCIdType(lhptee))
1606 return ConvTy;
1607
Chris Lattner4b009652007-07-25 00:24:17 +00001608 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1609 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001610 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1611 rhptee.getUnqualifiedType()))
1612 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001613 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001614}
1615
Steve Naroff3454b6c2008-09-04 15:10:53 +00001616/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1617/// block pointer types are compatible or whether a block and normal pointer
1618/// are compatible. It is more restrict than comparing two function pointer
1619// types.
1620Sema::AssignConvertType
1621Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1622 QualType rhsType) {
1623 QualType lhptee, rhptee;
1624
1625 // get the "pointed to" type (ignoring qualifiers at the top level)
1626 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1627 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1628
1629 // make sure we operate on the canonical type
1630 lhptee = Context.getCanonicalType(lhptee);
1631 rhptee = Context.getCanonicalType(rhptee);
1632
1633 AssignConvertType ConvTy = Compatible;
1634
1635 // For blocks we enforce that qualifiers are identical.
1636 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1637 ConvTy = CompatiblePointerDiscardsQualifiers;
1638
1639 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1640 return IncompatibleBlockPointer;
1641 return ConvTy;
1642}
1643
Chris Lattner4b009652007-07-25 00:24:17 +00001644/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1645/// has code to accommodate several GCC extensions when type checking
1646/// pointers. Here are some objectionable examples that GCC considers warnings:
1647///
1648/// int a, *pint;
1649/// short *pshort;
1650/// struct foo *pfoo;
1651///
1652/// pint = pshort; // warning: assignment from incompatible pointer type
1653/// a = pint; // warning: assignment makes integer from pointer without a cast
1654/// pint = a; // warning: assignment makes pointer from integer without a cast
1655/// pint = pfoo; // warning: assignment from incompatible pointer type
1656///
1657/// As a result, the code for dealing with pointers is more complex than the
1658/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001659///
Chris Lattner005ed752008-01-04 18:04:52 +00001660Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001661Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001662 // Get canonical types. We're not formatting these types, just comparing
1663 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001664 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1665 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001666
1667 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001668 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001669
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001670 // If the left-hand side is a reference type, then we are in a
1671 // (rare!) case where we've allowed the use of references in C,
1672 // e.g., as a parameter type in a built-in function. In this case,
1673 // just make sure that the type referenced is compatible with the
1674 // right-hand side type. The caller is responsible for adjusting
1675 // lhsType so that the resulting expression does not have reference
1676 // type.
1677 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
1678 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001679 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001680 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001681 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001682
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001683 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1684 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001685 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001686 // Relax integer conversions like we do for pointers below.
1687 if (rhsType->isIntegerType())
1688 return IntToPointer;
1689 if (lhsType->isIntegerType())
1690 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00001691 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001692 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001693
Nate Begemanc5f0f652008-07-14 18:02:46 +00001694 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001695 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001696 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1697 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001698 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001699
Nate Begemanc5f0f652008-07-14 18:02:46 +00001700 // If we are allowing lax vector conversions, and LHS and RHS are both
1701 // vectors, the total size only needs to be the same. This is a bitcast;
1702 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001703 if (getLangOptions().LaxVectorConversions &&
1704 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001705 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1706 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001707 }
1708 return Incompatible;
1709 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001710
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001711 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001712 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001713
Chris Lattner390564e2008-04-07 06:49:41 +00001714 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001715 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001716 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001717
Chris Lattner390564e2008-04-07 06:49:41 +00001718 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001719 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001720
Steve Naroffa982c712008-09-29 18:10:17 +00001721 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00001722 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff3454b6c2008-09-04 15:10:53 +00001723 return BlockVoidPointer;
Steve Naroffa982c712008-09-29 18:10:17 +00001724
1725 // Treat block pointers as objects.
1726 if (getLangOptions().ObjC1 &&
1727 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1728 return Compatible;
1729 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001730 return Incompatible;
1731 }
1732
1733 if (isa<BlockPointerType>(lhsType)) {
1734 if (rhsType->isIntegerType())
1735 return IntToPointer;
1736
Steve Naroffa982c712008-09-29 18:10:17 +00001737 // Treat block pointers as objects.
1738 if (getLangOptions().ObjC1 &&
1739 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1740 return Compatible;
1741
Steve Naroff3454b6c2008-09-04 15:10:53 +00001742 if (rhsType->isBlockPointerType())
1743 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1744
1745 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1746 if (RHSPT->getPointeeType()->isVoidType())
1747 return BlockVoidPointer;
1748 }
Chris Lattner1853da22008-01-04 23:18:45 +00001749 return Incompatible;
1750 }
1751
Chris Lattner390564e2008-04-07 06:49:41 +00001752 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001753 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001754 if (lhsType == Context.BoolTy)
1755 return Compatible;
1756
1757 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001758 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001759
Chris Lattner390564e2008-04-07 06:49:41 +00001760 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001761 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001762
1763 if (isa<BlockPointerType>(lhsType) &&
1764 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1765 return BlockVoidPointer;
Chris Lattner1853da22008-01-04 23:18:45 +00001766 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001767 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001768
Chris Lattner1853da22008-01-04 23:18:45 +00001769 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001770 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001771 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001772 }
1773 return Incompatible;
1774}
1775
Chris Lattner005ed752008-01-04 18:04:52 +00001776Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001777Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001778 if (getLangOptions().CPlusPlus) {
1779 if (!lhsType->isRecordType()) {
1780 // C++ 5.17p3: If the left operand is not of class type, the
1781 // expression is implicitly converted (C++ 4) to the
1782 // cv-unqualified type of the left operand.
Douglas Gregorbb461502008-10-24 04:54:22 +00001783 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001784 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00001785 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001786 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001787 }
1788
1789 // FIXME: Currently, we fall through and treat C++ classes like C
1790 // structures.
1791 }
1792
Steve Naroffcdee22d2007-11-27 17:58:44 +00001793 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1794 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00001795 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1796 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001797 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001798 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001799 return Compatible;
1800 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001801
1802 // We don't allow conversion of non-null-pointer constants to integers.
1803 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1804 return IntToBlockPointer;
1805
Chris Lattner5f505bf2007-10-16 02:55:40 +00001806 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001807 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001808 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001809 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001810 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001811 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00001812 if (!lhsType->isReferenceType())
1813 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001814
Chris Lattner005ed752008-01-04 18:04:52 +00001815 Sema::AssignConvertType result =
1816 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001817
1818 // C99 6.5.16.1p2: The value of the right operand is converted to the
1819 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001820 // CheckAssignmentConstraints allows the left-hand side to be a reference,
1821 // so that we can use references in built-in functions even in C.
1822 // The getNonReferenceType() call makes sure that the resulting expression
1823 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00001824 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001825 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001826 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001827}
1828
Chris Lattner005ed752008-01-04 18:04:52 +00001829Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001830Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1831 return CheckAssignmentConstraints(lhsType, rhsType);
1832}
1833
Chris Lattner2c8bff72007-12-12 05:47:28 +00001834QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001835 Diag(loc, diag::err_typecheck_invalid_operands,
1836 lex->getType().getAsString(), rex->getType().getAsString(),
1837 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001838 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001839}
1840
1841inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1842 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001843 // For conversion purposes, we ignore any qualifiers.
1844 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001845 QualType lhsType =
1846 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1847 QualType rhsType =
1848 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001849
Nate Begemanc5f0f652008-07-14 18:02:46 +00001850 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001851 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001852 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001853
Nate Begemanc5f0f652008-07-14 18:02:46 +00001854 // Handle the case of a vector & extvector type of the same size and element
1855 // type. It would be nice if we only had one vector type someday.
1856 if (getLangOptions().LaxVectorConversions)
1857 if (const VectorType *LV = lhsType->getAsVectorType())
1858 if (const VectorType *RV = rhsType->getAsVectorType())
1859 if (LV->getElementType() == RV->getElementType() &&
1860 LV->getNumElements() == RV->getNumElements())
1861 return lhsType->isExtVectorType() ? lhsType : rhsType;
1862
1863 // If the lhs is an extended vector and the rhs is a scalar of the same type
1864 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001865 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001866 QualType eltType = V->getElementType();
1867
1868 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1869 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1870 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001871 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001872 return lhsType;
1873 }
1874 }
1875
Nate Begemanc5f0f652008-07-14 18:02:46 +00001876 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001877 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001878 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001879 QualType eltType = V->getElementType();
1880
1881 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1882 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1883 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001884 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001885 return rhsType;
1886 }
1887 }
1888
Chris Lattner4b009652007-07-25 00:24:17 +00001889 // You cannot convert between vector values of different size.
1890 Diag(loc, diag::err_typecheck_vector_not_convertable,
1891 lex->getType().getAsString(), rex->getType().getAsString(),
1892 lex->getSourceRange(), rex->getSourceRange());
1893 return QualType();
1894}
1895
1896inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001897 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001898{
1899 QualType lhsType = lex->getType(), rhsType = rex->getType();
1900
1901 if (lhsType->isVectorType() || rhsType->isVectorType())
1902 return CheckVectorOperands(loc, lex, rex);
1903
Steve Naroff8f708362007-08-24 19:07:16 +00001904 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001905
Chris Lattner4b009652007-07-25 00:24:17 +00001906 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001907 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001908 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001909}
1910
1911inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001912 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001913{
1914 QualType lhsType = lex->getType(), rhsType = rex->getType();
1915
Steve Naroff8f708362007-08-24 19:07:16 +00001916 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001917
Chris Lattner4b009652007-07-25 00:24:17 +00001918 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001919 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001920 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001921}
1922
1923inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001924 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001925{
1926 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1927 return CheckVectorOperands(loc, lex, rex);
1928
Steve Naroff8f708362007-08-24 19:07:16 +00001929 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001930
Chris Lattner4b009652007-07-25 00:24:17 +00001931 // handle the common case first (both operands are arithmetic).
1932 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001933 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001934
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001935 // Put any potential pointer into PExp
1936 Expr* PExp = lex, *IExp = rex;
1937 if (IExp->getType()->isPointerType())
1938 std::swap(PExp, IExp);
1939
1940 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1941 if (IExp->getType()->isIntegerType()) {
1942 // Check for arithmetic on pointers to incomplete types
1943 if (!PTy->getPointeeType()->isObjectType()) {
1944 if (PTy->getPointeeType()->isVoidType()) {
1945 Diag(loc, diag::ext_gnu_void_ptr,
1946 lex->getSourceRange(), rex->getSourceRange());
1947 } else {
1948 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1949 lex->getType().getAsString(), lex->getSourceRange());
1950 return QualType();
1951 }
1952 }
1953 return PExp->getType();
1954 }
1955 }
1956
Chris Lattner2c8bff72007-12-12 05:47:28 +00001957 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001958}
1959
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001960// C99 6.5.6
1961QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1962 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001963 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1964 return CheckVectorOperands(loc, lex, rex);
1965
Steve Naroff8f708362007-08-24 19:07:16 +00001966 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001967
Chris Lattnerf6da2912007-12-09 21:53:25 +00001968 // Enforce type constraints: C99 6.5.6p3.
1969
1970 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001971 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001972 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001973
1974 // Either ptr - int or ptr - ptr.
1975 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001976 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001977
Chris Lattnerf6da2912007-12-09 21:53:25 +00001978 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001979 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001980 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001981 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001982 Diag(loc, diag::ext_gnu_void_ptr,
1983 lex->getSourceRange(), rex->getSourceRange());
1984 } else {
1985 Diag(loc, diag::err_typecheck_sub_ptr_object,
1986 lex->getType().getAsString(), lex->getSourceRange());
1987 return QualType();
1988 }
1989 }
1990
1991 // The result type of a pointer-int computation is the pointer type.
1992 if (rex->getType()->isIntegerType())
1993 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001994
Chris Lattnerf6da2912007-12-09 21:53:25 +00001995 // Handle pointer-pointer subtractions.
1996 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001997 QualType rpointee = RHSPTy->getPointeeType();
1998
Chris Lattnerf6da2912007-12-09 21:53:25 +00001999 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002000 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002001 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002002 if (rpointee->isVoidType()) {
2003 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00002004 Diag(loc, diag::ext_gnu_void_ptr,
2005 lex->getSourceRange(), rex->getSourceRange());
2006 } else {
2007 Diag(loc, diag::err_typecheck_sub_ptr_object,
2008 rex->getType().getAsString(), rex->getSourceRange());
2009 return QualType();
2010 }
2011 }
2012
2013 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002014 if (!Context.typesAreCompatible(
2015 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2016 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002017 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
2018 lex->getType().getAsString(), rex->getType().getAsString(),
2019 lex->getSourceRange(), rex->getSourceRange());
2020 return QualType();
2021 }
2022
2023 return Context.getPointerDiffType();
2024 }
2025 }
2026
Chris Lattner2c8bff72007-12-12 05:47:28 +00002027 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002028}
2029
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002030// C99 6.5.7
2031QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2032 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002033 // C99 6.5.7p2: Each of the operands shall have integer type.
2034 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
2035 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002036
Chris Lattner2c8bff72007-12-12 05:47:28 +00002037 // Shifts don't perform usual arithmetic conversions, they just do integer
2038 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002039 if (!isCompAssign)
2040 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002041 UsualUnaryConversions(rex);
2042
2043 // "The type of the result is that of the promoted left operand."
2044 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002045}
2046
Eli Friedman0d9549b2008-08-22 00:56:42 +00002047static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2048 ASTContext& Context) {
2049 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2050 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2051 // ID acts sort of like void* for ObjC interfaces
2052 if (LHSIface && Context.isObjCIdType(RHS))
2053 return true;
2054 if (RHSIface && Context.isObjCIdType(LHS))
2055 return true;
2056 if (!LHSIface || !RHSIface)
2057 return false;
2058 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2059 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2060}
2061
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002062// C99 6.5.8
2063QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2064 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002065 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2066 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
2067
Chris Lattner254f3bc2007-08-26 01:18:55 +00002068 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002069 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2070 UsualArithmeticConversions(lex, rex);
2071 else {
2072 UsualUnaryConversions(lex);
2073 UsualUnaryConversions(rex);
2074 }
Chris Lattner4b009652007-07-25 00:24:17 +00002075 QualType lType = lex->getType();
2076 QualType rType = rex->getType();
2077
Ted Kremenek486509e2007-10-29 17:13:39 +00002078 // For non-floating point types, check for self-comparisons of the form
2079 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2080 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002081 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002082 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2083 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002084 if (DRL->getDecl() == DRR->getDecl())
2085 Diag(loc, diag::warn_selfcomparison);
2086 }
2087
Chris Lattner254f3bc2007-08-26 01:18:55 +00002088 if (isRelational) {
2089 if (lType->isRealType() && rType->isRealType())
2090 return Context.IntTy;
2091 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002092 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002093 if (lType->isFloatingType()) {
2094 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00002095 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002096 }
2097
Chris Lattner254f3bc2007-08-26 01:18:55 +00002098 if (lType->isArithmeticType() && rType->isArithmeticType())
2099 return Context.IntTy;
2100 }
Chris Lattner4b009652007-07-25 00:24:17 +00002101
Chris Lattner22be8422007-08-26 01:10:14 +00002102 bool LHSIsNull = lex->isNullPointerConstant(Context);
2103 bool RHSIsNull = rex->isNullPointerConstant(Context);
2104
Chris Lattner254f3bc2007-08-26 01:18:55 +00002105 // All of the following pointer related warnings are GCC extensions, except
2106 // when handling null pointer constants. One day, we can consider making them
2107 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002108 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002109 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002110 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002111 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002112 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002113
Steve Naroff3b435622007-11-13 14:57:38 +00002114 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002115 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2116 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002117 RCanPointeeTy.getUnqualifiedType()) &&
2118 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroff4462cb02007-08-16 21:48:38 +00002119 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2120 lType.getAsString(), rType.getAsString(),
2121 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002122 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002123 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002124 return Context.IntTy;
2125 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002126 // Handle block pointer types.
2127 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2128 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2129 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2130
2131 if (!LHSIsNull && !RHSIsNull &&
2132 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2133 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2134 lType.getAsString(), rType.getAsString(),
2135 lex->getSourceRange(), rex->getSourceRange());
2136 }
2137 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2138 return Context.IntTy;
2139 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002140 // Allow block pointers to be compared with null pointer constants.
2141 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2142 (lType->isPointerType() && rType->isBlockPointerType())) {
2143 if (!LHSIsNull && !RHSIsNull) {
2144 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2145 lType.getAsString(), rType.getAsString(),
2146 lex->getSourceRange(), rex->getSourceRange());
2147 }
2148 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2149 return Context.IntTy;
2150 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002151
Steve Naroff936c4362008-06-03 14:04:54 +00002152 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002153 if (lType->isPointerType() || rType->isPointerType()) {
2154 if (!Context.typesAreCompatible(lType, rType)) {
2155 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2156 lType.getAsString(), rType.getAsString(),
2157 lex->getSourceRange(), rex->getSourceRange());
2158 ImpCastExprToType(rex, lType);
2159 return Context.IntTy;
2160 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002161 ImpCastExprToType(rex, lType);
Steve Naroff792800d2008-10-22 22:40:28 +00002162 return Context.IntTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002163 }
Steve Naroff936c4362008-06-03 14:04:54 +00002164 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2165 ImpCastExprToType(rex, lType);
2166 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002167 } else {
2168 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
2169 Diag(loc, diag::warn_incompatible_qualified_id_operands,
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002170 lType.getAsString(), rType.getAsString(),
Steve Naroff19608432008-10-14 22:18:38 +00002171 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002172 ImpCastExprToType(rex, lType);
Steve Naroff792800d2008-10-22 22:40:28 +00002173 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002174 }
Steve Naroff936c4362008-06-03 14:04:54 +00002175 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002176 }
Steve Naroff936c4362008-06-03 14:04:54 +00002177 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2178 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002179 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002180 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2181 lType.getAsString(), rType.getAsString(),
2182 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002183 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002184 return Context.IntTy;
2185 }
Steve Naroff936c4362008-06-03 14:04:54 +00002186 if (lType->isIntegerType() &&
2187 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002188 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002189 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2190 lType.getAsString(), rType.getAsString(),
2191 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002192 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002193 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002194 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002195 // Handle block pointers.
2196 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2197 if (!RHSIsNull)
2198 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2199 lType.getAsString(), rType.getAsString(),
2200 lex->getSourceRange(), rex->getSourceRange());
2201 ImpCastExprToType(rex, lType); // promote the integer to pointer
2202 return Context.IntTy;
2203 }
2204 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2205 if (!LHSIsNull)
2206 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2207 lType.getAsString(), rType.getAsString(),
2208 lex->getSourceRange(), rex->getSourceRange());
2209 ImpCastExprToType(lex, rType); // promote the integer to pointer
2210 return Context.IntTy;
2211 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00002212 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002213}
2214
Nate Begemanc5f0f652008-07-14 18:02:46 +00002215/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2216/// operates on extended vector types. Instead of producing an IntTy result,
2217/// like a scalar comparison, a vector comparison produces a vector of integer
2218/// types.
2219QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2220 SourceLocation loc,
2221 bool isRelational) {
2222 // Check to make sure we're operating on vectors of the same type and width,
2223 // Allowing one side to be a scalar of element type.
2224 QualType vType = CheckVectorOperands(loc, lex, rex);
2225 if (vType.isNull())
2226 return vType;
2227
2228 QualType lType = lex->getType();
2229 QualType rType = rex->getType();
2230
2231 // For non-floating point types, check for self-comparisons of the form
2232 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2233 // often indicate logic errors in the program.
2234 if (!lType->isFloatingType()) {
2235 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2236 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2237 if (DRL->getDecl() == DRR->getDecl())
2238 Diag(loc, diag::warn_selfcomparison);
2239 }
2240
2241 // Check for comparisons of floating point operands using != and ==.
2242 if (!isRelational && lType->isFloatingType()) {
2243 assert (rType->isFloatingType());
2244 CheckFloatComparison(loc,lex,rex);
2245 }
2246
2247 // Return the type for the comparison, which is the same as vector type for
2248 // integer vectors, or an integer type of identical size and number of
2249 // elements for floating point vectors.
2250 if (lType->isIntegerType())
2251 return lType;
2252
2253 const VectorType *VTy = lType->getAsVectorType();
2254
2255 // FIXME: need to deal with non-32b int / non-64b long long
2256 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2257 if (TypeSize == 32) {
2258 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2259 }
2260 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2261 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2262}
2263
Chris Lattner4b009652007-07-25 00:24:17 +00002264inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00002265 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002266{
2267 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2268 return CheckVectorOperands(loc, lex, rex);
2269
Steve Naroff8f708362007-08-24 19:07:16 +00002270 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002271
2272 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002273 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002274 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002275}
2276
2277inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
2278 Expr *&lex, Expr *&rex, SourceLocation loc)
2279{
2280 UsualUnaryConversions(lex);
2281 UsualUnaryConversions(rex);
2282
Eli Friedmanbea3f842008-05-13 20:16:47 +00002283 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002284 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002285 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002286}
2287
2288inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00002289 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00002290{
2291 QualType lhsType = lex->getType();
2292 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner25168a52008-07-26 21:30:36 +00002293 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002294
2295 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00002296 case Expr::MLV_Valid:
2297 break;
2298 case Expr::MLV_ConstQualified:
2299 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2300 return QualType();
2301 case Expr::MLV_ArrayType:
2302 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2303 lhsType.getAsString(), lex->getSourceRange());
2304 return QualType();
2305 case Expr::MLV_NotObjectType:
2306 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2307 lhsType.getAsString(), lex->getSourceRange());
2308 return QualType();
2309 case Expr::MLV_InvalidExpression:
2310 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2311 lex->getSourceRange());
2312 return QualType();
2313 case Expr::MLV_IncompleteType:
2314 case Expr::MLV_IncompleteVoidType:
2315 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2316 lhsType.getAsString(), lex->getSourceRange());
2317 return QualType();
2318 case Expr::MLV_DuplicateVectorComponents:
2319 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2320 lex->getSourceRange());
2321 return QualType();
Steve Naroff076d6cb2008-09-26 14:41:28 +00002322 case Expr::MLV_NotBlockQualified:
2323 Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2324 lex->getSourceRange());
2325 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002326 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002327
Chris Lattner005ed752008-01-04 18:04:52 +00002328 AssignConvertType ConvTy;
Chris Lattner34c85082008-08-21 18:04:13 +00002329 if (compoundType.isNull()) {
2330 // Simple assignment "x = y".
Chris Lattner005ed752008-01-04 18:04:52 +00002331 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner34c85082008-08-21 18:04:13 +00002332
2333 // If the RHS is a unary plus or minus, check to see if they = and + are
2334 // right next to each other. If so, the user may have typo'd "x =+ 4"
2335 // instead of "x += 4".
2336 Expr *RHSCheck = rex;
2337 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2338 RHSCheck = ICE->getSubExpr();
2339 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2340 if ((UO->getOpcode() == UnaryOperator::Plus ||
2341 UO->getOpcode() == UnaryOperator::Minus) &&
2342 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2343 // Only if the two operators are exactly adjacent.
2344 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2345 Diag(loc, diag::warn_not_compound_assign,
2346 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2347 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2348 }
2349 } else {
2350 // Compound assignment "x += y"
Chris Lattner005ed752008-01-04 18:04:52 +00002351 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner34c85082008-08-21 18:04:13 +00002352 }
Chris Lattner005ed752008-01-04 18:04:52 +00002353
2354 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2355 rex, "assigning"))
2356 return QualType();
2357
Chris Lattner4b009652007-07-25 00:24:17 +00002358 // C99 6.5.16p3: The type of an assignment expression is the type of the
2359 // left operand unless the left operand has qualified type, in which case
2360 // it is the unqualified version of the type of the left operand.
2361 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2362 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002363 // C++ 5.17p1: the type of the assignment expression is that of its left
2364 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00002365 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002366}
2367
2368inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2369 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00002370
2371 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2372 DefaultFunctionArrayConversion(rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002373 return rex->getType();
2374}
2375
2376/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2377/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2378QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2379 QualType resType = op->getType();
2380 assert(!resType.isNull() && "no type for increment/decrement expression");
2381
Steve Naroffd30e1932007-08-24 17:20:07 +00002382 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00002383 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002384 if (pt->getPointeeType()->isVoidType()) {
2385 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2386 } else if (!pt->getPointeeType()->isObjectType()) {
2387 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00002388 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2389 resType.getAsString(), op->getSourceRange());
2390 return QualType();
2391 }
Steve Naroffd30e1932007-08-24 17:20:07 +00002392 } else if (!resType->isRealType()) {
2393 if (resType->isComplexType())
2394 // C99 does not support ++/-- on complex types.
2395 Diag(OpLoc, diag::ext_integer_increment_complex,
2396 resType.getAsString(), op->getSourceRange());
2397 else {
2398 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2399 resType.getAsString(), op->getSourceRange());
2400 return QualType();
2401 }
Chris Lattner4b009652007-07-25 00:24:17 +00002402 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002403 // At this point, we know we have a real, complex or pointer type.
2404 // Now make sure the operand is a modifiable lvalue.
Chris Lattner25168a52008-07-26 21:30:36 +00002405 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002406 if (mlval != Expr::MLV_Valid) {
2407 // FIXME: emit a more precise diagnostic...
2408 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2409 op->getSourceRange());
2410 return QualType();
2411 }
2412 return resType;
2413}
2414
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002415/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002416/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002417/// where the declaration is needed for type checking. We only need to
2418/// handle cases when the expression references a function designator
2419/// or is an lvalue. Here are some examples:
2420/// - &(x) => x
2421/// - &*****f => f for f a function designator.
2422/// - &s.xx => s
2423/// - &s.zz[1].yy -> s, if zz is an array
2424/// - *(x + 1) -> x, if x is an array
2425/// - &"123"[2] -> 0
2426/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002427static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002428 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002429 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002430 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002431 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002432 // Fields cannot be declared with a 'register' storage class.
2433 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002434 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002435 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002436 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002437 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002438 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002439
Douglas Gregord2baafd2008-10-21 16:13:35 +00002440 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002441 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002442 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002443 return 0;
2444 else
2445 return VD;
2446 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002447 case Stmt::UnaryOperatorClass: {
2448 UnaryOperator *UO = cast<UnaryOperator>(E);
2449
2450 switch(UO->getOpcode()) {
2451 case UnaryOperator::Deref: {
2452 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002453 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2454 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2455 if (!VD || VD->getType()->isPointerType())
2456 return 0;
2457 return VD;
2458 }
2459 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002460 }
2461 case UnaryOperator::Real:
2462 case UnaryOperator::Imag:
2463 case UnaryOperator::Extension:
2464 return getPrimaryDecl(UO->getSubExpr());
2465 default:
2466 return 0;
2467 }
2468 }
2469 case Stmt::BinaryOperatorClass: {
2470 BinaryOperator *BO = cast<BinaryOperator>(E);
2471
2472 // Handle cases involving pointer arithmetic. The result of an
2473 // Assign or AddAssign is not an lvalue so they can be ignored.
2474
2475 // (x + n) or (n + x) => x
2476 if (BO->getOpcode() == BinaryOperator::Add) {
2477 if (BO->getLHS()->getType()->isPointerType()) {
2478 return getPrimaryDecl(BO->getLHS());
2479 } else if (BO->getRHS()->getType()->isPointerType()) {
2480 return getPrimaryDecl(BO->getRHS());
2481 }
2482 }
2483
2484 return 0;
2485 }
Chris Lattner4b009652007-07-25 00:24:17 +00002486 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002487 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002488 case Stmt::ImplicitCastExprClass:
2489 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002490 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002491 default:
2492 return 0;
2493 }
2494}
2495
2496/// CheckAddressOfOperand - The operand of & must be either a function
2497/// designator or an lvalue designating an object. If it is an lvalue, the
2498/// object cannot be declared with storage class register or be a bit field.
2499/// Note: The usual conversions are *not* applied to the operand of the &
2500/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2501QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002502 if (getLangOptions().C99) {
2503 // Implement C99-only parts of addressof rules.
2504 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2505 if (uOp->getOpcode() == UnaryOperator::Deref)
2506 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2507 // (assuming the deref expression is valid).
2508 return uOp->getSubExpr()->getType();
2509 }
2510 // Technically, there should be a check for array subscript
2511 // expressions here, but the result of one is always an lvalue anyway.
2512 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002513 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002514 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002515
2516 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002517 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2518 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002519 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2520 op->getSourceRange());
2521 return QualType();
2522 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002523 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2524 if (MemExpr->getMemberDecl()->isBitField()) {
2525 Diag(OpLoc, diag::err_typecheck_address_of,
2526 std::string("bit-field"), op->getSourceRange());
2527 return QualType();
2528 }
2529 // Check for Apple extension for accessing vector components.
2530 } else if (isa<ArraySubscriptExpr>(op) &&
2531 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2532 Diag(OpLoc, diag::err_typecheck_address_of,
2533 std::string("vector"), op->getSourceRange());
2534 return QualType();
2535 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002536 // We have an lvalue with a decl. Make sure the decl is not declared
2537 // with the register storage-class specifier.
2538 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2539 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002540 Diag(OpLoc, diag::err_typecheck_address_of,
2541 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002542 return QualType();
2543 }
2544 } else
2545 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002546 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002547
Chris Lattner4b009652007-07-25 00:24:17 +00002548 // If the operand has type "type", the result has type "pointer to type".
2549 return Context.getPointerType(op->getType());
2550}
2551
2552QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2553 UsualUnaryConversions(op);
2554 QualType qType = op->getType();
2555
Chris Lattner7931f4a2007-07-31 16:53:04 +00002556 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002557 // Note that per both C89 and C99, this is always legal, even
2558 // if ptype is an incomplete type or void.
2559 // It would be possible to warn about dereferencing a
2560 // void pointer, but it's completely well-defined,
2561 // and such a warning is unlikely to catch any mistakes.
2562 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002563 }
2564 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2565 qType.getAsString(), op->getSourceRange());
2566 return QualType();
2567}
2568
2569static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2570 tok::TokenKind Kind) {
2571 BinaryOperator::Opcode Opc;
2572 switch (Kind) {
2573 default: assert(0 && "Unknown binop!");
2574 case tok::star: Opc = BinaryOperator::Mul; break;
2575 case tok::slash: Opc = BinaryOperator::Div; break;
2576 case tok::percent: Opc = BinaryOperator::Rem; break;
2577 case tok::plus: Opc = BinaryOperator::Add; break;
2578 case tok::minus: Opc = BinaryOperator::Sub; break;
2579 case tok::lessless: Opc = BinaryOperator::Shl; break;
2580 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2581 case tok::lessequal: Opc = BinaryOperator::LE; break;
2582 case tok::less: Opc = BinaryOperator::LT; break;
2583 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2584 case tok::greater: Opc = BinaryOperator::GT; break;
2585 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2586 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2587 case tok::amp: Opc = BinaryOperator::And; break;
2588 case tok::caret: Opc = BinaryOperator::Xor; break;
2589 case tok::pipe: Opc = BinaryOperator::Or; break;
2590 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2591 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2592 case tok::equal: Opc = BinaryOperator::Assign; break;
2593 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2594 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2595 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2596 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2597 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2598 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2599 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2600 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2601 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2602 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2603 case tok::comma: Opc = BinaryOperator::Comma; break;
2604 }
2605 return Opc;
2606}
2607
2608static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2609 tok::TokenKind Kind) {
2610 UnaryOperator::Opcode Opc;
2611 switch (Kind) {
2612 default: assert(0 && "Unknown unary op!");
2613 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2614 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2615 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2616 case tok::star: Opc = UnaryOperator::Deref; break;
2617 case tok::plus: Opc = UnaryOperator::Plus; break;
2618 case tok::minus: Opc = UnaryOperator::Minus; break;
2619 case tok::tilde: Opc = UnaryOperator::Not; break;
2620 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2621 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2622 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2623 case tok::kw___real: Opc = UnaryOperator::Real; break;
2624 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2625 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2626 }
2627 return Opc;
2628}
2629
Douglas Gregord7f915e2008-11-06 23:29:22 +00002630/// CreateBuiltinBinOp - Creates a new built-in binary operation with
2631/// operator @p Opc at location @c TokLoc. This routine only supports
2632/// built-in operations; ActOnBinOp handles overloaded operators.
2633Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
2634 unsigned Op,
2635 Expr *lhs, Expr *rhs) {
2636 QualType ResultTy; // Result type of the binary operator.
2637 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2638 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
2639
2640 switch (Opc) {
2641 default:
2642 assert(0 && "Unknown binary expr!");
2643 case BinaryOperator::Assign:
2644 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
2645 break;
2646 case BinaryOperator::Mul:
2647 case BinaryOperator::Div:
2648 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
2649 break;
2650 case BinaryOperator::Rem:
2651 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
2652 break;
2653 case BinaryOperator::Add:
2654 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
2655 break;
2656 case BinaryOperator::Sub:
2657 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
2658 break;
2659 case BinaryOperator::Shl:
2660 case BinaryOperator::Shr:
2661 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
2662 break;
2663 case BinaryOperator::LE:
2664 case BinaryOperator::LT:
2665 case BinaryOperator::GE:
2666 case BinaryOperator::GT:
2667 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
2668 break;
2669 case BinaryOperator::EQ:
2670 case BinaryOperator::NE:
2671 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
2672 break;
2673 case BinaryOperator::And:
2674 case BinaryOperator::Xor:
2675 case BinaryOperator::Or:
2676 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
2677 break;
2678 case BinaryOperator::LAnd:
2679 case BinaryOperator::LOr:
2680 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
2681 break;
2682 case BinaryOperator::MulAssign:
2683 case BinaryOperator::DivAssign:
2684 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
2685 if (!CompTy.isNull())
2686 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2687 break;
2688 case BinaryOperator::RemAssign:
2689 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
2690 if (!CompTy.isNull())
2691 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2692 break;
2693 case BinaryOperator::AddAssign:
2694 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
2695 if (!CompTy.isNull())
2696 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2697 break;
2698 case BinaryOperator::SubAssign:
2699 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
2700 if (!CompTy.isNull())
2701 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2702 break;
2703 case BinaryOperator::ShlAssign:
2704 case BinaryOperator::ShrAssign:
2705 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
2706 if (!CompTy.isNull())
2707 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2708 break;
2709 case BinaryOperator::AndAssign:
2710 case BinaryOperator::XorAssign:
2711 case BinaryOperator::OrAssign:
2712 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
2713 if (!CompTy.isNull())
2714 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
2715 break;
2716 case BinaryOperator::Comma:
2717 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
2718 break;
2719 }
2720 if (ResultTy.isNull())
2721 return true;
2722 if (CompTy.isNull())
2723 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
2724 else
2725 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
2726}
2727
Chris Lattner4b009652007-07-25 00:24:17 +00002728// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00002729Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
2730 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002731 ExprTy *LHS, ExprTy *RHS) {
2732 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2733 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2734
Steve Naroff87d58b42007-09-16 03:34:24 +00002735 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2736 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002737
Douglas Gregord7f915e2008-11-06 23:29:22 +00002738 if (getLangOptions().CPlusPlus &&
2739 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
2740 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
2741 // C++ [over.binary]p1:
2742 // A binary operator shall be implemented either by a non-static
2743 // member function (9.3) with one parameter or by a non-member
2744 // function with two parameters. Thus, for any binary operator
2745 // @, x@y can be interpreted as either x.operator@(y) or
2746 // operator@(x,y). If both forms of the operator function have
2747 // been declared, the rules in 13.3.1.2 determines which, if
2748 // any, interpretation is used.
2749 OverloadCandidateSet CandidateSet;
2750
2751 // Determine which overloaded operator we're dealing with.
2752 static const OverloadedOperatorKind OverOps[] = {
2753 OO_Star, OO_Slash, OO_Percent,
2754 OO_Plus, OO_Minus,
2755 OO_LessLess, OO_GreaterGreater,
2756 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2757 OO_EqualEqual, OO_ExclaimEqual,
2758 OO_Amp,
2759 OO_Caret,
2760 OO_Pipe,
2761 OO_AmpAmp,
2762 OO_PipePipe,
2763 OO_Equal, OO_StarEqual,
2764 OO_SlashEqual, OO_PercentEqual,
2765 OO_PlusEqual, OO_MinusEqual,
2766 OO_LessLessEqual, OO_GreaterGreaterEqual,
2767 OO_AmpEqual, OO_CaretEqual,
2768 OO_PipeEqual,
2769 OO_Comma
2770 };
2771 OverloadedOperatorKind OverOp = OverOps[Opc];
2772
2773 // Lookup this operator.
2774 Decl *D = LookupDecl(&PP.getIdentifierTable().getOverloadedOperator(OverOp),
2775 Decl::IDNS_Ordinary, S);
2776
2777 // Add any overloaded operators we find to the overload set.
2778 Expr *Args[2] = { lhs, rhs };
2779 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
2780 AddOverloadCandidate(FD, Args, 2, CandidateSet);
2781 else if (OverloadedFunctionDecl *Ovl
2782 = dyn_cast_or_null<OverloadedFunctionDecl>(D))
2783 AddOverloadCandidates(Ovl, Args, 2, CandidateSet);
2784
2785 // FIXME: Add builtin overload candidates (C++ [over.built]).
2786
2787 // Perform overload resolution.
2788 OverloadCandidateSet::iterator Best;
2789 switch (BestViableFunction(CandidateSet, Best)) {
2790 case OR_Success: {
2791 // FIXME: We might find a built-in candidate here.
2792 FunctionDecl *FnDecl = Best->Function;
2793
2794 // Convert the arguments.
2795 // FIXME: Conversion will be different for member operators.
2796 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
2797 "passing") ||
2798 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
2799 "passing"))
2800 return true;
2801
2802 // Determine the result type
2803 QualType ResultTy
2804 = FnDecl->getType()->getAsFunctionType()->getResultType();
2805 ResultTy = ResultTy.getNonReferenceType();
2806
2807 // Build the actual expression node.
2808 // FIXME: We lose the fact that we have a function here!
2809 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
2810 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, ResultTy,
2811 TokLoc);
2812 else
2813 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
2814 }
2815
2816 case OR_No_Viable_Function:
2817 // No viable function; fall through to handling this as a
2818 // built-in operator.
2819 break;
2820
2821 case OR_Ambiguous:
2822 Diag(TokLoc,
2823 diag::err_ovl_ambiguous_oper,
2824 BinaryOperator::getOpcodeStr(Opc),
2825 lhs->getSourceRange(), rhs->getSourceRange());
2826 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2827 return true;
2828 }
2829
2830 // There was no viable overloaded operator; fall through.
2831 }
2832
Chris Lattner4b009652007-07-25 00:24:17 +00002833
Douglas Gregord7f915e2008-11-06 23:29:22 +00002834 // Build a built-in binary operation.
2835 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00002836}
2837
2838// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002839Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002840 ExprTy *input) {
2841 Expr *Input = (Expr*)input;
2842 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2843 QualType resultType;
2844 switch (Opc) {
2845 default:
2846 assert(0 && "Unimplemented unary expr!");
2847 case UnaryOperator::PreInc:
2848 case UnaryOperator::PreDec:
2849 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2850 break;
2851 case UnaryOperator::AddrOf:
2852 resultType = CheckAddressOfOperand(Input, OpLoc);
2853 break;
2854 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002855 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002856 resultType = CheckIndirectionOperand(Input, OpLoc);
2857 break;
2858 case UnaryOperator::Plus:
2859 case UnaryOperator::Minus:
2860 UsualUnaryConversions(Input);
2861 resultType = Input->getType();
2862 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2863 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2864 resultType.getAsString());
2865 break;
2866 case UnaryOperator::Not: // bitwise complement
2867 UsualUnaryConversions(Input);
2868 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002869 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2870 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2871 // C99 does not support '~' for complex conjugation.
2872 Diag(OpLoc, diag::ext_integer_complement_complex,
2873 resultType.getAsString(), Input->getSourceRange());
2874 else if (!resultType->isIntegerType())
2875 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2876 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002877 break;
2878 case UnaryOperator::LNot: // logical negation
2879 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2880 DefaultFunctionArrayConversion(Input);
2881 resultType = Input->getType();
2882 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2883 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2884 resultType.getAsString());
2885 // LNot always has type int. C99 6.5.3.3p5.
2886 resultType = Context.IntTy;
2887 break;
2888 case UnaryOperator::SizeOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002889 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2890 Input->getSourceRange(), true);
Chris Lattner4b009652007-07-25 00:24:17 +00002891 break;
2892 case UnaryOperator::AlignOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002893 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2894 Input->getSourceRange(), false);
Chris Lattner4b009652007-07-25 00:24:17 +00002895 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002896 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002897 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002898 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002899 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002900 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002901 resultType = Input->getType();
2902 break;
2903 }
2904 if (resultType.isNull())
2905 return true;
2906 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2907}
2908
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002909/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2910Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002911 SourceLocation LabLoc,
2912 IdentifierInfo *LabelII) {
2913 // Look up the record for this label identifier.
2914 LabelStmt *&LabelDecl = LabelMap[LabelII];
2915
Daniel Dunbar879788d2008-08-04 16:51:22 +00002916 // If we haven't seen this label yet, create a forward reference. It
2917 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00002918 if (LabelDecl == 0)
2919 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2920
2921 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002922 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2923 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002924}
2925
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002926Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002927 SourceLocation RPLoc) { // "({..})"
2928 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2929 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2930 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2931
2932 // FIXME: there are a variety of strange constraints to enforce here, for
2933 // example, it is not possible to goto into a stmt expression apparently.
2934 // More semantic analysis is needed.
2935
2936 // FIXME: the last statement in the compount stmt has its value used. We
2937 // should not warn about it being unused.
2938
2939 // If there are sub stmts in the compound stmt, take the type of the last one
2940 // as the type of the stmtexpr.
2941 QualType Ty = Context.VoidTy;
2942
Chris Lattner200964f2008-07-26 19:51:01 +00002943 if (!Compound->body_empty()) {
2944 Stmt *LastStmt = Compound->body_back();
2945 // If LastStmt is a label, skip down through into the body.
2946 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2947 LastStmt = Label->getSubStmt();
2948
2949 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00002950 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00002951 }
Chris Lattner4b009652007-07-25 00:24:17 +00002952
2953 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2954}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002955
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002956Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002957 SourceLocation TypeLoc,
2958 TypeTy *argty,
2959 OffsetOfComponent *CompPtr,
2960 unsigned NumComponents,
2961 SourceLocation RPLoc) {
2962 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2963 assert(!ArgTy.isNull() && "Missing type argument!");
2964
2965 // We must have at least one component that refers to the type, and the first
2966 // one is known to be a field designator. Verify that the ArgTy represents
2967 // a struct/union/class.
2968 if (!ArgTy->isRecordType())
2969 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2970
2971 // Otherwise, create a compound literal expression as the base, and
2972 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002973 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002974
Chris Lattnerb37522e2007-08-31 21:49:13 +00002975 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2976 // GCC extension, diagnose them.
2977 if (NumComponents != 1)
2978 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2979 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2980
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002981 for (unsigned i = 0; i != NumComponents; ++i) {
2982 const OffsetOfComponent &OC = CompPtr[i];
2983 if (OC.isBrackets) {
2984 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00002985 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002986 if (!AT) {
2987 delete Res;
2988 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2989 Res->getType().getAsString());
2990 }
2991
Chris Lattner2af6a802007-08-30 17:59:59 +00002992 // FIXME: C++: Verify that operator[] isn't overloaded.
2993
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002994 // C99 6.5.2.1p1
2995 Expr *Idx = static_cast<Expr*>(OC.U.E);
2996 if (!Idx->getType()->isIntegerType())
2997 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2998 Idx->getSourceRange());
2999
3000 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3001 continue;
3002 }
3003
3004 const RecordType *RC = Res->getType()->getAsRecordType();
3005 if (!RC) {
3006 delete Res;
3007 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
3008 Res->getType().getAsString());
3009 }
3010
3011 // Get the decl corresponding to this.
3012 RecordDecl *RD = RC->getDecl();
3013 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
3014 if (!MemberDecl)
3015 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
3016 OC.U.IdentInfo->getName(),
3017 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00003018
3019 // FIXME: C++: Verify that MemberDecl isn't a static field.
3020 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003021 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3022 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003023 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3024 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003025 }
3026
3027 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3028 BuiltinLoc);
3029}
3030
3031
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003032Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003033 TypeTy *arg1, TypeTy *arg2,
3034 SourceLocation RPLoc) {
3035 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3036 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3037
3038 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3039
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003040 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003041}
3042
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003043Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003044 ExprTy *expr1, ExprTy *expr2,
3045 SourceLocation RPLoc) {
3046 Expr *CondExpr = static_cast<Expr*>(cond);
3047 Expr *LHSExpr = static_cast<Expr*>(expr1);
3048 Expr *RHSExpr = static_cast<Expr*>(expr2);
3049
3050 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3051
3052 // The conditional expression is required to be a constant expression.
3053 llvm::APSInt condEval(32);
3054 SourceLocation ExpLoc;
3055 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
3056 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
3057 CondExpr->getSourceRange());
3058
3059 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3060 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3061 RHSExpr->getType();
3062 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3063}
3064
Steve Naroff52a81c02008-09-03 18:15:37 +00003065//===----------------------------------------------------------------------===//
3066// Clang Extensions.
3067//===----------------------------------------------------------------------===//
3068
3069/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003070void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003071 // Analyze block parameters.
3072 BlockSemaInfo *BSI = new BlockSemaInfo();
3073
3074 // Add BSI to CurBlock.
3075 BSI->PrevBlockInfo = CurBlock;
3076 CurBlock = BSI;
3077
3078 BSI->ReturnType = 0;
3079 BSI->TheScope = BlockScope;
3080
Steve Naroff52059382008-10-10 01:28:17 +00003081 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
3082 PushDeclContext(BSI->TheDecl);
3083}
3084
3085void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003086 // Analyze arguments to block.
3087 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3088 "Not a function declarator!");
3089 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3090
Steve Naroff52059382008-10-10 01:28:17 +00003091 CurBlock->hasPrototype = FTI.hasPrototype;
3092 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003093
3094 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3095 // no arguments, not a function that takes a single void argument.
3096 if (FTI.hasPrototype &&
3097 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3098 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3099 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3100 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003101 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003102 } else if (FTI.hasPrototype) {
3103 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003104 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3105 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003106 }
Steve Naroff52059382008-10-10 01:28:17 +00003107 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3108
3109 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3110 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3111 // If this has an identifier, add it to the scope stack.
3112 if ((*AI)->getIdentifier())
3113 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003114}
3115
3116/// ActOnBlockError - If there is an error parsing a block, this callback
3117/// is invoked to pop the information about the block from the action impl.
3118void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3119 // Ensure that CurBlock is deleted.
3120 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3121
3122 // Pop off CurBlock, handle nested blocks.
3123 CurBlock = CurBlock->PrevBlockInfo;
3124
3125 // FIXME: Delete the ParmVarDecl objects as well???
3126
3127}
3128
3129/// ActOnBlockStmtExpr - This is called when the body of a block statement
3130/// literal was successfully completed. ^(int x){...}
3131Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3132 Scope *CurScope) {
3133 // Ensure that CurBlock is deleted.
3134 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3135 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3136
Steve Naroff52059382008-10-10 01:28:17 +00003137 PopDeclContext();
3138
Steve Naroff52a81c02008-09-03 18:15:37 +00003139 // Pop off CurBlock, handle nested blocks.
3140 CurBlock = CurBlock->PrevBlockInfo;
3141
3142 QualType RetTy = Context.VoidTy;
3143 if (BSI->ReturnType)
3144 RetTy = QualType(BSI->ReturnType, 0);
3145
3146 llvm::SmallVector<QualType, 8> ArgTypes;
3147 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3148 ArgTypes.push_back(BSI->Params[i]->getType());
3149
3150 QualType BlockTy;
3151 if (!BSI->hasPrototype)
3152 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3153 else
3154 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003155 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003156
3157 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003158
Steve Naroff95029d92008-10-08 18:44:00 +00003159 BSI->TheDecl->setBody(Body.take());
3160 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003161}
3162
Nate Begemanbd881ef2008-01-30 20:50:20 +00003163/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003164/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003165/// The number of arguments has already been validated to match the number of
3166/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003167static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3168 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003169 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003170 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003171 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3172 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003173
3174 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003175 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003176 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003177 return true;
3178}
3179
3180Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3181 SourceLocation *CommaLocs,
3182 SourceLocation BuiltinLoc,
3183 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003184 // __builtin_overload requires at least 2 arguments
3185 if (NumArgs < 2)
3186 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3187 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003188
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003189 // The first argument is required to be a constant expression. It tells us
3190 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003191 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003192 Expr *NParamsExpr = Args[0];
3193 llvm::APSInt constEval(32);
3194 SourceLocation ExpLoc;
3195 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
3196 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3197 NParamsExpr->getSourceRange());
3198
3199 // Verify that the number of parameters is > 0
3200 unsigned NumParams = constEval.getZExtValue();
3201 if (NumParams == 0)
3202 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3203 NParamsExpr->getSourceRange());
3204 // Verify that we have at least 1 + NumParams arguments to the builtin.
3205 if ((NumParams + 1) > NumArgs)
3206 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3207 SourceRange(BuiltinLoc, RParenLoc));
3208
3209 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003210 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003211 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003212 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3213 // UsualUnaryConversions will convert the function DeclRefExpr into a
3214 // pointer to function.
3215 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003216 const FunctionTypeProto *FnType = 0;
3217 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3218 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003219
3220 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3221 // parameters, and the number of parameters must match the value passed to
3222 // the builtin.
3223 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00003224 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
3225 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003226
3227 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003228 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003229 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003230 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003231 if (OE)
3232 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
3233 OE->getFn()->getSourceRange());
3234 // Remember our match, and continue processing the remaining arguments
3235 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003236 OE = new OverloadExpr(Args, NumArgs, i,
3237 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003238 BuiltinLoc, RParenLoc);
3239 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003240 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003241 // Return the newly created OverloadExpr node, if we succeded in matching
3242 // exactly one of the candidate functions.
3243 if (OE)
3244 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003245
3246 // If we didn't find a matching function Expr in the __builtin_overload list
3247 // the return an error.
3248 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003249 for (unsigned i = 0; i != NumParams; ++i) {
3250 if (i != 0) typeNames += ", ";
3251 typeNames += Args[i+1]->getType().getAsString();
3252 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003253
3254 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3255 SourceRange(BuiltinLoc, RParenLoc));
3256}
3257
Anders Carlsson36760332007-10-15 20:28:48 +00003258Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3259 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003260 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003261 Expr *E = static_cast<Expr*>(expr);
3262 QualType T = QualType::getFromOpaquePtr(type);
3263
3264 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003265
3266 // Get the va_list type
3267 QualType VaListType = Context.getBuiltinVaListType();
3268 // Deal with implicit array decay; for example, on x86-64,
3269 // va_list is an array, but it's supposed to decay to
3270 // a pointer for va_arg.
3271 if (VaListType->isArrayType())
3272 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003273 // Make sure the input expression also decays appropriately.
3274 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003275
3276 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003277 return Diag(E->getLocStart(),
3278 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3279 E->getType().getAsString(),
3280 E->getSourceRange());
3281
3282 // FIXME: Warn if a non-POD type is passed in.
3283
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003284 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003285}
3286
Chris Lattner005ed752008-01-04 18:04:52 +00003287bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3288 SourceLocation Loc,
3289 QualType DstType, QualType SrcType,
3290 Expr *SrcExpr, const char *Flavor) {
3291 // Decode the result (notice that AST's are still created for extensions).
3292 bool isInvalid = false;
3293 unsigned DiagKind;
3294 switch (ConvTy) {
3295 default: assert(0 && "Unknown conversion type");
3296 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003297 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003298 DiagKind = diag::ext_typecheck_convert_pointer_int;
3299 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003300 case IntToPointer:
3301 DiagKind = diag::ext_typecheck_convert_int_pointer;
3302 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003303 case IncompatiblePointer:
3304 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3305 break;
3306 case FunctionVoidPointer:
3307 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3308 break;
3309 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003310 // If the qualifiers lost were because we were applying the
3311 // (deprecated) C++ conversion from a string literal to a char*
3312 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3313 // Ideally, this check would be performed in
3314 // CheckPointerTypesForAssignment. However, that would require a
3315 // bit of refactoring (so that the second argument is an
3316 // expression, rather than a type), which should be done as part
3317 // of a larger effort to fix CheckPointerTypesForAssignment for
3318 // C++ semantics.
3319 if (getLangOptions().CPlusPlus &&
3320 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3321 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003322 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3323 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003324 case IntToBlockPointer:
3325 DiagKind = diag::err_int_to_block_pointer;
3326 break;
3327 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003328 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003329 break;
3330 case BlockVoidPointer:
3331 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3332 break;
Steve Naroff19608432008-10-14 22:18:38 +00003333 case IncompatibleObjCQualifiedId:
3334 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3335 // it can give a more specific diagnostic.
3336 DiagKind = diag::warn_incompatible_qualified_id;
3337 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003338 case Incompatible:
3339 DiagKind = diag::err_typecheck_convert_incompatible;
3340 isInvalid = true;
3341 break;
3342 }
3343
3344 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3345 SrcExpr->getSourceRange());
3346 return isInvalid;
3347}