blob: 831765376b6a0f91a7f91adf30b3d54cafecc940 [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,
340 bool HasTrailingLParen) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000341 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroff6384a012008-04-02 14:35:35 +0000342 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000343
344 // If this reference is in an Objective-C method, then ivar lookup happens as
345 // well.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000346 if (getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000347 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000348 // There are two cases to handle here. 1) scoped lookup could have failed,
349 // in which case we should look for an ivar. 2) scoped lookup could have
350 // found a decl, but that decl is outside the current method (i.e. a global
351 // variable). In these two cases, we do a lookup for an ivar with this
352 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000353 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000354 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattnered94f762008-07-21 04:44:44 +0000355 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000356 // FIXME: This should use a new expr for a direct reference, don't turn
357 // this into Self->ivar, just return a BareIVarExpr or something.
358 IdentifierInfo &II = Context.Idents.get("self");
359 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
360 return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
361 static_cast<Expr*>(SelfExpr.Val), true, true);
362 }
363 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000364 // Needed to implement property "super.method" notation.
Daniel Dunbar4837ae72008-08-14 22:04:54 +0000365 if (SD == 0 && &II == SuperID) {
Steve Naroff6f786252008-06-02 23:03:37 +0000366 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000367 getCurMethodDecl()->getClassInterface()));
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000368 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroff6f786252008-06-02 23:03:37 +0000369 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000370 }
Chris Lattner4b009652007-07-25 00:24:17 +0000371 if (D == 0) {
372 // Otherwise, this could be an implicitly declared function reference (legal
373 // in C90, extension in C99).
374 if (HasTrailingLParen &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000375 !getLangOptions().CPlusPlus) // Not in C++.
Chris Lattner4b009652007-07-25 00:24:17 +0000376 D = ImplicitlyDefineFunction(Loc, II, S);
377 else {
378 // If this name wasn't predeclared and if this is not a function call,
379 // diagnose the problem.
380 return Diag(Loc, diag::err_undeclared_var_use, II.getName());
381 }
382 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000383
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000384 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
385 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
386 if (MD->isStatic())
387 // "invalid use of member 'x' in static member function"
388 return Diag(Loc, diag::err_invalid_member_use_in_static_method,
389 FD->getName());
390 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
391 // "invalid use of nonstatic data member 'x'"
392 return Diag(Loc, diag::err_invalid_non_static_member_use,
393 FD->getName());
394
395 if (FD->isInvalidDecl())
396 return true;
397
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +0000398 // FIXME: Handle 'mutable'.
399 return new DeclRefExpr(FD,
400 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000401 }
402
403 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
404 }
Chris Lattner4b009652007-07-25 00:24:17 +0000405 if (isa<TypedefDecl>(D))
406 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremenek42730c52008-01-07 19:49:32 +0000407 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian3102df92007-12-05 18:16:33 +0000408 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000409 if (isa<NamespaceDecl>(D))
410 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Chris Lattner4b009652007-07-25 00:24:17 +0000411
Steve Naroffd6163f32008-09-05 22:11:13 +0000412 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000413 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
414 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
415
Steve Naroffd6163f32008-09-05 22:11:13 +0000416 ValueDecl *VD = cast<ValueDecl>(D);
417
418 // check if referencing an identifier with __attribute__((deprecated)).
419 if (VD->getAttr<DeprecatedAttr>())
420 Diag(Loc, diag::warn_deprecated, VD->getName());
421
422 // Only create DeclRefExpr's for valid Decl's.
423 if (VD->isInvalidDecl())
424 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000425
426 // If the identifier reference is inside a block, and it refers to a value
427 // that is outside the block, create a BlockDeclRefExpr instead of a
428 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
429 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000430 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000431 // We do not do this for things like enum constants, global variables, etc,
432 // as they do not get snapshotted.
433 //
434 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000435 // The BlocksAttr indicates the variable is bound by-reference.
436 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000437 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
438 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000439
440 // Variable will be bound by-copy, make it const within the closure.
441 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000442 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
443 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000444 }
445 // If this reference is not in a block or if the referenced variable is
446 // within the block, create a normal DeclRefExpr.
Douglas Gregor3fb675a2008-10-22 04:14:44 +0000447 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Chris Lattner4b009652007-07-25 00:24:17 +0000448}
449
Chris Lattner69909292008-08-10 01:53:14 +0000450Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000451 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000452 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000453
454 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000455 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000456 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
457 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
458 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000459 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000460
461 // Verify that this is in a function context.
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000462 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000463 return Diag(Loc, diag::err_predef_outside_function);
Chris Lattner4b009652007-07-25 00:24:17 +0000464
Chris Lattner7e637512008-01-12 08:14:25 +0000465 // Pre-defined identifiers are of type char[x], where x is the length of the
466 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000467 unsigned Length;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000468 if (getCurFunctionDecl())
469 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000470 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000471 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000472
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000473 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000474 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000475 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000476 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000477}
478
Steve Naroff87d58b42007-09-16 03:34:24 +0000479Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000480 llvm::SmallString<16> CharBuffer;
481 CharBuffer.resize(Tok.getLength());
482 const char *ThisTokBegin = &CharBuffer[0];
483 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
484
485 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
486 Tok.getLocation(), PP);
487 if (Literal.hadError())
488 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000489
490 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
491
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000492 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
493 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000494}
495
Steve Naroff87d58b42007-09-16 03:34:24 +0000496Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000497 // fast path for a single digit (which is quite common). A single digit
498 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
499 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000500 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000501
Chris Lattner8cd0e932008-03-05 18:54:05 +0000502 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000503 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000504 Context.IntTy,
505 Tok.getLocation()));
506 }
507 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000508 // Add padding so that NumericLiteralParser can overread by one character.
509 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000510 const char *ThisTokBegin = &IntegerBuffer[0];
511
512 // Get the spelling of the token, which eliminates trigraphs, etc.
513 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000514
Chris Lattner4b009652007-07-25 00:24:17 +0000515 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
516 Tok.getLocation(), PP);
517 if (Literal.hadError)
518 return ExprResult(true);
519
Chris Lattner1de66eb2007-08-26 03:42:43 +0000520 Expr *Res;
521
522 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000523 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000524 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000525 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000526 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000527 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000528 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000529 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000530
531 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
532
Ted Kremenekddedbe22007-11-29 00:56:49 +0000533 // isExact will be set by GetFloatValue().
534 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000535 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000536 Ty, Tok.getLocation());
537
Chris Lattner1de66eb2007-08-26 03:42:43 +0000538 } else if (!Literal.isIntegerLiteral()) {
539 return ExprResult(true);
540 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000541 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000542
Neil Booth7421e9c2007-08-29 22:00:19 +0000543 // long long is a C99 feature.
544 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000545 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000546 Diag(Tok.getLocation(), diag::ext_longlong);
547
Chris Lattner4b009652007-07-25 00:24:17 +0000548 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000549 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000550
551 if (Literal.GetIntegerValue(ResultVal)) {
552 // If this value didn't fit into uintmax_t, warn and force to ull.
553 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000554 Ty = Context.UnsignedLongLongTy;
555 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000556 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000557 } else {
558 // If this value fits into a ULL, try to figure out what else it fits into
559 // according to the rules of C99 6.4.4.1p5.
560
561 // Octal, Hexadecimal, and integers with a U suffix are allowed to
562 // be an unsigned int.
563 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
564
565 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000566 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000567 if (!Literal.isLong && !Literal.isLongLong) {
568 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000569 unsigned IntSize = Context.Target.getIntWidth();
570
Chris Lattner4b009652007-07-25 00:24:17 +0000571 // Does it fit in a unsigned int?
572 if (ResultVal.isIntN(IntSize)) {
573 // Does it fit in a signed int?
574 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000575 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000576 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000577 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000578 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000579 }
Chris Lattner4b009652007-07-25 00:24:17 +0000580 }
581
582 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000583 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000584 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000585
586 // Does it fit in a unsigned long?
587 if (ResultVal.isIntN(LongSize)) {
588 // Does it fit in a signed long?
589 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000590 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000591 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000592 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000593 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000594 }
Chris Lattner4b009652007-07-25 00:24:17 +0000595 }
596
597 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000598 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000599 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000600
601 // Does it fit in a unsigned long long?
602 if (ResultVal.isIntN(LongLongSize)) {
603 // Does it fit in a signed long long?
604 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000605 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000606 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000607 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000608 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000609 }
610 }
611
612 // If we still couldn't decide a type, we probably have something that
613 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000614 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000615 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000616 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000617 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000618 }
Chris Lattnere4068872008-05-09 05:59:00 +0000619
620 if (ResultVal.getBitWidth() != Width)
621 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000622 }
623
Chris Lattner48d7f382008-04-02 04:24:33 +0000624 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000625 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000626
627 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
628 if (Literal.isImaginary)
629 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
630
631 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000632}
633
Steve Naroff87d58b42007-09-16 03:34:24 +0000634Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000635 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000636 Expr *E = (Expr *)Val;
637 assert((E != 0) && "ActOnParenExpr() missing expr");
638 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000639}
640
641/// The UsualUnaryConversions() function is *not* called by this routine.
642/// See C99 6.3.2.1p[2-4] for more details.
643QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Chris Lattnerf814d882008-07-25 21:45:37 +0000644 SourceLocation OpLoc,
645 const SourceRange &ExprRange,
646 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000647 // C99 6.5.3.4p1:
648 if (isa<FunctionType>(exprType) && isSizeof)
649 // alignof(function) is allowed.
Chris Lattnerf814d882008-07-25 21:45:37 +0000650 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000651 else if (exprType->isVoidType())
Chris Lattnerf814d882008-07-25 21:45:37 +0000652 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
653 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000654 else if (exprType->isIncompleteType()) {
655 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
656 diag::err_alignof_incomplete_type,
Chris Lattnerf814d882008-07-25 21:45:37 +0000657 exprType.getAsString(), ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +0000658 return QualType(); // error
659 }
660 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
661 return Context.getSizeType();
662}
663
664Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000665ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Chris Lattner4b009652007-07-25 00:24:17 +0000666 SourceLocation LPLoc, TypeTy *Ty,
667 SourceLocation RPLoc) {
668 // If error parsing type, ignore.
669 if (Ty == 0) return true;
670
671 // Verify that this is a valid expression.
672 QualType ArgTy = QualType::getFromOpaquePtr(Ty);
673
Chris Lattnerf814d882008-07-25 21:45:37 +0000674 QualType resultType =
675 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Chris Lattner4b009652007-07-25 00:24:17 +0000676
677 if (resultType.isNull())
678 return true;
679 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
680}
681
Chris Lattner5110ad52007-08-24 21:41:10 +0000682QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000683 DefaultFunctionArrayConversion(V);
684
Chris Lattnera16e42d2007-08-26 05:39:26 +0000685 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000686 if (const ComplexType *CT = V->getType()->getAsComplexType())
687 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000688
689 // Otherwise they pass through real integer and floating point types here.
690 if (V->getType()->isArithmeticType())
691 return V->getType();
692
693 // Reject anything else.
694 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
695 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000696}
697
698
Chris Lattner4b009652007-07-25 00:24:17 +0000699
Steve Naroff87d58b42007-09-16 03:34:24 +0000700Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000701 tok::TokenKind Kind,
702 ExprTy *Input) {
703 UnaryOperator::Opcode Opc;
704 switch (Kind) {
705 default: assert(0 && "Unknown unary op!");
706 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
707 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
708 }
709 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
710 if (result.isNull())
711 return true;
712 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
713}
714
715Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000716ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000717 ExprTy *Idx, SourceLocation RLoc) {
718 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
719
720 // Perform default conversions.
721 DefaultFunctionArrayConversion(LHSExp);
722 DefaultFunctionArrayConversion(RHSExp);
723
724 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
725
726 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +0000727 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +0000728 // in the subscript position. As a result, we need to derive the array base
729 // and index from the expression types.
730 Expr *BaseExpr, *IndexExpr;
731 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +0000732 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000733 BaseExpr = LHSExp;
734 IndexExpr = RHSExp;
735 // FIXME: need to deal with const...
736 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +0000737 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000738 // Handle the uncommon case of "123[Ptr]".
739 BaseExpr = RHSExp;
740 IndexExpr = LHSExp;
741 // FIXME: need to deal with const...
742 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +0000743 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
744 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +0000745 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +0000746
747 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +0000748 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
749 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begemanaf6ed502008-04-18 23:10:10 +0000750 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff89345522007-08-03 22:40:33 +0000751 SourceRange(LLoc, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +0000752 // FIXME: need to deal with const...
753 ResultType = VTy->getElementType();
754 } else {
755 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
756 RHSExp->getSourceRange());
757 }
758 // C99 6.5.2.1p1
759 if (!IndexExpr->getType()->isIntegerType())
760 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
761 IndexExpr->getSourceRange());
762
763 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
764 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +0000765 // void (*)(int)) and pointers to incomplete types. Functions are not
766 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +0000767 if (!ResultType->isObjectType())
768 return Diag(BaseExpr->getLocStart(),
769 diag::err_typecheck_subscript_not_object,
770 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
771
772 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
773}
774
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000775QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +0000776CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000777 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000778 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +0000779
780 // This flag determines whether or not the component is to be treated as a
781 // special name, or a regular GLSL-style component access.
782 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000783
784 // The vector accessor can't exceed the number of elements.
785 const char *compStr = CompName.getName();
786 if (strlen(compStr) > vecType->getNumElements()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +0000787 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000788 baseType.getAsString(), SourceRange(CompLoc));
789 return QualType();
790 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000791
792 // Check that we've found one of the special components, or that the component
793 // names must come from the same set.
794 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
795 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
796 SpecialComponent = true;
797 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +0000798 do
799 compStr++;
800 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
801 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
802 do
803 compStr++;
804 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
805 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
806 do
807 compStr++;
808 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
809 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000810
Nate Begemanc8e51f82008-05-09 06:41:27 +0000811 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000812 // We didn't get to the end of the string. This means the component names
813 // didn't come from the same set *or* we encountered an illegal name.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000814 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000815 std::string(compStr,compStr+1), SourceRange(CompLoc));
816 return QualType();
817 }
818 // Each component accessor can't exceed the vector type.
819 compStr = CompName.getName();
820 while (*compStr) {
821 if (vecType->isAccessorWithinNumElements(*compStr))
822 compStr++;
823 else
824 break;
825 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000826 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000827 // We didn't get to the end of the string. This means a component accessor
828 // exceeds the number of elements in the vector.
Nate Begemanaf6ed502008-04-18 23:10:10 +0000829 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000830 baseType.getAsString(), SourceRange(CompLoc));
831 return QualType();
832 }
Nate Begemanc8e51f82008-05-09 06:41:27 +0000833
834 // If we have a special component name, verify that the current vector length
835 // is an even number, since all special component names return exactly half
836 // the elements.
837 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Daniel Dunbar45a91802008-09-30 17:22:47 +0000838 Diag(OpLoc, diag::err_ext_vector_component_requires_even,
839 baseType.getAsString(), SourceRange(CompLoc));
Nate Begemanc8e51f82008-05-09 06:41:27 +0000840 return QualType();
841 }
842
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000843 // The component accessor looks fine - now we need to compute the actual type.
844 // The vector type is implied by the component accessor. For example,
845 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +0000846 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
847 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
848 : strlen(CompName.getName());
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000849 if (CompSize == 1)
850 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +0000851
Nate Begemanaf6ed502008-04-18 23:10:10 +0000852 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +0000853 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +0000854 // diagostics look bad. We want extended vector types to appear built-in.
855 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
856 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
857 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +0000858 }
859 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000860}
861
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000862/// constructSetterName - Return the setter name for the given
863/// identifier, i.e. "set" + Name where the initial character of Name
864/// has been capitalized.
865// FIXME: Merge with same routine in Parser. But where should this
866// live?
867static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
868 const IdentifierInfo *Name) {
869 unsigned N = Name->getLength();
870 char *SelectorName = new char[3 + N];
871 memcpy(SelectorName, "set", 3);
872 memcpy(&SelectorName[3], Name->getName(), N);
873 SelectorName[3] = toupper(SelectorName[3]);
874
875 IdentifierInfo *Setter =
876 &Idents.get(SelectorName, &SelectorName[3 + N]);
877 delete[] SelectorName;
878 return Setter;
879}
880
Chris Lattner4b009652007-07-25 00:24:17 +0000881Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +0000882ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000883 tok::TokenKind OpKind, SourceLocation MemberLoc,
884 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000885 Expr *BaseExpr = static_cast<Expr *>(Base);
886 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +0000887
888 // Perform default conversions.
889 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +0000890
Steve Naroff2cb66382007-07-26 03:11:44 +0000891 QualType BaseType = BaseExpr->getType();
892 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +0000893
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000894 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
895 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +0000896 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +0000897 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +0000898 BaseType = PT->getPointeeType();
899 else
Chris Lattner7d5a8762008-07-21 05:35:34 +0000900 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
901 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000902 }
Chris Lattnera57cf472008-07-21 04:28:12 +0000903
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000904 // Handle field access to simple records. This also handles access to fields
905 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +0000906 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +0000907 RecordDecl *RDecl = RTy->getDecl();
908 if (RTy->isIncompleteType())
909 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
910 BaseExpr->getSourceRange());
911 // The record definition is complete, now make sure the member is valid.
Steve Naroff1b8a46c2007-07-27 22:15:19 +0000912 FieldDecl *MemberDecl = RDecl->getMember(&Member);
913 if (!MemberDecl)
Chris Lattner7d5a8762008-07-21 05:35:34 +0000914 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
915 BaseExpr->getSourceRange());
Eli Friedman76b49832008-02-06 22:48:16 +0000916
917 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedmanaedabcf2008-02-07 05:24:51 +0000918 // FIXME: Handle address space modifiers
Eli Friedman76b49832008-02-06 22:48:16 +0000919 QualType MemberType = MemberDecl->getType();
920 unsigned combinedQualifiers =
Chris Lattner35fef522008-02-20 20:55:12 +0000921 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman76b49832008-02-06 22:48:16 +0000922 MemberType = MemberType.getQualifiedType(combinedQualifiers);
923
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000924 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman76b49832008-02-06 22:48:16 +0000925 MemberLoc, MemberType);
Chris Lattnera57cf472008-07-21 04:28:12 +0000926 }
927
Chris Lattnere9d71612008-07-21 04:59:05 +0000928 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
929 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +0000930 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
931 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian4af72492007-11-12 22:29:28 +0000932 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnera57cf472008-07-21 04:28:12 +0000933 OpKind == tok::arrow);
Chris Lattner7d5a8762008-07-21 05:35:34 +0000934 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner52292be2008-07-21 04:42:08 +0000935 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner7d5a8762008-07-21 05:35:34 +0000936 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +0000937 }
938
Chris Lattnere9d71612008-07-21 04:59:05 +0000939 // Handle Objective-C property access, which is "Obj.property" where Obj is a
940 // pointer to a (potentially qualified) interface type.
941 const PointerType *PTy;
942 const ObjCInterfaceType *IFTy;
943 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
944 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
945 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +0000946
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000947 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +0000948 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
949 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
950
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000951 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +0000952 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
953 E = IFTy->qual_end(); I != E; ++I)
954 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
955 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000956
957 // If that failed, look for an "implicit" property by seeing if the nullary
958 // selector is implemented.
959
960 // FIXME: The logic for looking up nullary and unary selectors should be
961 // shared with the code in ActOnInstanceMessage.
962
963 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
964 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
965
966 // If this reference is in an @implementation, check for 'private' methods.
967 if (!Getter)
968 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
969 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
970 if (ObjCImplementationDecl *ImpDecl =
971 ObjCImplementations[ClassDecl->getIdentifier()])
972 Getter = ImpDecl->getInstanceMethod(Sel);
973
Steve Naroff04151f32008-10-22 19:16:27 +0000974 // Look through local category implementations associated with the class.
975 if (!Getter) {
976 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
977 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
978 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
979 }
980 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +0000981 if (Getter) {
982 // If we found a getter then this may be a valid dot-reference, we
983 // need to also look for the matching setter.
984 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
985 &Member);
986 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
987 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
988
989 if (!Setter) {
990 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
991 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
992 if (ObjCImplementationDecl *ImpDecl =
993 ObjCImplementations[ClassDecl->getIdentifier()])
994 Setter = ImpDecl->getInstanceMethod(SetterSel);
995 }
996
997 // FIXME: There are some issues here. First, we are not
998 // diagnosing accesses to read-only properties because we do not
999 // know if this is a getter or setter yet. Second, we are
1000 // checking that the type of the setter matches the type we
1001 // expect.
1002 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
1003 MemberLoc, BaseExpr);
1004 }
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001005 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001006 // Handle properties on qualified "id" protocols.
1007 const ObjCQualifiedIdType *QIdTy;
1008 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1009 // Check protocols on qualified interfaces.
1010 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1011 E = QIdTy->qual_end(); I != E; ++I)
1012 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1013 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1014 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001015 // Handle 'field access' to vectors, such as 'V.xx'.
1016 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1017 // Component access limited to variables (reject vec4.rg.g).
1018 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1019 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner7d5a8762008-07-21 05:35:34 +00001020 return Diag(MemberLoc, diag::err_ext_vector_component_access,
1021 BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001022 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1023 if (ret.isNull())
1024 return true;
1025 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1026 }
1027
Chris Lattner7d5a8762008-07-21 05:35:34 +00001028 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1029 BaseType.getAsString(), BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001030}
1031
Steve Naroff87d58b42007-09-16 03:34:24 +00001032/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001033/// This provides the location of the left/right parens and a list of comma
1034/// locations.
1035Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001036ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001037 ExprTy **args, unsigned NumArgs,
Chris Lattner4b009652007-07-25 00:24:17 +00001038 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1039 Expr *Fn = static_cast<Expr *>(fn);
1040 Expr **Args = reinterpret_cast<Expr**>(args);
1041 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001042 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001043 OverloadedFunctionDecl *Ovl = NULL;
1044
1045 // If we're directly calling a function or a set of overloaded
1046 // functions, get the appropriate declaration.
1047 {
1048 DeclRefExpr *DRExpr = NULL;
1049 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1050 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1051 else
1052 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1053
1054 if (DRExpr) {
1055 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1056 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1057 }
1058 }
1059
1060 // If we have a set of overloaded functions, perform overload
1061 // resolution to pick the function.
1062 if (Ovl) {
1063 OverloadCandidateSet CandidateSet;
1064 OverloadCandidateSet::iterator Best;
1065 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
1066 switch (BestViableFunction(CandidateSet, Best)) {
1067 case OR_Success:
1068 {
1069 // Success! Let the remainder of this function build a call to
1070 // the function selected by overload resolution.
1071 FDecl = Best->Function;
1072 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1073 Fn->getSourceRange().getBegin());
1074 delete Fn;
1075 Fn = NewFn;
1076 }
1077 break;
1078
1079 case OR_No_Viable_Function:
1080 if (CandidateSet.empty())
1081 Diag(Fn->getSourceRange().getBegin(),
1082 diag::err_ovl_no_viable_function_in_call, Ovl->getName(),
1083 Fn->getSourceRange());
1084 else {
1085 Diag(Fn->getSourceRange().getBegin(),
1086 diag::err_ovl_no_viable_function_in_call_with_cands,
1087 Ovl->getName(), Fn->getSourceRange());
1088 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1089 }
1090 return true;
1091
1092 case OR_Ambiguous:
1093 Diag(Fn->getSourceRange().getBegin(),
1094 diag::err_ovl_ambiguous_call, Ovl->getName(),
1095 Fn->getSourceRange());
1096 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1097 return true;
1098 }
1099 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001100
1101 // Promote the function operand.
1102 UsualUnaryConversions(Fn);
1103
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001104 // Make the call expr early, before semantic checks. This guarantees cleanup
1105 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001106 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001107 Context.BoolTy, RParenLoc));
Steve Naroffd6163f32008-09-05 22:11:13 +00001108 const FunctionType *FuncT;
1109 if (!Fn->getType()->isBlockPointerType()) {
1110 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1111 // have type pointer to function".
1112 const PointerType *PT = Fn->getType()->getAsPointerType();
1113 if (PT == 0)
1114 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1115 Fn->getSourceRange());
1116 FuncT = PT->getPointeeType()->getAsFunctionType();
1117 } else { // This is a block call.
1118 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1119 getAsFunctionType();
1120 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001121 if (FuncT == 0)
Chris Lattner61000b12008-08-14 04:33:24 +00001122 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1123 Fn->getSourceRange());
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001124
1125 // We know the result type of the call, set it.
1126 TheCall->setType(FuncT->getResultType());
Chris Lattner4b009652007-07-25 00:24:17 +00001127
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001128 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001129 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1130 // assignment, to the types of the corresponding parameter, ...
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001131 unsigned NumArgsInProto = Proto->getNumArgs();
1132 unsigned NumArgsToCheck = NumArgs;
Chris Lattner4b009652007-07-25 00:24:17 +00001133
Chris Lattner3e254fb2008-04-08 04:40:51 +00001134 // If too few arguments are available (and we don't have default
1135 // arguments for the remaining parameters), don't make the call.
1136 if (NumArgs < NumArgsInProto) {
Chris Lattner97316c02008-04-10 02:22:51 +00001137 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001138 // Use default arguments for missing arguments
1139 NumArgsToCheck = NumArgsInProto;
Chris Lattner97316c02008-04-10 02:22:51 +00001140 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001141 } else
Steve Naroffd6163f32008-09-05 22:11:13 +00001142 return Diag(RParenLoc,
1143 !Fn->getType()->isBlockPointerType()
1144 ? diag::err_typecheck_call_too_few_args
1145 : diag::err_typecheck_block_too_few_args,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001146 Fn->getSourceRange());
1147 }
1148
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001149 // If too many are passed and not variadic, error on the extras and drop
1150 // them.
1151 if (NumArgs > NumArgsInProto) {
1152 if (!Proto->isVariadic()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001153 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffd6163f32008-09-05 22:11:13 +00001154 !Fn->getType()->isBlockPointerType()
1155 ? diag::err_typecheck_call_too_many_args
1156 : diag::err_typecheck_block_too_many_args,
1157 Fn->getSourceRange(),
Chris Lattner4b009652007-07-25 00:24:17 +00001158 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001159 Args[NumArgs-1]->getLocEnd()));
1160 // This deletes the extra arguments.
1161 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner4b009652007-07-25 00:24:17 +00001162 }
1163 NumArgsToCheck = NumArgsInProto;
1164 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001165
Chris Lattner4b009652007-07-25 00:24:17 +00001166 // Continue to check argument types (even if we have too few/many args).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001167 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner005ed752008-01-04 18:04:52 +00001168 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001169
1170 Expr *Arg;
1171 if (i < NumArgs)
1172 Arg = Args[i];
1173 else
1174 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
Chris Lattner005ed752008-01-04 18:04:52 +00001175 QualType ArgType = Arg->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001176
Douglas Gregor81c29152008-10-29 00:13:59 +00001177 // Pass the argument.
1178 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
Chris Lattner005ed752008-01-04 18:04:52 +00001179 return true;
Douglas Gregor81c29152008-10-29 00:13:59 +00001180
1181 TheCall->setArg(i, Arg);
Chris Lattner4b009652007-07-25 00:24:17 +00001182 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001183
1184 // If this is a variadic call, handle args passed through "...".
1185 if (Proto->isVariadic()) {
Steve Naroffdb65e052007-08-28 23:30:39 +00001186 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001187 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1188 Expr *Arg = Args[i];
1189 DefaultArgumentPromotion(Arg);
1190 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001191 }
Steve Naroffdb65e052007-08-28 23:30:39 +00001192 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001193 } else {
1194 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1195
Steve Naroffdb65e052007-08-28 23:30:39 +00001196 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001197 for (unsigned i = 0; i != NumArgs; i++) {
1198 Expr *Arg = Args[i];
1199 DefaultArgumentPromotion(Arg);
1200 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001201 }
Chris Lattner4b009652007-07-25 00:24:17 +00001202 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001203
Chris Lattner2e64c072007-08-10 20:18:51 +00001204 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001205 if (FDecl)
1206 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001207
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001208 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001209}
1210
1211Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001212ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001213 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001214 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001215 QualType literalType = QualType::getFromOpaquePtr(Ty);
1216 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001217 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001218 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001219
Eli Friedman8c2173d2008-05-20 05:22:08 +00001220 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001221 if (literalType->isVariableArrayType())
Eli Friedman8c2173d2008-05-20 05:22:08 +00001222 return Diag(LParenLoc,
1223 diag::err_variable_object_no_init,
1224 SourceRange(LParenLoc,
1225 literalExpr->getSourceRange().getEnd()));
1226 } else if (literalType->isIncompleteType()) {
1227 return Diag(LParenLoc,
1228 diag::err_typecheck_decl_incomplete_type,
1229 literalType.getAsString(),
1230 SourceRange(LParenLoc,
1231 literalExpr->getSourceRange().getEnd()));
1232 }
1233
Steve Narofff0b23542008-01-10 22:15:12 +00001234 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff92590f92008-01-09 20:58:06 +00001235 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001236
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001237 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001238 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001239 if (CheckForConstantInitializer(literalExpr, literalType))
1240 return true;
1241 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001242 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1243 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001244}
1245
1246Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001247ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001248 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001249 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001250 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001251
Steve Naroff0acc9c92007-09-15 18:49:24 +00001252 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001253 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001254
Chris Lattner71ca8c82008-10-26 23:43:26 +00001255 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1256 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001257 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1258 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001259}
1260
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001261/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001262bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001263 UsualUnaryConversions(castExpr);
1264
1265 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1266 // type needs to be scalar.
1267 if (castType->isVoidType()) {
1268 // Cast to void allows any expr type.
1269 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1270 // GCC struct/union extension: allow cast to self.
1271 if (Context.getCanonicalType(castType) !=
1272 Context.getCanonicalType(castExpr->getType()) ||
1273 (!castType->isStructureType() && !castType->isUnionType())) {
1274 // Reject any other conversions to non-scalar types.
1275 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1276 castType.getAsString(), castExpr->getSourceRange());
1277 }
1278
1279 // accept this, but emit an ext-warn.
1280 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1281 castType.getAsString(), castExpr->getSourceRange());
1282 } else if (!castExpr->getType()->isScalarType() &&
1283 !castExpr->getType()->isVectorType()) {
1284 return Diag(castExpr->getLocStart(),
1285 diag::err_typecheck_expect_scalar_operand,
1286 castExpr->getType().getAsString(),castExpr->getSourceRange());
1287 } else if (castExpr->getType()->isVectorType()) {
1288 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1289 return true;
1290 } else if (castType->isVectorType()) {
1291 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1292 return true;
1293 }
1294 return false;
1295}
1296
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001297bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001298 assert(VectorTy->isVectorType() && "Not a vector type!");
1299
1300 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001301 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001302 return Diag(R.getBegin(),
1303 Ty->isVectorType() ?
1304 diag::err_invalid_conversion_between_vectors :
1305 diag::err_invalid_conversion_between_vector_and_integer,
1306 VectorTy.getAsString().c_str(),
1307 Ty.getAsString().c_str(), R);
1308 } else
1309 return Diag(R.getBegin(),
1310 diag::err_invalid_conversion_between_vector_and_scalar,
1311 VectorTy.getAsString().c_str(),
1312 Ty.getAsString().c_str(), R);
1313
1314 return false;
1315}
1316
Chris Lattner4b009652007-07-25 00:24:17 +00001317Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001318ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001319 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001320 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001321
1322 Expr *castExpr = static_cast<Expr*>(Op);
1323 QualType castType = QualType::getFromOpaquePtr(Ty);
1324
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001325 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1326 return true;
Douglas Gregor035d0882008-10-28 15:36:24 +00001327 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001328}
1329
Chris Lattner98a425c2007-11-26 01:40:58 +00001330/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1331/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001332inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1333 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1334 UsualUnaryConversions(cond);
1335 UsualUnaryConversions(lex);
1336 UsualUnaryConversions(rex);
1337 QualType condT = cond->getType();
1338 QualType lexT = lex->getType();
1339 QualType rexT = rex->getType();
1340
1341 // first, check the condition.
1342 if (!condT->isScalarType()) { // C99 6.5.15p2
1343 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1344 condT.getAsString());
1345 return QualType();
1346 }
Chris Lattner992ae932008-01-06 22:42:25 +00001347
1348 // Now check the two expressions.
1349
1350 // If both operands have arithmetic type, do the usual arithmetic conversions
1351 // to find a common type: C99 6.5.15p3,5.
1352 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001353 UsualArithmeticConversions(lex, rex);
1354 return lex->getType();
1355 }
Chris Lattner992ae932008-01-06 22:42:25 +00001356
1357 // If both operands are the same structure or union type, the result is that
1358 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001359 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001360 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001361 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001362 // "If both the operands have structure or union type, the result has
1363 // that type." This implies that CV qualifiers are dropped.
1364 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001365 }
Chris Lattner992ae932008-01-06 22:42:25 +00001366
1367 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001368 // The following || allows only one side to be void (a GCC-ism).
1369 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001370 if (!lexT->isVoidType())
Steve Naroff95cb3892008-05-12 21:44:38 +00001371 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1372 rex->getSourceRange());
1373 if (!rexT->isVoidType())
1374 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopes4ba41fd2008-06-04 19:14:12 +00001375 lex->getSourceRange());
Eli Friedmanf025aac2008-06-04 19:47:51 +00001376 ImpCastExprToType(lex, Context.VoidTy);
1377 ImpCastExprToType(rex, Context.VoidTy);
1378 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001379 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001380 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1381 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001382 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1383 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001384 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001385 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001386 return lexT;
1387 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001388 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1389 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff3eac7692008-09-10 19:17:48 +00001390 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001391 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001392 return rexT;
1393 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001394 // Handle the case where both operands are pointers before we handle null
1395 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001396 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1397 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1398 // get the "pointed to" types
1399 QualType lhptee = LHSPT->getPointeeType();
1400 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001401
Chris Lattner71225142007-07-31 21:27:01 +00001402 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1403 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001404 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001405 // Figure out necessary qualifiers (C99 6.5.15p6)
1406 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001407 QualType destType = Context.getPointerType(destPointee);
1408 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1409 ImpCastExprToType(rex, destType); // promote to void*
1410 return destType;
1411 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001412 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001413 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001414 QualType destType = Context.getPointerType(destPointee);
1415 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1416 ImpCastExprToType(rex, destType); // promote to void*
1417 return destType;
1418 }
Chris Lattner4b009652007-07-25 00:24:17 +00001419
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001420 QualType compositeType = lexT;
1421
1422 // If either type is an Objective-C object type then check
1423 // compatibility according to Objective-C.
1424 if (Context.isObjCObjectPointerType(lexT) ||
1425 Context.isObjCObjectPointerType(rexT)) {
1426 // If both operands are interfaces and either operand can be
1427 // assigned to the other, use that type as the composite
1428 // type. This allows
1429 // xxx ? (A*) a : (B*) b
1430 // where B is a subclass of A.
1431 //
1432 // Additionally, as for assignment, if either type is 'id'
1433 // allow silent coercion. Finally, if the types are
1434 // incompatible then make sure to use 'id' as the composite
1435 // type so the result is acceptable for sending messages to.
1436
1437 // FIXME: This code should not be localized to here. Also this
1438 // should use a compatible check instead of abusing the
1439 // canAssignObjCInterfaces code.
1440 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1441 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1442 if (LHSIface && RHSIface &&
1443 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1444 compositeType = lexT;
1445 } else if (LHSIface && RHSIface &&
1446 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1447 compositeType = rexT;
1448 } else if (Context.isObjCIdType(lhptee) ||
1449 Context.isObjCIdType(rhptee)) {
1450 // FIXME: This code looks wrong, because isObjCIdType checks
1451 // the struct but getObjCIdType returns the pointer to
1452 // struct. This is horrible and should be fixed.
1453 compositeType = Context.getObjCIdType();
1454 } else {
1455 QualType incompatTy = Context.getObjCIdType();
1456 ImpCastExprToType(lex, incompatTy);
1457 ImpCastExprToType(rex, incompatTy);
1458 return incompatTy;
1459 }
1460 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1461 rhptee.getUnqualifiedType())) {
Steve Naroff232324e2008-02-01 22:44:48 +00001462 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner71225142007-07-31 21:27:01 +00001463 lexT.getAsString(), rexT.getAsString(),
1464 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001465 // In this situation, we assume void* type. No especially good
1466 // reason, but this is what gcc does, and we do have to pick
1467 // to get a consistent AST.
1468 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001469 ImpCastExprToType(lex, incompatTy);
1470 ImpCastExprToType(rex, incompatTy);
1471 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001472 }
1473 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001474 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1475 // differently qualified versions of compatible types, the result type is
1476 // a pointer to an appropriately qualified version of the *composite*
1477 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001478 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001479 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001480 ImpCastExprToType(lex, compositeType);
1481 ImpCastExprToType(rex, compositeType);
1482 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001483 }
Chris Lattner4b009652007-07-25 00:24:17 +00001484 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001485 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1486 // evaluates to "struct objc_object *" (and is handled above when comparing
1487 // id with statically typed objects).
1488 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1489 // GCC allows qualified id and any Objective-C type to devolve to
1490 // id. Currently localizing to here until clear this should be
1491 // part of ObjCQualifiedIdTypesAreCompatible.
1492 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1493 (lexT->isObjCQualifiedIdType() &&
1494 Context.isObjCObjectPointerType(rexT)) ||
1495 (rexT->isObjCQualifiedIdType() &&
1496 Context.isObjCObjectPointerType(lexT))) {
1497 // FIXME: This is not the correct composite type. This only
1498 // happens to work because id can more or less be used anywhere,
1499 // however this may change the type of method sends.
1500 // FIXME: gcc adds some type-checking of the arguments and emits
1501 // (confusing) incompatible comparison warnings in some
1502 // cases. Investigate.
1503 QualType compositeType = Context.getObjCIdType();
1504 ImpCastExprToType(lex, compositeType);
1505 ImpCastExprToType(rex, compositeType);
1506 return compositeType;
1507 }
1508 }
1509
Steve Naroff3eac7692008-09-10 19:17:48 +00001510 // Selection between block pointer types is ok as long as they are the same.
1511 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1512 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1513 return lexT;
1514
Chris Lattner992ae932008-01-06 22:42:25 +00001515 // Otherwise, the operands are not compatible.
Chris Lattner4b009652007-07-25 00:24:17 +00001516 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1517 lexT.getAsString(), rexT.getAsString(),
1518 lex->getSourceRange(), rex->getSourceRange());
1519 return QualType();
1520}
1521
Steve Naroff87d58b42007-09-16 03:34:24 +00001522/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001523/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001524Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001525 SourceLocation ColonLoc,
1526 ExprTy *Cond, ExprTy *LHS,
1527 ExprTy *RHS) {
1528 Expr *CondExpr = (Expr *) Cond;
1529 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001530
1531 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1532 // was the condition.
1533 bool isLHSNull = LHSExpr == 0;
1534 if (isLHSNull)
1535 LHSExpr = CondExpr;
1536
Chris Lattner4b009652007-07-25 00:24:17 +00001537 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1538 RHSExpr, QuestionLoc);
1539 if (result.isNull())
1540 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00001541 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1542 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00001543}
1544
Chris Lattner4b009652007-07-25 00:24:17 +00001545
1546// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1547// being closely modeled after the C99 spec:-). The odd characteristic of this
1548// routine is it effectively iqnores the qualifiers on the top level pointee.
1549// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1550// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00001551Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001552Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1553 QualType lhptee, rhptee;
1554
1555 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00001556 lhptee = lhsType->getAsPointerType()->getPointeeType();
1557 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001558
1559 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001560 lhptee = Context.getCanonicalType(lhptee);
1561 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00001562
Chris Lattner005ed752008-01-04 18:04:52 +00001563 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001564
1565 // C99 6.5.16.1p1: This following citation is common to constraints
1566 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1567 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00001568 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001569 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00001570 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00001571
1572 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1573 // incomplete type and the other is a pointer to a qualified or unqualified
1574 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001575 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001576 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001577 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001578
1579 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001580 assert(rhptee->isFunctionType());
1581 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001582 }
1583
1584 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00001585 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00001586 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001587
1588 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00001589 assert(lhptee->isFunctionType());
1590 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00001591 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00001592
1593 // Check for ObjC interfaces
1594 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1595 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1596 if (LHSIface && RHSIface &&
1597 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1598 return ConvTy;
1599
1600 // ID acts sort of like void* for ObjC interfaces
1601 if (LHSIface && Context.isObjCIdType(rhptee))
1602 return ConvTy;
1603 if (RHSIface && Context.isObjCIdType(lhptee))
1604 return ConvTy;
1605
Chris Lattner4b009652007-07-25 00:24:17 +00001606 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1607 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00001608 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1609 rhptee.getUnqualifiedType()))
1610 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00001611 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001612}
1613
Steve Naroff3454b6c2008-09-04 15:10:53 +00001614/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1615/// block pointer types are compatible or whether a block and normal pointer
1616/// are compatible. It is more restrict than comparing two function pointer
1617// types.
1618Sema::AssignConvertType
1619Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1620 QualType rhsType) {
1621 QualType lhptee, rhptee;
1622
1623 // get the "pointed to" type (ignoring qualifiers at the top level)
1624 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1625 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1626
1627 // make sure we operate on the canonical type
1628 lhptee = Context.getCanonicalType(lhptee);
1629 rhptee = Context.getCanonicalType(rhptee);
1630
1631 AssignConvertType ConvTy = Compatible;
1632
1633 // For blocks we enforce that qualifiers are identical.
1634 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1635 ConvTy = CompatiblePointerDiscardsQualifiers;
1636
1637 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1638 return IncompatibleBlockPointer;
1639 return ConvTy;
1640}
1641
Chris Lattner4b009652007-07-25 00:24:17 +00001642/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1643/// has code to accommodate several GCC extensions when type checking
1644/// pointers. Here are some objectionable examples that GCC considers warnings:
1645///
1646/// int a, *pint;
1647/// short *pshort;
1648/// struct foo *pfoo;
1649///
1650/// pint = pshort; // warning: assignment from incompatible pointer type
1651/// a = pint; // warning: assignment makes integer from pointer without a cast
1652/// pint = a; // warning: assignment makes pointer from integer without a cast
1653/// pint = pfoo; // warning: assignment from incompatible pointer type
1654///
1655/// As a result, the code for dealing with pointers is more complex than the
1656/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00001657///
Chris Lattner005ed752008-01-04 18:04:52 +00001658Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001659Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00001660 // Get canonical types. We're not formatting these types, just comparing
1661 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001662 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1663 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00001664
1665 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00001666 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00001667
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001668 // If the left-hand side is a reference type, then we are in a
1669 // (rare!) case where we've allowed the use of references in C,
1670 // e.g., as a parameter type in a built-in function. In this case,
1671 // just make sure that the type referenced is compatible with the
1672 // right-hand side type. The caller is responsible for adjusting
1673 // lhsType so that the resulting expression does not have reference
1674 // type.
1675 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
1676 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00001677 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001678 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001679 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001680
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001681 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1682 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001683 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00001684 // Relax integer conversions like we do for pointers below.
1685 if (rhsType->isIntegerType())
1686 return IntToPointer;
1687 if (lhsType->isIntegerType())
1688 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00001689 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00001690 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001691
Nate Begemanc5f0f652008-07-14 18:02:46 +00001692 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001693 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00001694 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1695 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001696 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001697
Nate Begemanc5f0f652008-07-14 18:02:46 +00001698 // If we are allowing lax vector conversions, and LHS and RHS are both
1699 // vectors, the total size only needs to be the same. This is a bitcast;
1700 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001701 if (getLangOptions().LaxVectorConversions &&
1702 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001703 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1704 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001705 }
1706 return Incompatible;
1707 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001708
Chris Lattnerdb22bf42008-01-04 23:32:24 +00001709 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00001710 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001711
Chris Lattner390564e2008-04-07 06:49:41 +00001712 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001713 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001714 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00001715
Chris Lattner390564e2008-04-07 06:49:41 +00001716 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001717 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001718
Steve Naroffa982c712008-09-29 18:10:17 +00001719 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00001720 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff3454b6c2008-09-04 15:10:53 +00001721 return BlockVoidPointer;
Steve Naroffa982c712008-09-29 18:10:17 +00001722
1723 // Treat block pointers as objects.
1724 if (getLangOptions().ObjC1 &&
1725 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1726 return Compatible;
1727 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001728 return Incompatible;
1729 }
1730
1731 if (isa<BlockPointerType>(lhsType)) {
1732 if (rhsType->isIntegerType())
1733 return IntToPointer;
1734
Steve Naroffa982c712008-09-29 18:10:17 +00001735 // Treat block pointers as objects.
1736 if (getLangOptions().ObjC1 &&
1737 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1738 return Compatible;
1739
Steve Naroff3454b6c2008-09-04 15:10:53 +00001740 if (rhsType->isBlockPointerType())
1741 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1742
1743 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1744 if (RHSPT->getPointeeType()->isVoidType())
1745 return BlockVoidPointer;
1746 }
Chris Lattner1853da22008-01-04 23:18:45 +00001747 return Incompatible;
1748 }
1749
Chris Lattner390564e2008-04-07 06:49:41 +00001750 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001751 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00001752 if (lhsType == Context.BoolTy)
1753 return Compatible;
1754
1755 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00001756 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00001757
Chris Lattner390564e2008-04-07 06:49:41 +00001758 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001759 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00001760
1761 if (isa<BlockPointerType>(lhsType) &&
1762 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1763 return BlockVoidPointer;
Chris Lattner1853da22008-01-04 23:18:45 +00001764 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00001765 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00001766
Chris Lattner1853da22008-01-04 23:18:45 +00001767 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00001768 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00001769 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00001770 }
1771 return Incompatible;
1772}
1773
Chris Lattner005ed752008-01-04 18:04:52 +00001774Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001775Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001776 if (getLangOptions().CPlusPlus) {
1777 if (!lhsType->isRecordType()) {
1778 // C++ 5.17p3: If the left operand is not of class type, the
1779 // expression is implicitly converted (C++ 4) to the
1780 // cv-unqualified type of the left operand.
Douglas Gregorbb461502008-10-24 04:54:22 +00001781 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001782 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00001783 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001784 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001785 }
1786
1787 // FIXME: Currently, we fall through and treat C++ classes like C
1788 // structures.
1789 }
1790
Steve Naroffcdee22d2007-11-27 17:58:44 +00001791 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1792 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00001793 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1794 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00001795 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001796 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00001797 return Compatible;
1798 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00001799
1800 // We don't allow conversion of non-null-pointer constants to integers.
1801 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1802 return IntToBlockPointer;
1803
Chris Lattner5f505bf2007-10-16 02:55:40 +00001804 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00001805 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00001806 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00001807 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00001808 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001809 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00001810 if (!lhsType->isReferenceType())
1811 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00001812
Chris Lattner005ed752008-01-04 18:04:52 +00001813 Sema::AssignConvertType result =
1814 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001815
1816 // C99 6.5.16.1p2: The value of the right operand is converted to the
1817 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001818 // CheckAssignmentConstraints allows the left-hand side to be a reference,
1819 // so that we can use references in built-in functions even in C.
1820 // The getNonReferenceType() call makes sure that the resulting expression
1821 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00001822 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00001823 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00001824 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00001825}
1826
Chris Lattner005ed752008-01-04 18:04:52 +00001827Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00001828Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1829 return CheckAssignmentConstraints(lhsType, rhsType);
1830}
1831
Chris Lattner2c8bff72007-12-12 05:47:28 +00001832QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Chris Lattner4b009652007-07-25 00:24:17 +00001833 Diag(loc, diag::err_typecheck_invalid_operands,
1834 lex->getType().getAsString(), rex->getType().getAsString(),
1835 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner2c8bff72007-12-12 05:47:28 +00001836 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00001837}
1838
1839inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1840 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00001841 // For conversion purposes, we ignore any qualifiers.
1842 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001843 QualType lhsType =
1844 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1845 QualType rhsType =
1846 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001847
Nate Begemanc5f0f652008-07-14 18:02:46 +00001848 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00001849 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00001850 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00001851
Nate Begemanc5f0f652008-07-14 18:02:46 +00001852 // Handle the case of a vector & extvector type of the same size and element
1853 // type. It would be nice if we only had one vector type someday.
1854 if (getLangOptions().LaxVectorConversions)
1855 if (const VectorType *LV = lhsType->getAsVectorType())
1856 if (const VectorType *RV = rhsType->getAsVectorType())
1857 if (LV->getElementType() == RV->getElementType() &&
1858 LV->getNumElements() == RV->getNumElements())
1859 return lhsType->isExtVectorType() ? lhsType : rhsType;
1860
1861 // If the lhs is an extended vector and the rhs is a scalar of the same type
1862 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001863 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001864 QualType eltType = V->getElementType();
1865
1866 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1867 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1868 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001869 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001870 return lhsType;
1871 }
1872 }
1873
Nate Begemanc5f0f652008-07-14 18:02:46 +00001874 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00001875 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001876 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00001877 QualType eltType = V->getElementType();
1878
1879 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1880 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1881 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001882 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00001883 return rhsType;
1884 }
1885 }
1886
Chris Lattner4b009652007-07-25 00:24:17 +00001887 // You cannot convert between vector values of different size.
1888 Diag(loc, diag::err_typecheck_vector_not_convertable,
1889 lex->getType().getAsString(), rex->getType().getAsString(),
1890 lex->getSourceRange(), rex->getSourceRange());
1891 return QualType();
1892}
1893
1894inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001895 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001896{
1897 QualType lhsType = lex->getType(), rhsType = rex->getType();
1898
1899 if (lhsType->isVectorType() || rhsType->isVectorType())
1900 return CheckVectorOperands(loc, lex, rex);
1901
Steve Naroff8f708362007-08-24 19:07:16 +00001902 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001903
Chris Lattner4b009652007-07-25 00:24:17 +00001904 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001905 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001906 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001907}
1908
1909inline QualType Sema::CheckRemainderOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00001910 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001911{
1912 QualType lhsType = lex->getType(), rhsType = rex->getType();
1913
Steve Naroff8f708362007-08-24 19:07:16 +00001914 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001915
Chris Lattner4b009652007-07-25 00:24:17 +00001916 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00001917 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00001918 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001919}
1920
1921inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff8f708362007-08-24 19:07:16 +00001922 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00001923{
1924 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1925 return CheckVectorOperands(loc, lex, rex);
1926
Steve Naroff8f708362007-08-24 19:07:16 +00001927 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001928
Chris Lattner4b009652007-07-25 00:24:17 +00001929 // handle the common case first (both operands are arithmetic).
1930 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001931 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00001932
Eli Friedmand9b1fec2008-05-18 18:08:51 +00001933 // Put any potential pointer into PExp
1934 Expr* PExp = lex, *IExp = rex;
1935 if (IExp->getType()->isPointerType())
1936 std::swap(PExp, IExp);
1937
1938 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1939 if (IExp->getType()->isIntegerType()) {
1940 // Check for arithmetic on pointers to incomplete types
1941 if (!PTy->getPointeeType()->isObjectType()) {
1942 if (PTy->getPointeeType()->isVoidType()) {
1943 Diag(loc, diag::ext_gnu_void_ptr,
1944 lex->getSourceRange(), rex->getSourceRange());
1945 } else {
1946 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1947 lex->getType().getAsString(), lex->getSourceRange());
1948 return QualType();
1949 }
1950 }
1951 return PExp->getType();
1952 }
1953 }
1954
Chris Lattner2c8bff72007-12-12 05:47:28 +00001955 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00001956}
1957
Chris Lattnerfe1f4032008-04-07 05:30:13 +00001958// C99 6.5.6
1959QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1960 SourceLocation loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00001961 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1962 return CheckVectorOperands(loc, lex, rex);
1963
Steve Naroff8f708362007-08-24 19:07:16 +00001964 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00001965
Chris Lattnerf6da2912007-12-09 21:53:25 +00001966 // Enforce type constraints: C99 6.5.6p3.
1967
1968 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00001969 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00001970 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00001971
1972 // Either ptr - int or ptr - ptr.
1973 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00001974 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00001975
Chris Lattnerf6da2912007-12-09 21:53:25 +00001976 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00001977 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001978 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00001979 if (lpointee->isVoidType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001980 Diag(loc, diag::ext_gnu_void_ptr,
1981 lex->getSourceRange(), rex->getSourceRange());
1982 } else {
1983 Diag(loc, diag::err_typecheck_sub_ptr_object,
1984 lex->getType().getAsString(), lex->getSourceRange());
1985 return QualType();
1986 }
1987 }
1988
1989 // The result type of a pointer-int computation is the pointer type.
1990 if (rex->getType()->isIntegerType())
1991 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001992
Chris Lattnerf6da2912007-12-09 21:53:25 +00001993 // Handle pointer-pointer subtractions.
1994 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00001995 QualType rpointee = RHSPTy->getPointeeType();
1996
Chris Lattnerf6da2912007-12-09 21:53:25 +00001997 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00001998 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00001999 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002000 if (rpointee->isVoidType()) {
2001 if (!lpointee->isVoidType())
Chris Lattnerf6da2912007-12-09 21:53:25 +00002002 Diag(loc, diag::ext_gnu_void_ptr,
2003 lex->getSourceRange(), rex->getSourceRange());
2004 } else {
2005 Diag(loc, diag::err_typecheck_sub_ptr_object,
2006 rex->getType().getAsString(), rex->getSourceRange());
2007 return QualType();
2008 }
2009 }
2010
2011 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002012 if (!Context.typesAreCompatible(
2013 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2014 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002015 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
2016 lex->getType().getAsString(), rex->getType().getAsString(),
2017 lex->getSourceRange(), rex->getSourceRange());
2018 return QualType();
2019 }
2020
2021 return Context.getPointerDiffType();
2022 }
2023 }
2024
Chris Lattner2c8bff72007-12-12 05:47:28 +00002025 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002026}
2027
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002028// C99 6.5.7
2029QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2030 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002031 // C99 6.5.7p2: Each of the operands shall have integer type.
2032 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
2033 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002034
Chris Lattner2c8bff72007-12-12 05:47:28 +00002035 // Shifts don't perform usual arithmetic conversions, they just do integer
2036 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002037 if (!isCompAssign)
2038 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002039 UsualUnaryConversions(rex);
2040
2041 // "The type of the result is that of the promoted left operand."
2042 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002043}
2044
Eli Friedman0d9549b2008-08-22 00:56:42 +00002045static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2046 ASTContext& Context) {
2047 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2048 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2049 // ID acts sort of like void* for ObjC interfaces
2050 if (LHSIface && Context.isObjCIdType(RHS))
2051 return true;
2052 if (RHSIface && Context.isObjCIdType(LHS))
2053 return true;
2054 if (!LHSIface || !RHSIface)
2055 return false;
2056 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2057 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2058}
2059
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002060// C99 6.5.8
2061QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2062 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002063 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2064 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
2065
Chris Lattner254f3bc2007-08-26 01:18:55 +00002066 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002067 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2068 UsualArithmeticConversions(lex, rex);
2069 else {
2070 UsualUnaryConversions(lex);
2071 UsualUnaryConversions(rex);
2072 }
Chris Lattner4b009652007-07-25 00:24:17 +00002073 QualType lType = lex->getType();
2074 QualType rType = rex->getType();
2075
Ted Kremenek486509e2007-10-29 17:13:39 +00002076 // For non-floating point types, check for self-comparisons of the form
2077 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2078 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002079 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002080 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2081 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002082 if (DRL->getDecl() == DRR->getDecl())
2083 Diag(loc, diag::warn_selfcomparison);
2084 }
2085
Chris Lattner254f3bc2007-08-26 01:18:55 +00002086 if (isRelational) {
2087 if (lType->isRealType() && rType->isRealType())
2088 return Context.IntTy;
2089 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002090 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002091 if (lType->isFloatingType()) {
2092 assert (rType->isFloatingType());
Ted Kremenek30c66752007-11-25 00:58:00 +00002093 CheckFloatComparison(loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002094 }
2095
Chris Lattner254f3bc2007-08-26 01:18:55 +00002096 if (lType->isArithmeticType() && rType->isArithmeticType())
2097 return Context.IntTy;
2098 }
Chris Lattner4b009652007-07-25 00:24:17 +00002099
Chris Lattner22be8422007-08-26 01:10:14 +00002100 bool LHSIsNull = lex->isNullPointerConstant(Context);
2101 bool RHSIsNull = rex->isNullPointerConstant(Context);
2102
Chris Lattner254f3bc2007-08-26 01:18:55 +00002103 // All of the following pointer related warnings are GCC extensions, except
2104 // when handling null pointer constants. One day, we can consider making them
2105 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002106 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002107 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002108 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002109 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002110 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002111
Steve Naroff3b435622007-11-13 14:57:38 +00002112 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002113 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2114 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002115 RCanPointeeTy.getUnqualifiedType()) &&
2116 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroff4462cb02007-08-16 21:48:38 +00002117 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2118 lType.getAsString(), rType.getAsString(),
2119 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002120 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002121 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002122 return Context.IntTy;
2123 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002124 // Handle block pointer types.
2125 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2126 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2127 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2128
2129 if (!LHSIsNull && !RHSIsNull &&
2130 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2131 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2132 lType.getAsString(), rType.getAsString(),
2133 lex->getSourceRange(), rex->getSourceRange());
2134 }
2135 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2136 return Context.IntTy;
2137 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002138 // Allow block pointers to be compared with null pointer constants.
2139 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2140 (lType->isPointerType() && rType->isBlockPointerType())) {
2141 if (!LHSIsNull && !RHSIsNull) {
2142 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2143 lType.getAsString(), rType.getAsString(),
2144 lex->getSourceRange(), rex->getSourceRange());
2145 }
2146 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2147 return Context.IntTy;
2148 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002149
Steve Naroff936c4362008-06-03 14:04:54 +00002150 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002151 if (lType->isPointerType() || rType->isPointerType()) {
2152 if (!Context.typesAreCompatible(lType, rType)) {
2153 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2154 lType.getAsString(), rType.getAsString(),
2155 lex->getSourceRange(), rex->getSourceRange());
2156 ImpCastExprToType(rex, lType);
2157 return Context.IntTy;
2158 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002159 ImpCastExprToType(rex, lType);
Steve Naroff792800d2008-10-22 22:40:28 +00002160 return Context.IntTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002161 }
Steve Naroff936c4362008-06-03 14:04:54 +00002162 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2163 ImpCastExprToType(rex, lType);
2164 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002165 } else {
2166 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
2167 Diag(loc, diag::warn_incompatible_qualified_id_operands,
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002168 lType.getAsString(), rType.getAsString(),
Steve Naroff19608432008-10-14 22:18:38 +00002169 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002170 ImpCastExprToType(rex, lType);
Steve Naroff792800d2008-10-22 22:40:28 +00002171 return Context.IntTy;
Steve Naroff19608432008-10-14 22:18:38 +00002172 }
Steve Naroff936c4362008-06-03 14:04:54 +00002173 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002174 }
Steve Naroff936c4362008-06-03 14:04:54 +00002175 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2176 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002177 if (!RHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002178 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2179 lType.getAsString(), rType.getAsString(),
2180 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002181 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002182 return Context.IntTy;
2183 }
Steve Naroff936c4362008-06-03 14:04:54 +00002184 if (lType->isIntegerType() &&
2185 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002186 if (!LHSIsNull)
Steve Naroff4462cb02007-08-16 21:48:38 +00002187 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2188 lType.getAsString(), rType.getAsString(),
2189 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnere992d6c2008-01-16 19:17:22 +00002190 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroff4462cb02007-08-16 21:48:38 +00002191 return Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002192 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002193 // Handle block pointers.
2194 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2195 if (!RHSIsNull)
2196 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2197 lType.getAsString(), rType.getAsString(),
2198 lex->getSourceRange(), rex->getSourceRange());
2199 ImpCastExprToType(rex, lType); // promote the integer to pointer
2200 return Context.IntTy;
2201 }
2202 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2203 if (!LHSIsNull)
2204 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2205 lType.getAsString(), rType.getAsString(),
2206 lex->getSourceRange(), rex->getSourceRange());
2207 ImpCastExprToType(lex, rType); // promote the integer to pointer
2208 return Context.IntTy;
2209 }
Chris Lattner2c8bff72007-12-12 05:47:28 +00002210 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002211}
2212
Nate Begemanc5f0f652008-07-14 18:02:46 +00002213/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2214/// operates on extended vector types. Instead of producing an IntTy result,
2215/// like a scalar comparison, a vector comparison produces a vector of integer
2216/// types.
2217QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2218 SourceLocation loc,
2219 bool isRelational) {
2220 // Check to make sure we're operating on vectors of the same type and width,
2221 // Allowing one side to be a scalar of element type.
2222 QualType vType = CheckVectorOperands(loc, lex, rex);
2223 if (vType.isNull())
2224 return vType;
2225
2226 QualType lType = lex->getType();
2227 QualType rType = rex->getType();
2228
2229 // For non-floating point types, check for self-comparisons of the form
2230 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2231 // often indicate logic errors in the program.
2232 if (!lType->isFloatingType()) {
2233 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2234 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2235 if (DRL->getDecl() == DRR->getDecl())
2236 Diag(loc, diag::warn_selfcomparison);
2237 }
2238
2239 // Check for comparisons of floating point operands using != and ==.
2240 if (!isRelational && lType->isFloatingType()) {
2241 assert (rType->isFloatingType());
2242 CheckFloatComparison(loc,lex,rex);
2243 }
2244
2245 // Return the type for the comparison, which is the same as vector type for
2246 // integer vectors, or an integer type of identical size and number of
2247 // elements for floating point vectors.
2248 if (lType->isIntegerType())
2249 return lType;
2250
2251 const VectorType *VTy = lType->getAsVectorType();
2252
2253 // FIXME: need to deal with non-32b int / non-64b long long
2254 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2255 if (TypeSize == 32) {
2256 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2257 }
2258 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2259 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2260}
2261
Chris Lattner4b009652007-07-25 00:24:17 +00002262inline QualType Sema::CheckBitwiseOperands(
Steve Naroff8f708362007-08-24 19:07:16 +00002263 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002264{
2265 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2266 return CheckVectorOperands(loc, lex, rex);
2267
Steve Naroff8f708362007-08-24 19:07:16 +00002268 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002269
2270 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002271 return compType;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002272 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002273}
2274
2275inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
2276 Expr *&lex, Expr *&rex, SourceLocation loc)
2277{
2278 UsualUnaryConversions(lex);
2279 UsualUnaryConversions(rex);
2280
Eli Friedmanbea3f842008-05-13 20:16:47 +00002281 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002282 return Context.IntTy;
Chris Lattner2c8bff72007-12-12 05:47:28 +00002283 return InvalidOperands(loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002284}
2285
2286inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Naroff0f32f432007-08-24 22:33:52 +00002287 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Chris Lattner4b009652007-07-25 00:24:17 +00002288{
2289 QualType lhsType = lex->getType();
2290 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner25168a52008-07-26 21:30:36 +00002291 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002292
2293 switch (mlval) { // C99 6.5.16p2
Chris Lattner005ed752008-01-04 18:04:52 +00002294 case Expr::MLV_Valid:
2295 break;
2296 case Expr::MLV_ConstQualified:
2297 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2298 return QualType();
2299 case Expr::MLV_ArrayType:
2300 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2301 lhsType.getAsString(), lex->getSourceRange());
2302 return QualType();
2303 case Expr::MLV_NotObjectType:
2304 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2305 lhsType.getAsString(), lex->getSourceRange());
2306 return QualType();
2307 case Expr::MLV_InvalidExpression:
2308 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2309 lex->getSourceRange());
2310 return QualType();
2311 case Expr::MLV_IncompleteType:
2312 case Expr::MLV_IncompleteVoidType:
2313 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2314 lhsType.getAsString(), lex->getSourceRange());
2315 return QualType();
2316 case Expr::MLV_DuplicateVectorComponents:
2317 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2318 lex->getSourceRange());
2319 return QualType();
Steve Naroff076d6cb2008-09-26 14:41:28 +00002320 case Expr::MLV_NotBlockQualified:
2321 Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2322 lex->getSourceRange());
2323 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002324 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002325
Chris Lattner005ed752008-01-04 18:04:52 +00002326 AssignConvertType ConvTy;
Chris Lattner34c85082008-08-21 18:04:13 +00002327 if (compoundType.isNull()) {
2328 // Simple assignment "x = y".
Chris Lattner005ed752008-01-04 18:04:52 +00002329 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner34c85082008-08-21 18:04:13 +00002330
2331 // If the RHS is a unary plus or minus, check to see if they = and + are
2332 // right next to each other. If so, the user may have typo'd "x =+ 4"
2333 // instead of "x += 4".
2334 Expr *RHSCheck = rex;
2335 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2336 RHSCheck = ICE->getSubExpr();
2337 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2338 if ((UO->getOpcode() == UnaryOperator::Plus ||
2339 UO->getOpcode() == UnaryOperator::Minus) &&
2340 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2341 // Only if the two operators are exactly adjacent.
2342 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2343 Diag(loc, diag::warn_not_compound_assign,
2344 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2345 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2346 }
2347 } else {
2348 // Compound assignment "x += y"
Chris Lattner005ed752008-01-04 18:04:52 +00002349 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner34c85082008-08-21 18:04:13 +00002350 }
Chris Lattner005ed752008-01-04 18:04:52 +00002351
2352 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2353 rex, "assigning"))
2354 return QualType();
2355
Chris Lattner4b009652007-07-25 00:24:17 +00002356 // C99 6.5.16p3: The type of an assignment expression is the type of the
2357 // left operand unless the left operand has qualified type, in which case
2358 // it is the unqualified version of the type of the left operand.
2359 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2360 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002361 // C++ 5.17p1: the type of the assignment expression is that of its left
2362 // oprdu.
Chris Lattner005ed752008-01-04 18:04:52 +00002363 return lhsType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002364}
2365
2366inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2367 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00002368
2369 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2370 DefaultFunctionArrayConversion(rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002371 return rex->getType();
2372}
2373
2374/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2375/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2376QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2377 QualType resType = op->getType();
2378 assert(!resType.isNull() && "no type for increment/decrement expression");
2379
Steve Naroffd30e1932007-08-24 17:20:07 +00002380 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffce827582007-11-11 14:15:57 +00002381 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002382 if (pt->getPointeeType()->isVoidType()) {
2383 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2384 } else if (!pt->getPointeeType()->isObjectType()) {
2385 // C99 6.5.2.4p2, 6.5.6p2
Chris Lattner4b009652007-07-25 00:24:17 +00002386 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2387 resType.getAsString(), op->getSourceRange());
2388 return QualType();
2389 }
Steve Naroffd30e1932007-08-24 17:20:07 +00002390 } else if (!resType->isRealType()) {
2391 if (resType->isComplexType())
2392 // C99 does not support ++/-- on complex types.
2393 Diag(OpLoc, diag::ext_integer_increment_complex,
2394 resType.getAsString(), op->getSourceRange());
2395 else {
2396 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2397 resType.getAsString(), op->getSourceRange());
2398 return QualType();
2399 }
Chris Lattner4b009652007-07-25 00:24:17 +00002400 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002401 // At this point, we know we have a real, complex or pointer type.
2402 // Now make sure the operand is a modifiable lvalue.
Chris Lattner25168a52008-07-26 21:30:36 +00002403 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002404 if (mlval != Expr::MLV_Valid) {
2405 // FIXME: emit a more precise diagnostic...
2406 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2407 op->getSourceRange());
2408 return QualType();
2409 }
2410 return resType;
2411}
2412
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002413/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002414/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002415/// where the declaration is needed for type checking. We only need to
2416/// handle cases when the expression references a function designator
2417/// or is an lvalue. Here are some examples:
2418/// - &(x) => x
2419/// - &*****f => f for f a function designator.
2420/// - &s.xx => s
2421/// - &s.zz[1].yy -> s, if zz is an array
2422/// - *(x + 1) -> x, if x is an array
2423/// - &"123"[2] -> 0
2424/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002425static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002426 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002427 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002428 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002429 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002430 // Fields cannot be declared with a 'register' storage class.
2431 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002432 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002433 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002434 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002435 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002436 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002437
Douglas Gregord2baafd2008-10-21 16:13:35 +00002438 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002439 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002440 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002441 return 0;
2442 else
2443 return VD;
2444 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002445 case Stmt::UnaryOperatorClass: {
2446 UnaryOperator *UO = cast<UnaryOperator>(E);
2447
2448 switch(UO->getOpcode()) {
2449 case UnaryOperator::Deref: {
2450 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002451 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2452 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2453 if (!VD || VD->getType()->isPointerType())
2454 return 0;
2455 return VD;
2456 }
2457 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002458 }
2459 case UnaryOperator::Real:
2460 case UnaryOperator::Imag:
2461 case UnaryOperator::Extension:
2462 return getPrimaryDecl(UO->getSubExpr());
2463 default:
2464 return 0;
2465 }
2466 }
2467 case Stmt::BinaryOperatorClass: {
2468 BinaryOperator *BO = cast<BinaryOperator>(E);
2469
2470 // Handle cases involving pointer arithmetic. The result of an
2471 // Assign or AddAssign is not an lvalue so they can be ignored.
2472
2473 // (x + n) or (n + x) => x
2474 if (BO->getOpcode() == BinaryOperator::Add) {
2475 if (BO->getLHS()->getType()->isPointerType()) {
2476 return getPrimaryDecl(BO->getLHS());
2477 } else if (BO->getRHS()->getType()->isPointerType()) {
2478 return getPrimaryDecl(BO->getRHS());
2479 }
2480 }
2481
2482 return 0;
2483 }
Chris Lattner4b009652007-07-25 00:24:17 +00002484 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002485 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002486 case Stmt::ImplicitCastExprClass:
2487 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002488 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002489 default:
2490 return 0;
2491 }
2492}
2493
2494/// CheckAddressOfOperand - The operand of & must be either a function
2495/// designator or an lvalue designating an object. If it is an lvalue, the
2496/// object cannot be declared with storage class register or be a bit field.
2497/// Note: The usual conversions are *not* applied to the operand of the &
2498/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2499QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002500 if (getLangOptions().C99) {
2501 // Implement C99-only parts of addressof rules.
2502 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2503 if (uOp->getOpcode() == UnaryOperator::Deref)
2504 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2505 // (assuming the deref expression is valid).
2506 return uOp->getSubExpr()->getType();
2507 }
2508 // Technically, there should be a check for array subscript
2509 // expressions here, but the result of one is always an lvalue anyway.
2510 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002511 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00002512 Expr::isLvalueResult lval = op->isLvalue(Context);
Chris Lattner4b009652007-07-25 00:24:17 +00002513
2514 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00002515 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2516 // FIXME: emit more specific diag...
Chris Lattner4b009652007-07-25 00:24:17 +00002517 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2518 op->getSourceRange());
2519 return QualType();
2520 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00002521 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2522 if (MemExpr->getMemberDecl()->isBitField()) {
2523 Diag(OpLoc, diag::err_typecheck_address_of,
2524 std::string("bit-field"), op->getSourceRange());
2525 return QualType();
2526 }
2527 // Check for Apple extension for accessing vector components.
2528 } else if (isa<ArraySubscriptExpr>(op) &&
2529 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2530 Diag(OpLoc, diag::err_typecheck_address_of,
2531 std::string("vector"), op->getSourceRange());
2532 return QualType();
2533 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00002534 // We have an lvalue with a decl. Make sure the decl is not declared
2535 // with the register storage-class specifier.
2536 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2537 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroff73cf87e2008-02-29 23:30:25 +00002538 Diag(OpLoc, diag::err_typecheck_address_of,
2539 std::string("register variable"), op->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002540 return QualType();
2541 }
2542 } else
2543 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00002544 }
Chris Lattnera55e3212008-07-27 00:48:22 +00002545
Chris Lattner4b009652007-07-25 00:24:17 +00002546 // If the operand has type "type", the result has type "pointer to type".
2547 return Context.getPointerType(op->getType());
2548}
2549
2550QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2551 UsualUnaryConversions(op);
2552 QualType qType = op->getType();
2553
Chris Lattner7931f4a2007-07-31 16:53:04 +00002554 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff9c6c3592008-01-13 17:10:08 +00002555 // Note that per both C89 and C99, this is always legal, even
2556 // if ptype is an incomplete type or void.
2557 // It would be possible to warn about dereferencing a
2558 // void pointer, but it's completely well-defined,
2559 // and such a warning is unlikely to catch any mistakes.
2560 return PT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002561 }
2562 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2563 qType.getAsString(), op->getSourceRange());
2564 return QualType();
2565}
2566
2567static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2568 tok::TokenKind Kind) {
2569 BinaryOperator::Opcode Opc;
2570 switch (Kind) {
2571 default: assert(0 && "Unknown binop!");
2572 case tok::star: Opc = BinaryOperator::Mul; break;
2573 case tok::slash: Opc = BinaryOperator::Div; break;
2574 case tok::percent: Opc = BinaryOperator::Rem; break;
2575 case tok::plus: Opc = BinaryOperator::Add; break;
2576 case tok::minus: Opc = BinaryOperator::Sub; break;
2577 case tok::lessless: Opc = BinaryOperator::Shl; break;
2578 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2579 case tok::lessequal: Opc = BinaryOperator::LE; break;
2580 case tok::less: Opc = BinaryOperator::LT; break;
2581 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2582 case tok::greater: Opc = BinaryOperator::GT; break;
2583 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2584 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2585 case tok::amp: Opc = BinaryOperator::And; break;
2586 case tok::caret: Opc = BinaryOperator::Xor; break;
2587 case tok::pipe: Opc = BinaryOperator::Or; break;
2588 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2589 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2590 case tok::equal: Opc = BinaryOperator::Assign; break;
2591 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2592 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2593 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2594 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2595 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2596 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2597 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2598 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2599 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2600 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2601 case tok::comma: Opc = BinaryOperator::Comma; break;
2602 }
2603 return Opc;
2604}
2605
2606static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2607 tok::TokenKind Kind) {
2608 UnaryOperator::Opcode Opc;
2609 switch (Kind) {
2610 default: assert(0 && "Unknown unary op!");
2611 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2612 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2613 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2614 case tok::star: Opc = UnaryOperator::Deref; break;
2615 case tok::plus: Opc = UnaryOperator::Plus; break;
2616 case tok::minus: Opc = UnaryOperator::Minus; break;
2617 case tok::tilde: Opc = UnaryOperator::Not; break;
2618 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2619 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2620 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2621 case tok::kw___real: Opc = UnaryOperator::Real; break;
2622 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2623 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2624 }
2625 return Opc;
2626}
2627
2628// Binary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002629Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00002630 ExprTy *LHS, ExprTy *RHS) {
2631 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2632 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2633
Steve Naroff87d58b42007-09-16 03:34:24 +00002634 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2635 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002636
2637 QualType ResultTy; // Result type of the binary operator.
2638 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2639
2640 switch (Opc) {
2641 default:
2642 assert(0 && "Unknown binary expr!");
2643 case BinaryOperator::Assign:
2644 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2645 break;
2646 case BinaryOperator::Mul:
2647 case BinaryOperator::Div:
2648 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2649 break;
2650 case BinaryOperator::Rem:
2651 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2652 break;
2653 case BinaryOperator::Add:
2654 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2655 break;
2656 case BinaryOperator::Sub:
2657 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2658 break;
2659 case BinaryOperator::Shl:
2660 case BinaryOperator::Shr:
2661 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2662 break;
2663 case BinaryOperator::LE:
2664 case BinaryOperator::LT:
2665 case BinaryOperator::GE:
2666 case BinaryOperator::GT:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002667 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002668 break;
2669 case BinaryOperator::EQ:
2670 case BinaryOperator::NE:
Chris Lattner254f3bc2007-08-26 01:18:55 +00002671 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Chris Lattner4b009652007-07-25 00:24:17 +00002672 break;
2673 case BinaryOperator::And:
2674 case BinaryOperator::Xor:
2675 case BinaryOperator::Or:
2676 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2677 break;
2678 case BinaryOperator::LAnd:
2679 case BinaryOperator::LOr:
2680 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2681 break;
2682 case BinaryOperator::MulAssign:
2683 case BinaryOperator::DivAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002684 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002685 if (!CompTy.isNull())
2686 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2687 break;
2688 case BinaryOperator::RemAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002689 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002690 if (!CompTy.isNull())
2691 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2692 break;
2693 case BinaryOperator::AddAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002694 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002695 if (!CompTy.isNull())
2696 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2697 break;
2698 case BinaryOperator::SubAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002699 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002700 if (!CompTy.isNull())
2701 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2702 break;
2703 case BinaryOperator::ShlAssign:
2704 case BinaryOperator::ShrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002705 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002706 if (!CompTy.isNull())
2707 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2708 break;
2709 case BinaryOperator::AndAssign:
2710 case BinaryOperator::XorAssign:
2711 case BinaryOperator::OrAssign:
Steve Naroff8f708362007-08-24 19:07:16 +00002712 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Chris Lattner4b009652007-07-25 00:24:17 +00002713 if (!CompTy.isNull())
2714 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2715 break;
2716 case BinaryOperator::Comma:
2717 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2718 break;
2719 }
2720 if (ResultTy.isNull())
2721 return true;
2722 if (CompTy.isNull())
Chris Lattnerf420df12007-08-28 18:36:55 +00002723 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002724 else
Chris Lattnerf420df12007-08-28 18:36:55 +00002725 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002726}
2727
2728// Unary Operators. 'Tok' is the token for the operator.
Steve Naroff87d58b42007-09-16 03:34:24 +00002729Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Chris Lattner4b009652007-07-25 00:24:17 +00002730 ExprTy *input) {
2731 Expr *Input = (Expr*)input;
2732 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2733 QualType resultType;
2734 switch (Opc) {
2735 default:
2736 assert(0 && "Unimplemented unary expr!");
2737 case UnaryOperator::PreInc:
2738 case UnaryOperator::PreDec:
2739 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2740 break;
2741 case UnaryOperator::AddrOf:
2742 resultType = CheckAddressOfOperand(Input, OpLoc);
2743 break;
2744 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00002745 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00002746 resultType = CheckIndirectionOperand(Input, OpLoc);
2747 break;
2748 case UnaryOperator::Plus:
2749 case UnaryOperator::Minus:
2750 UsualUnaryConversions(Input);
2751 resultType = Input->getType();
2752 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2753 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2754 resultType.getAsString());
2755 break;
2756 case UnaryOperator::Not: // bitwise complement
2757 UsualUnaryConversions(Input);
2758 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00002759 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2760 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2761 // C99 does not support '~' for complex conjugation.
2762 Diag(OpLoc, diag::ext_integer_complement_complex,
2763 resultType.getAsString(), Input->getSourceRange());
2764 else if (!resultType->isIntegerType())
2765 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2766 resultType.getAsString(), Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002767 break;
2768 case UnaryOperator::LNot: // logical negation
2769 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2770 DefaultFunctionArrayConversion(Input);
2771 resultType = Input->getType();
2772 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2773 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2774 resultType.getAsString());
2775 // LNot always has type int. C99 6.5.3.3p5.
2776 resultType = Context.IntTy;
2777 break;
2778 case UnaryOperator::SizeOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002779 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2780 Input->getSourceRange(), true);
Chris Lattner4b009652007-07-25 00:24:17 +00002781 break;
2782 case UnaryOperator::AlignOf:
Chris Lattnerf814d882008-07-25 21:45:37 +00002783 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2784 Input->getSourceRange(), false);
Chris Lattner4b009652007-07-25 00:24:17 +00002785 break;
Chris Lattner03931a72007-08-24 21:16:53 +00002786 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00002787 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00002788 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00002789 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002790 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00002791 resultType = Input->getType();
2792 break;
2793 }
2794 if (resultType.isNull())
2795 return true;
2796 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2797}
2798
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002799/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2800Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002801 SourceLocation LabLoc,
2802 IdentifierInfo *LabelII) {
2803 // Look up the record for this label identifier.
2804 LabelStmt *&LabelDecl = LabelMap[LabelII];
2805
Daniel Dunbar879788d2008-08-04 16:51:22 +00002806 // If we haven't seen this label yet, create a forward reference. It
2807 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00002808 if (LabelDecl == 0)
2809 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2810
2811 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00002812 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2813 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002814}
2815
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002816Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00002817 SourceLocation RPLoc) { // "({..})"
2818 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2819 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2820 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2821
2822 // FIXME: there are a variety of strange constraints to enforce here, for
2823 // example, it is not possible to goto into a stmt expression apparently.
2824 // More semantic analysis is needed.
2825
2826 // FIXME: the last statement in the compount stmt has its value used. We
2827 // should not warn about it being unused.
2828
2829 // If there are sub stmts in the compound stmt, take the type of the last one
2830 // as the type of the stmtexpr.
2831 QualType Ty = Context.VoidTy;
2832
Chris Lattner200964f2008-07-26 19:51:01 +00002833 if (!Compound->body_empty()) {
2834 Stmt *LastStmt = Compound->body_back();
2835 // If LastStmt is a label, skip down through into the body.
2836 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2837 LastStmt = Label->getSubStmt();
2838
2839 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00002840 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00002841 }
Chris Lattner4b009652007-07-25 00:24:17 +00002842
2843 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2844}
Steve Naroff63bad2d2007-08-01 22:05:33 +00002845
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002846Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002847 SourceLocation TypeLoc,
2848 TypeTy *argty,
2849 OffsetOfComponent *CompPtr,
2850 unsigned NumComponents,
2851 SourceLocation RPLoc) {
2852 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2853 assert(!ArgTy.isNull() && "Missing type argument!");
2854
2855 // We must have at least one component that refers to the type, and the first
2856 // one is known to be a field designator. Verify that the ArgTy represents
2857 // a struct/union/class.
2858 if (!ArgTy->isRecordType())
2859 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2860
2861 // Otherwise, create a compound literal expression as the base, and
2862 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00002863 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002864
Chris Lattnerb37522e2007-08-31 21:49:13 +00002865 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2866 // GCC extension, diagnose them.
2867 if (NumComponents != 1)
2868 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2869 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2870
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002871 for (unsigned i = 0; i != NumComponents; ++i) {
2872 const OffsetOfComponent &OC = CompPtr[i];
2873 if (OC.isBrackets) {
2874 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00002875 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002876 if (!AT) {
2877 delete Res;
2878 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2879 Res->getType().getAsString());
2880 }
2881
Chris Lattner2af6a802007-08-30 17:59:59 +00002882 // FIXME: C++: Verify that operator[] isn't overloaded.
2883
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002884 // C99 6.5.2.1p1
2885 Expr *Idx = static_cast<Expr*>(OC.U.E);
2886 if (!Idx->getType()->isIntegerType())
2887 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2888 Idx->getSourceRange());
2889
2890 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2891 continue;
2892 }
2893
2894 const RecordType *RC = Res->getType()->getAsRecordType();
2895 if (!RC) {
2896 delete Res;
2897 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2898 Res->getType().getAsString());
2899 }
2900
2901 // Get the decl corresponding to this.
2902 RecordDecl *RD = RC->getDecl();
2903 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2904 if (!MemberDecl)
2905 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2906 OC.U.IdentInfo->getName(),
2907 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner2af6a802007-08-30 17:59:59 +00002908
2909 // FIXME: C++: Verify that MemberDecl isn't a static field.
2910 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00002911 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2912 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002913 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
2914 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002915 }
2916
2917 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2918 BuiltinLoc);
2919}
2920
2921
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002922Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00002923 TypeTy *arg1, TypeTy *arg2,
2924 SourceLocation RPLoc) {
2925 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2926 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2927
2928 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2929
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002930 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00002931}
2932
Steve Naroff5cbb02f2007-09-16 14:56:35 +00002933Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00002934 ExprTy *expr1, ExprTy *expr2,
2935 SourceLocation RPLoc) {
2936 Expr *CondExpr = static_cast<Expr*>(cond);
2937 Expr *LHSExpr = static_cast<Expr*>(expr1);
2938 Expr *RHSExpr = static_cast<Expr*>(expr2);
2939
2940 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2941
2942 // The conditional expression is required to be a constant expression.
2943 llvm::APSInt condEval(32);
2944 SourceLocation ExpLoc;
2945 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2946 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2947 CondExpr->getSourceRange());
2948
2949 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2950 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2951 RHSExpr->getType();
2952 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2953}
2954
Steve Naroff52a81c02008-09-03 18:15:37 +00002955//===----------------------------------------------------------------------===//
2956// Clang Extensions.
2957//===----------------------------------------------------------------------===//
2958
2959/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00002960void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00002961 // Analyze block parameters.
2962 BlockSemaInfo *BSI = new BlockSemaInfo();
2963
2964 // Add BSI to CurBlock.
2965 BSI->PrevBlockInfo = CurBlock;
2966 CurBlock = BSI;
2967
2968 BSI->ReturnType = 0;
2969 BSI->TheScope = BlockScope;
2970
Steve Naroff52059382008-10-10 01:28:17 +00002971 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
2972 PushDeclContext(BSI->TheDecl);
2973}
2974
2975void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00002976 // Analyze arguments to block.
2977 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2978 "Not a function declarator!");
2979 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2980
Steve Naroff52059382008-10-10 01:28:17 +00002981 CurBlock->hasPrototype = FTI.hasPrototype;
2982 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00002983
2984 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2985 // no arguments, not a function that takes a single void argument.
2986 if (FTI.hasPrototype &&
2987 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2988 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2989 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2990 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00002991 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00002992 } else if (FTI.hasPrototype) {
2993 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00002994 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2995 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00002996 }
Steve Naroff52059382008-10-10 01:28:17 +00002997 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
2998
2999 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3000 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3001 // If this has an identifier, add it to the scope stack.
3002 if ((*AI)->getIdentifier())
3003 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003004}
3005
3006/// ActOnBlockError - If there is an error parsing a block, this callback
3007/// is invoked to pop the information about the block from the action impl.
3008void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3009 // Ensure that CurBlock is deleted.
3010 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3011
3012 // Pop off CurBlock, handle nested blocks.
3013 CurBlock = CurBlock->PrevBlockInfo;
3014
3015 // FIXME: Delete the ParmVarDecl objects as well???
3016
3017}
3018
3019/// ActOnBlockStmtExpr - This is called when the body of a block statement
3020/// literal was successfully completed. ^(int x){...}
3021Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3022 Scope *CurScope) {
3023 // Ensure that CurBlock is deleted.
3024 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3025 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3026
Steve Naroff52059382008-10-10 01:28:17 +00003027 PopDeclContext();
3028
Steve Naroff52a81c02008-09-03 18:15:37 +00003029 // Pop off CurBlock, handle nested blocks.
3030 CurBlock = CurBlock->PrevBlockInfo;
3031
3032 QualType RetTy = Context.VoidTy;
3033 if (BSI->ReturnType)
3034 RetTy = QualType(BSI->ReturnType, 0);
3035
3036 llvm::SmallVector<QualType, 8> ArgTypes;
3037 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3038 ArgTypes.push_back(BSI->Params[i]->getType());
3039
3040 QualType BlockTy;
3041 if (!BSI->hasPrototype)
3042 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3043 else
3044 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003045 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003046
3047 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003048
Steve Naroff95029d92008-10-08 18:44:00 +00003049 BSI->TheDecl->setBody(Body.take());
3050 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003051}
3052
Nate Begemanbd881ef2008-01-30 20:50:20 +00003053/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003054/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003055/// The number of arguments has already been validated to match the number of
3056/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003057static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3058 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003059 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003060 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003061 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3062 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003063
3064 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003065 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003066 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003067 return true;
3068}
3069
3070Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3071 SourceLocation *CommaLocs,
3072 SourceLocation BuiltinLoc,
3073 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003074 // __builtin_overload requires at least 2 arguments
3075 if (NumArgs < 2)
3076 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3077 SourceRange(BuiltinLoc, RParenLoc));
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003078
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003079 // The first argument is required to be a constant expression. It tells us
3080 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003081 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003082 Expr *NParamsExpr = Args[0];
3083 llvm::APSInt constEval(32);
3084 SourceLocation ExpLoc;
3085 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
3086 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3087 NParamsExpr->getSourceRange());
3088
3089 // Verify that the number of parameters is > 0
3090 unsigned NumParams = constEval.getZExtValue();
3091 if (NumParams == 0)
3092 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3093 NParamsExpr->getSourceRange());
3094 // Verify that we have at least 1 + NumParams arguments to the builtin.
3095 if ((NumParams + 1) > NumArgs)
3096 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3097 SourceRange(BuiltinLoc, RParenLoc));
3098
3099 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003100 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003101 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003102 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3103 // UsualUnaryConversions will convert the function DeclRefExpr into a
3104 // pointer to function.
3105 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003106 const FunctionTypeProto *FnType = 0;
3107 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3108 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003109
3110 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3111 // parameters, and the number of parameters must match the value passed to
3112 // the builtin.
3113 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begemanbd881ef2008-01-30 20:50:20 +00003114 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
3115 Fn->getSourceRange());
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003116
3117 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003118 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003119 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003120 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003121 if (OE)
3122 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
3123 OE->getFn()->getSourceRange());
3124 // Remember our match, and continue processing the remaining arguments
3125 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003126 OE = new OverloadExpr(Args, NumArgs, i,
3127 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003128 BuiltinLoc, RParenLoc);
3129 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003130 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003131 // Return the newly created OverloadExpr node, if we succeded in matching
3132 // exactly one of the candidate functions.
3133 if (OE)
3134 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003135
3136 // If we didn't find a matching function Expr in the __builtin_overload list
3137 // the return an error.
3138 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003139 for (unsigned i = 0; i != NumParams; ++i) {
3140 if (i != 0) typeNames += ", ";
3141 typeNames += Args[i+1]->getType().getAsString();
3142 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003143
3144 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3145 SourceRange(BuiltinLoc, RParenLoc));
3146}
3147
Anders Carlsson36760332007-10-15 20:28:48 +00003148Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3149 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003150 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003151 Expr *E = static_cast<Expr*>(expr);
3152 QualType T = QualType::getFromOpaquePtr(type);
3153
3154 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003155
3156 // Get the va_list type
3157 QualType VaListType = Context.getBuiltinVaListType();
3158 // Deal with implicit array decay; for example, on x86-64,
3159 // va_list is an array, but it's supposed to decay to
3160 // a pointer for va_arg.
3161 if (VaListType->isArrayType())
3162 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003163 // Make sure the input expression also decays appropriately.
3164 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003165
3166 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003167 return Diag(E->getLocStart(),
3168 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3169 E->getType().getAsString(),
3170 E->getSourceRange());
3171
3172 // FIXME: Warn if a non-POD type is passed in.
3173
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003174 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003175}
3176
Chris Lattner005ed752008-01-04 18:04:52 +00003177bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3178 SourceLocation Loc,
3179 QualType DstType, QualType SrcType,
3180 Expr *SrcExpr, const char *Flavor) {
3181 // Decode the result (notice that AST's are still created for extensions).
3182 bool isInvalid = false;
3183 unsigned DiagKind;
3184 switch (ConvTy) {
3185 default: assert(0 && "Unknown conversion type");
3186 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003187 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003188 DiagKind = diag::ext_typecheck_convert_pointer_int;
3189 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003190 case IntToPointer:
3191 DiagKind = diag::ext_typecheck_convert_int_pointer;
3192 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003193 case IncompatiblePointer:
3194 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3195 break;
3196 case FunctionVoidPointer:
3197 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3198 break;
3199 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003200 // If the qualifiers lost were because we were applying the
3201 // (deprecated) C++ conversion from a string literal to a char*
3202 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3203 // Ideally, this check would be performed in
3204 // CheckPointerTypesForAssignment. However, that would require a
3205 // bit of refactoring (so that the second argument is an
3206 // expression, rather than a type), which should be done as part
3207 // of a larger effort to fix CheckPointerTypesForAssignment for
3208 // C++ semantics.
3209 if (getLangOptions().CPlusPlus &&
3210 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3211 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003212 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3213 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003214 case IntToBlockPointer:
3215 DiagKind = diag::err_int_to_block_pointer;
3216 break;
3217 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003218 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003219 break;
3220 case BlockVoidPointer:
3221 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3222 break;
Steve Naroff19608432008-10-14 22:18:38 +00003223 case IncompatibleObjCQualifiedId:
3224 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3225 // it can give a more specific diagnostic.
3226 DiagKind = diag::warn_incompatible_qualified_id;
3227 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003228 case Incompatible:
3229 DiagKind = diag::err_typecheck_convert_incompatible;
3230 isInvalid = true;
3231 break;
3232 }
3233
3234 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3235 SrcExpr->getSourceRange());
3236 return isInvalid;
3237}