blob: a4fae9117edec10c975b03d648fe7d1487150f6d [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner04421082008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Chris Lattnere7a2e912008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattnere7a2e912008-07-25 21:10:04 +000033/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
34void Sema::DefaultFunctionArrayConversion(Expr *&E) {
35 QualType Ty = E->getType();
36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
37
Chris Lattnere7a2e912008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-07-25 21:33:13 +000040 else if (Ty->isArrayType()) {
41 // In C90 mode, arrays only promote to pointers if the array expression is
42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
43 // type 'array of type' is converted to an expression that has type 'pointer
44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
45 // that has type 'array of type' ...". The relevant change is "an lvalue"
46 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +000047 //
48 // C++ 4.2p1:
49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
50 // T" can be converted to an rvalue of type "pointer to T".
51 //
52 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
53 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner67d33d82008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattnere7a2e912008-07-25 21:10:04 +000056}
57
58/// UsualUnaryConversions - Performs various conversions that are common to most
59/// operators (C99 6.3). The conversions of array and function types are
60/// sometimes surpressed. For example, the array->pointer conversion doesn't
61/// apply if the array is an argument to the sizeof or address (&) operators.
62/// In these instances, this routine should *not* be called.
63Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
64 QualType Ty = Expr->getType();
65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
66
Chris Lattnere7a2e912008-07-25 21:10:04 +000067 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
68 ImpCastExprToType(Expr, Context.IntTy);
69 else
70 DefaultFunctionArrayConversion(Expr);
71
72 return Expr;
73}
74
Chris Lattner05faf172008-07-25 22:25:12 +000075/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
76/// do not have a prototype. Arguments that have type float are promoted to
77/// double. All other argument types are converted by UsualUnaryConversions().
78void Sema::DefaultArgumentPromotion(Expr *&Expr) {
79 QualType Ty = Expr->getType();
80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
81
82 // If this is a 'float' (CVR qualified or typedef) promote to double.
83 if (const BuiltinType *BT = Ty->getAsBuiltinType())
84 if (BT->getKind() == BuiltinType::Float)
85 return ImpCastExprToType(Expr, Context.DoubleTy);
86
87 UsualUnaryConversions(Expr);
88}
89
Chris Lattnere7a2e912008-07-25 21:10:04 +000090/// UsualArithmeticConversions - Performs various conversions that are common to
91/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
92/// routine returns the first non-arithmetic type found. The client is
93/// responsible for emitting appropriate error diagnostics.
94/// FIXME: verify the conversion rules for "complex int" are consistent with
95/// GCC.
96QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
97 bool isCompAssign) {
98 if (!isCompAssign) {
99 UsualUnaryConversions(lhsExpr);
100 UsualUnaryConversions(rhsExpr);
101 }
102 // For conversion purposes, we ignore any qualifiers.
103 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000104 QualType lhs =
105 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
106 QualType rhs =
107 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Chris Lattnere7a2e912008-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 Narofff69936d2007-09-16 03:34:24 +0000259/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofff69936d2007-09-16 03:34:24 +0000266Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnera7ad98f2008-02-11 00:02:17 +0000276
277 // Verify that pascal strings aren't too large.
Anders Carlssonee98ac52007-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()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000282
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000283 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000284 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000285 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-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 Lattnera7ad98f2008-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
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
299 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000300 Literal.AnyWide, StrTy,
Anders Carlssonee98ac52007-10-15 02:50:23 +0000301 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000302 StringToks[NumStringToks-1].getLocation());
303}
304
Chris Lattner639e2d32008-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 Naroff08d92e42007-09-15 18:49:24 +0000335/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000336/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000337/// identifier is used in a function call context.
Steve Naroff08d92e42007-09-15 18:49:24 +0000338Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000339 IdentifierInfo &II,
340 bool HasTrailingLParen) {
Chris Lattner8a934232008-03-31 00:36:02 +0000341 // Could be enum-constant, value decl, instance variable, etc.
Steve Naroffb327ce02008-04-02 14:35:35 +0000342 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
Chris Lattner8a934232008-03-31 00:36:02 +0000343
344 // If this reference is in an Objective-C method, then ivar lookup happens as
345 // well.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000346 if (getCurMethodDecl()) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000347 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattner8a934232008-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 Naroffe8043c32008-04-01 23:04:06 +0000353 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000354 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Chris Lattner123a11f2008-07-21 04:44:44 +0000355 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
Chris Lattner8a934232008-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 Naroff76de9d72008-08-10 19:10:41 +0000364 // Needed to implement property "super.method" notation.
Daniel Dunbar662e8b52008-08-14 22:04:54 +0000365 if (SD == 0 && &II == SuperID) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000366 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000367 getCurMethodDecl()->getClassInterface()));
Steve Naroff76de9d72008-08-10 19:10:41 +0000368 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000369 }
Chris Lattner8a934232008-03-31 00:36:02 +0000370 }
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner8a934232008-03-31 00:36:02 +0000375 !getLangOptions().CPlusPlus) // Not in C++.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner8a934232008-03-31 00:36:02 +0000383
Argyrios Kyrtzidis07952322008-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
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +0000398 // FIXME: Handle 'mutable'.
399 return new DeclRefExpr(FD,
400 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000401 }
402
403 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
404 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000405 if (isa<TypedefDecl>(D))
406 return Diag(Loc, diag::err_unexpected_typedef, II.getName());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000407 if (isa<ObjCInterfaceDecl>(D))
Fariborz Jahanian5ef404f2007-12-05 18:16:33 +0000408 return Diag(Loc, diag::err_unexpected_interface, II.getName());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000409 if (isa<NamespaceDecl>(D))
410 return Diag(Loc, diag::err_unexpected_namespace, II.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000411
Steve Naroffdd972f22008-09-05 22:11:13 +0000412 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000413 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
414 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
415
Steve Naroffdd972f22008-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 Lattner639e2d32008-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 Naroffdd972f22008-09-05 22:11:13 +0000430 //
Chris Lattner639e2d32008-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 Naroff090276f2008-10-10 01:28:17 +0000435 // The BlocksAttr indicates the variable is bound by-reference.
436 if (VD->getAttr<BlocksAttr>())
Douglas Gregor9d293df2008-10-28 00:22:11 +0000437 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
438 Loc, true);
Steve Naroff090276f2008-10-10 01:28:17 +0000439
440 // Variable will be bound by-copy, make it const within the closure.
441 VD->getType().addConst();
Douglas Gregor9d293df2008-10-28 00:22:11 +0000442 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
443 Loc, false);
Steve Naroff090276f2008-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 Gregore0a5d5f2008-10-22 04:14:44 +0000447 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000448}
449
Chris Lattnerd9f69102008-08-10 01:53:14 +0000450Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000451 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000452 PredefinedExpr::IdentType IT;
Anders Carlsson22742662007-07-21 05:21:51 +0000453
Reid Spencer5f016e22007-07-11 17:01:13 +0000454 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000455 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-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;
Reid Spencer5f016e22007-07-11 17:01:13 +0000459 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000460
461 // Verify that this is in a function context.
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000462 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
Chris Lattner1423ea42008-01-12 18:39:25 +0000463 return Diag(Loc, diag::err_predef_outside_function);
Anders Carlsson22742662007-07-21 05:21:51 +0000464
Chris Lattnerfa28b302008-01-12 08:14:25 +0000465 // Pre-defined identifiers are of type char[x], where x is the length of the
466 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000467 unsigned Length;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000468 if (getCurFunctionDecl())
469 Length = getCurFunctionDecl()->getIdentifier()->getLength();
Chris Lattner8f978d52008-01-12 19:32:28 +0000470 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000471 Length = getCurMethodDecl()->getSynthesizedMethodSize();
Chris Lattner1423ea42008-01-12 18:39:25 +0000472
Chris Lattner8f978d52008-01-12 19:32:28 +0000473 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000474 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000475 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerd9f69102008-08-10 01:53:14 +0000476 return new PredefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000477}
478
Steve Narofff69936d2007-09-16 03:34:24 +0000479Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerfc62bfd2008-03-01 08:32:21 +0000489
490 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
491
Chris Lattnerc250aae2008-06-07 22:35:38 +0000492 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
493 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000494}
495
Steve Narofff69936d2007-09-16 03:34:24 +0000496Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000500 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000501
Chris Lattner98be4942008-03-05 18:54:05 +0000502 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000503 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +0000504 Context.IntTy,
505 Tok.getLocation()));
506 }
507 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000508 // Add padding so that NumericLiteralParser can overread by one character.
509 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner28997ec2008-09-30 20:51:14 +0000514
Reid Spencer5f016e22007-07-11 17:01:13 +0000515 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
516 Tok.getLocation(), PP);
517 if (Literal.hadError)
518 return ExprResult(true);
519
Chris Lattner5d661452007-08-26 03:42:43 +0000520 Expr *Res;
521
522 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000523 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000524 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000525 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000526 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000527 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000528 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000529 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000530
531 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
532
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000533 // isExact will be set by GetFloatValue().
534 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000535 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000536 Ty, Tok.getLocation());
537
Chris Lattner5d661452007-08-26 03:42:43 +0000538 } else if (!Literal.isIntegerLiteral()) {
539 return ExprResult(true);
540 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000541 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000542
Neil Boothb9449512007-08-29 22:00:19 +0000543 // long long is a C99 feature.
544 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000545 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000546 Diag(Tok.getLocation(), diag::ext_longlong);
547
Reid Spencer5f016e22007-07-11 17:01:13 +0000548 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000549 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000554 Ty = Context.UnsignedLongLongTy;
555 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000556 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner8cbcb0e2008-05-09 05:59:00 +0000566 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000567 if (!Literal.isLong && !Literal.isLongLong) {
568 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000569 unsigned IntSize = Context.Target.getIntWidth();
570
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000575 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000576 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000577 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000578 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000579 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000580 }
581
582 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000583 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000584 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000590 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000592 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000593 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 }
596
597 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000598 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000599 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000605 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000606 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000607 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000608 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf0467b32008-04-02 04:24:33 +0000614 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000615 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000616 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000617 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000618 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000619
620 if (ResultVal.getBitWidth() != Width)
621 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000622 }
623
Chris Lattnerf0467b32008-04-02 04:24:33 +0000624 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000625 }
Chris Lattner5d661452007-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;
Reid Spencer5f016e22007-07-11 17:01:13 +0000632}
633
Steve Narofff69936d2007-09-16 03:34:24 +0000634Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000635 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000636 Expr *E = (Expr *)Val;
637 assert((E != 0) && "ActOnParenExpr() missing expr");
638 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerbb280a42008-07-25 21:45:37 +0000644 SourceLocation OpLoc,
645 const SourceRange &ExprRange,
646 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000647 // C99 6.5.3.4p1:
648 if (isa<FunctionType>(exprType) && isSizeof)
649 // alignof(function) is allowed.
Chris Lattnerbb280a42008-07-25 21:45:37 +0000650 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000651 else if (exprType->isVoidType())
Chris Lattnerbb280a42008-07-25 21:45:37 +0000652 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
653 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +0000654 else if (exprType->isIncompleteType()) {
655 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
656 diag::err_alignof_incomplete_type,
Chris Lattnerbb280a42008-07-25 21:45:37 +0000657 exprType.getAsString(), ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofff69936d2007-09-16 03:34:24 +0000665ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerbb280a42008-07-25 21:45:37 +0000674 QualType resultType =
675 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
Reid Spencer5f016e22007-07-11 17:01:13 +0000676
677 if (resultType.isNull())
678 return true;
679 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
680}
681
Chris Lattner5d794252007-08-24 21:41:10 +0000682QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +0000683 DefaultFunctionArrayConversion(V);
684
Chris Lattnercc26ed72007-08-26 05:39:26 +0000685 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +0000686 if (const ComplexType *CT = V->getType()->getAsComplexType())
687 return CT->getElementType();
Chris Lattnercc26ed72007-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 Lattnerdbb36972007-08-24 21:16:53 +0000696}
697
698
Reid Spencer5f016e22007-07-11 17:01:13 +0000699
Steve Narofff69936d2007-09-16 03:34:24 +0000700Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofff69936d2007-09-16 03:34:24 +0000716ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +0000718 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +0000719
720 // Perform default conversions.
721 DefaultFunctionArrayConversion(LHSExp);
722 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +0000723
Chris Lattner12d9ff62007-07-16 00:14:47 +0000724 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000725
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +0000727 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 // in the subscript position. As a result, we need to derive the array base
729 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +0000730 Expr *BaseExpr, *IndexExpr;
731 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +0000732 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +0000733 BaseExpr = LHSExp;
734 IndexExpr = RHSExp;
735 // FIXME: need to deal with const...
736 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +0000737 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +0000738 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +0000739 BaseExpr = RHSExp;
740 IndexExpr = LHSExp;
741 // FIXME: need to deal with const...
742 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +0000743 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
744 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +0000745 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +0000746
747 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +0000748 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
749 !isa<ExtVectorElementExpr>(BaseExpr))
Nate Begeman213541a2008-04-18 23:10:10 +0000750 return Diag(LLoc, diag::err_ext_vector_component_access,
Steve Naroff608e0ee2007-08-03 22:40:33 +0000751 SourceRange(LLoc, RLoc));
Chris Lattner12d9ff62007-07-16 00:14:47 +0000752 // FIXME: need to deal with const...
753 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000754 } else {
Chris Lattner727a80d2007-07-15 23:59:53 +0000755 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
756 RHSExp->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000757 }
758 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +0000759 if (!IndexExpr->getType()->isIntegerType())
760 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
761 IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000762
Chris Lattner12d9ff62007-07-16 00:14:47 +0000763 // 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 Lattnerd805bec2008-04-02 06:59:01 +0000765 // void (*)(int)) and pointers to incomplete types. Functions are not
766 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +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);
Reid Spencer5f016e22007-07-11 17:01:13 +0000773}
774
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000775QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +0000776CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000777 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +0000778 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-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 Naroffe1b31fe2007-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 Begeman213541a2008-04-18 23:10:10 +0000787 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000788 baseType.getAsString(), SourceRange(CompLoc));
789 return QualType();
790 }
Nate Begeman8a997642008-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 Lattner88dca042007-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 Naroffe1b31fe2007-07-27 22:15:19 +0000810
Nate Begeman8a997642008-05-09 06:41:27 +0000811 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-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 Begeman213541a2008-04-18 23:10:10 +0000814 Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
Steve Naroffe1b31fe2007-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 Begeman8a997642008-05-09 06:41:27 +0000826 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-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 Begeman213541a2008-04-18 23:10:10 +0000829 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000830 baseType.getAsString(), SourceRange(CompLoc));
831 return QualType();
832 }
Nate Begeman8a997642008-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 Dunbarabee2d72008-09-30 17:22:47 +0000838 Diag(OpLoc, diag::err_ext_vector_component_requires_even,
839 baseType.getAsString(), SourceRange(CompLoc));
Nate Begeman8a997642008-05-09 06:41:27 +0000840 return QualType();
841 }
842
Steve Naroffe1b31fe2007-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 Begeman8a997642008-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 Naroffe1b31fe2007-07-27 22:15:19 +0000849 if (CompSize == 1)
850 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +0000851
Nate Begeman213541a2008-04-18 23:10:10 +0000852 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +0000853 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-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 Naroffbea0b342007-07-29 16:33:31 +0000858 }
859 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +0000860}
861
Daniel Dunbar2307d312008-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
Reid Spencer5f016e22007-07-11 17:01:13 +0000881Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +0000882ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000883 tok::TokenKind OpKind, SourceLocation MemberLoc,
884 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000885 Expr *BaseExpr = static_cast<Expr *>(Base);
886 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +0000887
888 // Perform default conversions.
889 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000890
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000891 QualType BaseType = BaseExpr->getType();
892 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +0000893
Chris Lattner68a057b2008-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.
Reid Spencer5f016e22007-07-11 17:01:13 +0000896 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +0000897 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +0000898 BaseType = PT->getPointeeType();
899 else
Chris Lattner2a01b722008-07-21 05:35:34 +0000900 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
901 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000902 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000903
Chris Lattner68a057b2008-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 Lattnerc8629632007-07-31 19:29:30 +0000906 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-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 Naroffe1b31fe2007-07-27 22:15:19 +0000912 FieldDecl *MemberDecl = RDecl->getMember(&Member);
913 if (!MemberDecl)
Chris Lattner2a01b722008-07-21 05:35:34 +0000914 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
915 BaseExpr->getSourceRange());
Eli Friedman51019072008-02-06 22:48:16 +0000916
917 // Figure out the type of the member; see C99 6.5.2.3p3
Eli Friedman64ec0cc2008-02-07 05:24:51 +0000918 // FIXME: Handle address space modifiers
Eli Friedman51019072008-02-06 22:48:16 +0000919 QualType MemberType = MemberDecl->getType();
920 unsigned combinedQualifiers =
Chris Lattnerf46699c2008-02-20 20:55:12 +0000921 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Eli Friedman51019072008-02-06 22:48:16 +0000922 MemberType = MemberType.getQualifiedType(combinedQualifiers);
923
Chris Lattner68a057b2008-07-21 04:36:39 +0000924 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
Eli Friedman51019072008-02-06 22:48:16 +0000925 MemberLoc, MemberType);
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000926 }
927
Chris Lattnera38e6b12008-07-21 04:59:05 +0000928 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
929 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +0000930 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
931 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
Fariborz Jahanian232220c2007-11-12 22:29:28 +0000932 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000933 OpKind == tok::arrow);
Chris Lattner2a01b722008-07-21 05:35:34 +0000934 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
Chris Lattner1f719742008-07-21 04:42:08 +0000935 IFTy->getDecl()->getName(), Member.getName(),
Chris Lattner2a01b722008-07-21 05:35:34 +0000936 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +0000937 }
938
Chris Lattnera38e6b12008-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 Dunbar7f8ea5c2008-08-30 05:35:15 +0000946
Daniel Dunbar2307d312008-09-03 01:05:41 +0000947 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +0000948 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
949 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
950
Daniel Dunbar2307d312008-09-03 01:05:41 +0000951 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-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 Dunbar2307d312008-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 Naroff7692ed62008-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 Dunbar2307d312008-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 Jahanian232220c2007-11-12 22:29:28 +00001005 }
Steve Naroff18bc1642008-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 Lattnerfb173ec2008-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 Lattner2a01b722008-07-21 05:35:34 +00001020 return Diag(MemberLoc, diag::err_ext_vector_component_access,
1021 BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-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 Lattner2a01b722008-07-21 05:35:34 +00001028 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1029 BaseType.getAsString(), BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001030}
1031
Steve Narofff69936d2007-09-16 03:34:24 +00001032/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001033/// This provides the location of the left/right parens and a list of comma
1034/// locations.
1035Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001036ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
Chris Lattner925e60d2007-12-28 05:29:59 +00001037 ExprTy **args, unsigned NumArgs,
Reid Spencer5f016e22007-07-11 17:01:13 +00001038 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +00001039 Expr *Fn = static_cast<Expr *>(fn);
1040 Expr **Args = reinterpret_cast<Expr**>(args);
1041 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001042 FunctionDecl *FDecl = NULL;
Douglas Gregor8e9bebd2008-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 Lattner04421082008-04-08 04:40:51 +00001100
1101 // Promote the function operand.
1102 UsualUnaryConversions(Fn);
1103
Chris Lattner925e60d2007-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 Lattner8123a952008-04-10 02:22:51 +00001106 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001107 Context.BoolTy, RParenLoc));
Steve Naroffdd972f22008-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 Lattner925e60d2007-12-28 05:29:59 +00001121 if (FuncT == 0)
Chris Lattnerad2018f2008-08-14 04:33:24 +00001122 return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1123 Fn->getSourceRange());
Chris Lattner925e60d2007-12-28 05:29:59 +00001124
1125 // We know the result type of the call, set it.
1126 TheCall->setType(FuncT->getResultType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001127
Chris Lattner925e60d2007-12-28 05:29:59 +00001128 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1130 // assignment, to the types of the corresponding parameter, ...
Chris Lattner925e60d2007-12-28 05:29:59 +00001131 unsigned NumArgsInProto = Proto->getNumArgs();
1132 unsigned NumArgsToCheck = NumArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001133
Chris Lattner04421082008-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 Lattner8123a952008-04-10 02:22:51 +00001137 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
Chris Lattner04421082008-04-08 04:40:51 +00001138 // Use default arguments for missing arguments
1139 NumArgsToCheck = NumArgsInProto;
Chris Lattner8123a952008-04-10 02:22:51 +00001140 TheCall->setNumArgs(NumArgsInProto);
Chris Lattner04421082008-04-08 04:40:51 +00001141 } else
Steve Naroffdd972f22008-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 Lattner04421082008-04-08 04:40:51 +00001146 Fn->getSourceRange());
1147 }
1148
Chris Lattner925e60d2007-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 Lattnerd472b312007-07-21 03:09:58 +00001153 Diag(Args[NumArgsInProto]->getLocStart(),
Steve Naroffdd972f22008-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 Lattnerd472b312007-07-21 03:09:58 +00001158 SourceRange(Args[NumArgsInProto]->getLocStart(),
Chris Lattner925e60d2007-12-28 05:29:59 +00001159 Args[NumArgs-1]->getLocEnd()));
1160 // This deletes the extra arguments.
1161 TheCall->setNumArgs(NumArgsInProto);
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 }
1163 NumArgsToCheck = NumArgsInProto;
1164 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001165
Reid Spencer5f016e22007-07-11 17:01:13 +00001166 // Continue to check argument types (even if we have too few/many args).
Chris Lattner925e60d2007-12-28 05:29:59 +00001167 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00001168 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner04421082008-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 Lattner5cf216b2008-01-04 18:04:52 +00001175 QualType ArgType = Arg->getType();
Steve Naroff700204c2007-07-24 21:46:40 +00001176
Chris Lattner925e60d2007-12-28 05:29:59 +00001177 // Compute implicit casts from the operand to the formal argument type.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001178 AssignConvertType ConvTy =
1179 CheckSingleAssignmentConstraints(ProtoArgType, Arg);
Chris Lattner925e60d2007-12-28 05:29:59 +00001180 TheCall->setArg(i, Arg);
Eli Friedmanf1c7b482008-09-02 05:09:35 +00001181
Chris Lattner5cf216b2008-01-04 18:04:52 +00001182 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1183 ArgType, Arg, "passing"))
1184 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001185 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001186
1187 // If this is a variadic call, handle args passed through "...".
1188 if (Proto->isVariadic()) {
Steve Naroffb291ab62007-08-28 23:30:39 +00001189 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattner925e60d2007-12-28 05:29:59 +00001190 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1191 Expr *Arg = Args[i];
1192 DefaultArgumentPromotion(Arg);
1193 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001194 }
Steve Naroffb291ab62007-08-28 23:30:39 +00001195 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001196 } else {
1197 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1198
Steve Naroffb291ab62007-08-28 23:30:39 +00001199 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001200 for (unsigned i = 0; i != NumArgs; i++) {
1201 Expr *Arg = Args[i];
1202 DefaultArgumentPromotion(Arg);
1203 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001204 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001206
Chris Lattner59907c42007-08-10 20:18:51 +00001207 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001208 if (FDecl)
1209 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001210
Chris Lattner925e60d2007-12-28 05:29:59 +00001211 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001212}
1213
1214Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001215ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +00001216 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001217 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001218 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001219 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001220 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +00001221 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +00001222
Eli Friedman6223c222008-05-20 05:22:08 +00001223 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001224 if (literalType->isVariableArrayType())
Eli Friedman6223c222008-05-20 05:22:08 +00001225 return Diag(LParenLoc,
1226 diag::err_variable_object_no_init,
1227 SourceRange(LParenLoc,
1228 literalExpr->getSourceRange().getEnd()));
1229 } else if (literalType->isIncompleteType()) {
1230 return Diag(LParenLoc,
1231 diag::err_typecheck_decl_incomplete_type,
1232 literalType.getAsString(),
1233 SourceRange(LParenLoc,
1234 literalExpr->getSourceRange().getEnd()));
1235 }
1236
Steve Naroffd0091aa2008-01-10 22:15:12 +00001237 if (CheckInitializerTypes(literalExpr, literalType))
Steve Naroff58d18212008-01-09 20:58:06 +00001238 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +00001239
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001240 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
Steve Naroffe9b12192008-01-14 18:19:28 +00001241 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001242 if (CheckForConstantInitializer(literalExpr, literalType))
1243 return true;
1244 }
Chris Lattner220ad7c2008-10-26 23:35:51 +00001245 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1246 isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001247}
1248
1249Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001250ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattner220ad7c2008-10-26 23:35:51 +00001251 InitListDesignations &Designators,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001252 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +00001253 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001254
Steve Naroff08d92e42007-09-15 18:49:24 +00001255 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001256 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001257
Chris Lattner418f6c72008-10-26 23:43:26 +00001258 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1259 Designators.hasAnyDesignators());
Chris Lattnerf0467b32008-04-02 04:24:33 +00001260 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1261 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001262}
1263
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001264/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001265bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001266 UsualUnaryConversions(castExpr);
1267
1268 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1269 // type needs to be scalar.
1270 if (castType->isVoidType()) {
1271 // Cast to void allows any expr type.
1272 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1273 // GCC struct/union extension: allow cast to self.
1274 if (Context.getCanonicalType(castType) !=
1275 Context.getCanonicalType(castExpr->getType()) ||
1276 (!castType->isStructureType() && !castType->isUnionType())) {
1277 // Reject any other conversions to non-scalar types.
1278 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1279 castType.getAsString(), castExpr->getSourceRange());
1280 }
1281
1282 // accept this, but emit an ext-warn.
1283 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1284 castType.getAsString(), castExpr->getSourceRange());
1285 } else if (!castExpr->getType()->isScalarType() &&
1286 !castExpr->getType()->isVectorType()) {
1287 return Diag(castExpr->getLocStart(),
1288 diag::err_typecheck_expect_scalar_operand,
1289 castExpr->getType().getAsString(),castExpr->getSourceRange());
1290 } else if (castExpr->getType()->isVectorType()) {
1291 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1292 return true;
1293 } else if (castType->isVectorType()) {
1294 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1295 return true;
1296 }
1297 return false;
1298}
1299
Chris Lattnerfe23e212007-12-20 00:44:32 +00001300bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00001301 assert(VectorTy->isVectorType() && "Not a vector type!");
1302
1303 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00001304 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00001305 return Diag(R.getBegin(),
1306 Ty->isVectorType() ?
1307 diag::err_invalid_conversion_between_vectors :
1308 diag::err_invalid_conversion_between_vector_and_integer,
1309 VectorTy.getAsString().c_str(),
1310 Ty.getAsString().c_str(), R);
1311 } else
1312 return Diag(R.getBegin(),
1313 diag::err_invalid_conversion_between_vector_and_scalar,
1314 VectorTy.getAsString().c_str(),
1315 Ty.getAsString().c_str(), R);
1316
1317 return false;
1318}
1319
Steve Naroff4aa88f82007-07-19 01:06:55 +00001320Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001321ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +00001322 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +00001323 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00001324
1325 Expr *castExpr = static_cast<Expr*>(Op);
1326 QualType castType = QualType::getFromOpaquePtr(Ty);
1327
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001328 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1329 return true;
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001330 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001331}
1332
Chris Lattnera21ddb32007-11-26 01:40:58 +00001333/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1334/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00001335inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00001336 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001337 UsualUnaryConversions(cond);
1338 UsualUnaryConversions(lex);
1339 UsualUnaryConversions(rex);
1340 QualType condT = cond->getType();
1341 QualType lexT = lex->getType();
1342 QualType rexT = rex->getType();
1343
Reid Spencer5f016e22007-07-11 17:01:13 +00001344 // first, check the condition.
Steve Naroff49b45262007-07-13 16:58:59 +00001345 if (!condT->isScalarType()) { // C99 6.5.15p2
1346 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1347 condT.getAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +00001348 return QualType();
1349 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001350
1351 // Now check the two expressions.
1352
1353 // If both operands have arithmetic type, do the usual arithmetic conversions
1354 // to find a common type: C99 6.5.15p3,5.
1355 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00001356 UsualArithmeticConversions(lex, rex);
1357 return lex->getType();
1358 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001359
1360 // If both operands are the same structure or union type, the result is that
1361 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001362 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00001363 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00001364 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00001365 // "If both the operands have structure or union type, the result has
1366 // that type." This implies that CV qualifiers are dropped.
1367 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001369
1370 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00001371 // The following || allows only one side to be void (a GCC-ism).
1372 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00001373 if (!lexT->isVoidType())
Steve Naroffe701c0a2008-05-12 21:44:38 +00001374 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1375 rex->getSourceRange());
1376 if (!rexT->isVoidType())
1377 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
Nuno Lopesd8de7252008-06-04 19:14:12 +00001378 lex->getSourceRange());
Eli Friedman0e724012008-06-04 19:47:51 +00001379 ImpCastExprToType(lex, Context.VoidTy);
1380 ImpCastExprToType(rex, Context.VoidTy);
1381 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00001382 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00001383 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1384 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001385 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1386 Context.isObjCObjectPointerType(lexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001387 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001388 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001389 return lexT;
1390 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001391 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1392 Context.isObjCObjectPointerType(rexT)) &&
Steve Naroff61f40a22008-09-10 19:17:48 +00001393 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001394 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00001395 return rexT;
1396 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00001397 // Handle the case where both operands are pointers before we handle null
1398 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001399 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1400 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1401 // get the "pointed to" types
1402 QualType lhptee = LHSPT->getPointeeType();
1403 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001404
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001405 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1406 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00001407 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001408 // Figure out necessary qualifiers (C99 6.5.15p6)
1409 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001410 QualType destType = Context.getPointerType(destPointee);
1411 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1412 ImpCastExprToType(rex, destType); // promote to void*
1413 return destType;
1414 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00001415 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00001416 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00001417 QualType destType = Context.getPointerType(destPointee);
1418 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1419 ImpCastExprToType(rex, destType); // promote to void*
1420 return destType;
1421 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001422
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001423 QualType compositeType = lexT;
1424
1425 // If either type is an Objective-C object type then check
1426 // compatibility according to Objective-C.
1427 if (Context.isObjCObjectPointerType(lexT) ||
1428 Context.isObjCObjectPointerType(rexT)) {
1429 // If both operands are interfaces and either operand can be
1430 // assigned to the other, use that type as the composite
1431 // type. This allows
1432 // xxx ? (A*) a : (B*) b
1433 // where B is a subclass of A.
1434 //
1435 // Additionally, as for assignment, if either type is 'id'
1436 // allow silent coercion. Finally, if the types are
1437 // incompatible then make sure to use 'id' as the composite
1438 // type so the result is acceptable for sending messages to.
1439
1440 // FIXME: This code should not be localized to here. Also this
1441 // should use a compatible check instead of abusing the
1442 // canAssignObjCInterfaces code.
1443 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1444 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1445 if (LHSIface && RHSIface &&
1446 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1447 compositeType = lexT;
1448 } else if (LHSIface && RHSIface &&
1449 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1450 compositeType = rexT;
1451 } else if (Context.isObjCIdType(lhptee) ||
1452 Context.isObjCIdType(rhptee)) {
1453 // FIXME: This code looks wrong, because isObjCIdType checks
1454 // the struct but getObjCIdType returns the pointer to
1455 // struct. This is horrible and should be fixed.
1456 compositeType = Context.getObjCIdType();
1457 } else {
1458 QualType incompatTy = Context.getObjCIdType();
1459 ImpCastExprToType(lex, incompatTy);
1460 ImpCastExprToType(rex, incompatTy);
1461 return incompatTy;
1462 }
1463 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1464 rhptee.getUnqualifiedType())) {
Steve Naroffc0ff1ca2008-02-01 22:44:48 +00001465 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001466 lexT.getAsString(), rexT.getAsString(),
1467 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001468 // In this situation, we assume void* type. No especially good
1469 // reason, but this is what gcc does, and we do have to pick
1470 // to get a consistent AST.
1471 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00001472 ImpCastExprToType(lex, incompatTy);
1473 ImpCastExprToType(rex, incompatTy);
1474 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001475 }
1476 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001477 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1478 // differently qualified versions of compatible types, the result type is
1479 // a pointer to an appropriately qualified version of the *composite*
1480 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00001481 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00001482 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00001483 ImpCastExprToType(lex, compositeType);
1484 ImpCastExprToType(rex, compositeType);
1485 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 }
1487 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00001488 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1489 // evaluates to "struct objc_object *" (and is handled above when comparing
1490 // id with statically typed objects).
1491 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1492 // GCC allows qualified id and any Objective-C type to devolve to
1493 // id. Currently localizing to here until clear this should be
1494 // part of ObjCQualifiedIdTypesAreCompatible.
1495 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1496 (lexT->isObjCQualifiedIdType() &&
1497 Context.isObjCObjectPointerType(rexT)) ||
1498 (rexT->isObjCQualifiedIdType() &&
1499 Context.isObjCObjectPointerType(lexT))) {
1500 // FIXME: This is not the correct composite type. This only
1501 // happens to work because id can more or less be used anywhere,
1502 // however this may change the type of method sends.
1503 // FIXME: gcc adds some type-checking of the arguments and emits
1504 // (confusing) incompatible comparison warnings in some
1505 // cases. Investigate.
1506 QualType compositeType = Context.getObjCIdType();
1507 ImpCastExprToType(lex, compositeType);
1508 ImpCastExprToType(rex, compositeType);
1509 return compositeType;
1510 }
1511 }
1512
Steve Naroff61f40a22008-09-10 19:17:48 +00001513 // Selection between block pointer types is ok as long as they are the same.
1514 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1515 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1516 return lexT;
1517
Chris Lattner70d67a92008-01-06 22:42:25 +00001518 // Otherwise, the operands are not compatible.
Reid Spencer5f016e22007-07-11 17:01:13 +00001519 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
Steve Naroff49b45262007-07-13 16:58:59 +00001520 lexT.getAsString(), rexT.getAsString(),
1521 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001522 return QualType();
1523}
1524
Steve Narofff69936d2007-09-16 03:34:24 +00001525/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00001526/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00001527Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 SourceLocation ColonLoc,
1529 ExprTy *Cond, ExprTy *LHS,
1530 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00001531 Expr *CondExpr = (Expr *) Cond;
1532 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001533
1534 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1535 // was the condition.
1536 bool isLHSNull = LHSExpr == 0;
1537 if (isLHSNull)
1538 LHSExpr = CondExpr;
1539
Chris Lattner26824902007-07-16 21:39:03 +00001540 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1541 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 if (result.isNull())
1543 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00001544 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1545 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001546}
1547
Reid Spencer5f016e22007-07-11 17:01:13 +00001548
1549// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1550// being closely modeled after the C99 spec:-). The odd characteristic of this
1551// routine is it effectively iqnores the qualifiers on the top level pointee.
1552// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1553// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001554Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001555Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1556 QualType lhptee, rhptee;
1557
1558 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001559 lhptee = lhsType->getAsPointerType()->getPointeeType();
1560 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001561
1562 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00001563 lhptee = Context.getCanonicalType(lhptee);
1564 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00001565
Chris Lattner5cf216b2008-01-04 18:04:52 +00001566 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001567
1568 // C99 6.5.16.1p1: This following citation is common to constraints
1569 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1570 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00001571 // FIXME: Handle ASQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00001572 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00001573 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00001574
1575 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1576 // incomplete type and the other is a pointer to a qualified or unqualified
1577 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001578 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001579 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001580 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001581
1582 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001583 assert(rhptee->isFunctionType());
1584 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001585 }
1586
1587 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00001588 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00001589 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001590
1591 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001592 assert(lhptee->isFunctionType());
1593 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001594 }
Eli Friedman3d815e72008-08-22 00:56:42 +00001595
1596 // Check for ObjC interfaces
1597 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1598 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1599 if (LHSIface && RHSIface &&
1600 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1601 return ConvTy;
1602
1603 // ID acts sort of like void* for ObjC interfaces
1604 if (LHSIface && Context.isObjCIdType(rhptee))
1605 return ConvTy;
1606 if (RHSIface && Context.isObjCIdType(lhptee))
1607 return ConvTy;
1608
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1610 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00001611 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1612 rhptee.getUnqualifiedType()))
1613 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00001614 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001615}
1616
Steve Naroff1c7d0672008-09-04 15:10:53 +00001617/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1618/// block pointer types are compatible or whether a block and normal pointer
1619/// are compatible. It is more restrict than comparing two function pointer
1620// types.
1621Sema::AssignConvertType
1622Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1623 QualType rhsType) {
1624 QualType lhptee, rhptee;
1625
1626 // get the "pointed to" type (ignoring qualifiers at the top level)
1627 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1628 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1629
1630 // make sure we operate on the canonical type
1631 lhptee = Context.getCanonicalType(lhptee);
1632 rhptee = Context.getCanonicalType(rhptee);
1633
1634 AssignConvertType ConvTy = Compatible;
1635
1636 // For blocks we enforce that qualifiers are identical.
1637 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1638 ConvTy = CompatiblePointerDiscardsQualifiers;
1639
1640 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1641 return IncompatibleBlockPointer;
1642 return ConvTy;
1643}
1644
Reid Spencer5f016e22007-07-11 17:01:13 +00001645/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1646/// has code to accommodate several GCC extensions when type checking
1647/// pointers. Here are some objectionable examples that GCC considers warnings:
1648///
1649/// int a, *pint;
1650/// short *pshort;
1651/// struct foo *pfoo;
1652///
1653/// pint = pshort; // warning: assignment from incompatible pointer type
1654/// a = pint; // warning: assignment makes integer from pointer without a cast
1655/// pint = a; // warning: assignment makes pointer from integer without a cast
1656/// pint = pfoo; // warning: assignment from incompatible pointer type
1657///
1658/// As a result, the code for dealing with pointers is more complex than the
1659/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00001660///
Chris Lattner5cf216b2008-01-04 18:04:52 +00001661Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00001662Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00001663 // Get canonical types. We're not formatting these types, just comparing
1664 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001665 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1666 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001667
1668 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00001669 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00001670
Douglas Gregor9d293df2008-10-28 00:22:11 +00001671 // If the left-hand side is a reference type, then we are in a
1672 // (rare!) case where we've allowed the use of references in C,
1673 // e.g., as a parameter type in a built-in function. In this case,
1674 // just make sure that the type referenced is compatible with the
1675 // right-hand side type. The caller is responsible for adjusting
1676 // lhsType so that the resulting expression does not have reference
1677 // type.
1678 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
1679 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00001680 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001681 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001682 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001683
Chris Lattnereca7be62008-04-07 05:30:13 +00001684 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1685 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001686 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00001687 // Relax integer conversions like we do for pointers below.
1688 if (rhsType->isIntegerType())
1689 return IntToPointer;
1690 if (lhsType->isIntegerType())
1691 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00001692 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00001693 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00001694
Nate Begemanbe2341d2008-07-14 18:02:46 +00001695 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001696 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00001697 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1698 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00001699 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001700
Nate Begemanbe2341d2008-07-14 18:02:46 +00001701 // If we are allowing lax vector conversions, and LHS and RHS are both
1702 // vectors, the total size only needs to be the same. This is a bitcast;
1703 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00001704 if (getLangOptions().LaxVectorConversions &&
1705 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001706 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1707 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00001708 }
1709 return Incompatible;
1710 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001711
Chris Lattnere8b3e962008-01-04 23:32:24 +00001712 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001713 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001714
Chris Lattner78eca282008-04-07 06:49:41 +00001715 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001716 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001717 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001718
Chris Lattner78eca282008-04-07 06:49:41 +00001719 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001720 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001721
Steve Naroffb4406862008-09-29 18:10:17 +00001722 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00001723 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Steve Naroff1c7d0672008-09-04 15:10:53 +00001724 return BlockVoidPointer;
Steve Naroffb4406862008-09-29 18:10:17 +00001725
1726 // Treat block pointers as objects.
1727 if (getLangOptions().ObjC1 &&
1728 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1729 return Compatible;
1730 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001731 return Incompatible;
1732 }
1733
1734 if (isa<BlockPointerType>(lhsType)) {
1735 if (rhsType->isIntegerType())
1736 return IntToPointer;
1737
Steve Naroffb4406862008-09-29 18:10:17 +00001738 // Treat block pointers as objects.
1739 if (getLangOptions().ObjC1 &&
1740 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1741 return Compatible;
1742
Steve Naroff1c7d0672008-09-04 15:10:53 +00001743 if (rhsType->isBlockPointerType())
1744 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1745
1746 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1747 if (RHSPT->getPointeeType()->isVoidType())
1748 return BlockVoidPointer;
1749 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00001750 return Incompatible;
1751 }
1752
Chris Lattner78eca282008-04-07 06:49:41 +00001753 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001754 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001755 if (lhsType == Context.BoolTy)
1756 return Compatible;
1757
1758 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00001759 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00001760
Chris Lattner78eca282008-04-07 06:49:41 +00001761 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001762 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00001763
1764 if (isa<BlockPointerType>(lhsType) &&
1765 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1766 return BlockVoidPointer;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001767 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00001768 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00001769
Chris Lattnerfc144e22008-01-04 23:18:45 +00001770 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00001771 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00001772 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00001773 }
1774 return Incompatible;
1775}
1776
Chris Lattner5cf216b2008-01-04 18:04:52 +00001777Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001778Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001779 if (getLangOptions().CPlusPlus) {
1780 if (!lhsType->isRecordType()) {
1781 // C++ 5.17p3: If the left operand is not of class type, the
1782 // expression is implicitly converted (C++ 4) to the
1783 // cv-unqualified type of the left operand.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001784 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType()))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001785 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001786 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00001787 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001788 }
1789
1790 // FIXME: Currently, we fall through and treat C++ classes like C
1791 // structures.
1792 }
1793
Steve Naroff529a4ad2007-11-27 17:58:44 +00001794 // C99 6.5.16.1p1: the left operand is a pointer and the right is
1795 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00001796 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1797 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00001798 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001799 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00001800 return Compatible;
1801 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00001802
1803 // We don't allow conversion of non-null-pointer constants to integers.
1804 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1805 return IntToBlockPointer;
1806
Chris Lattner943140e2007-10-16 02:55:40 +00001807 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00001808 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00001809 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00001810 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00001811 //
Douglas Gregor9d293df2008-10-28 00:22:11 +00001812 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00001813 if (!lhsType->isReferenceType())
1814 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00001815
Chris Lattner5cf216b2008-01-04 18:04:52 +00001816 Sema::AssignConvertType result =
1817 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00001818
1819 // C99 6.5.16.1p2: The value of the right operand is converted to the
1820 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00001821 // CheckAssignmentConstraints allows the left-hand side to be a reference,
1822 // so that we can use references in built-in functions even in C.
1823 // The getNonReferenceType() call makes sure that the resulting expression
1824 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00001825 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00001826 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00001827 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00001828}
1829
Chris Lattner5cf216b2008-01-04 18:04:52 +00001830Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00001831Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1832 return CheckAssignmentConstraints(lhsType, rhsType);
1833}
1834
Chris Lattnerca5eede2007-12-12 05:47:28 +00001835QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001836 Diag(loc, diag::err_typecheck_invalid_operands,
1837 lex->getType().getAsString(), rex->getType().getAsString(),
1838 lex->getSourceRange(), rex->getSourceRange());
Chris Lattnerca5eede2007-12-12 05:47:28 +00001839 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001840}
1841
Steve Naroff49b45262007-07-13 16:58:59 +00001842inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1843 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00001844 // For conversion purposes, we ignore any qualifiers.
1845 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00001846 QualType lhsType =
1847 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1848 QualType rhsType =
1849 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001850
Nate Begemanbe2341d2008-07-14 18:02:46 +00001851 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00001852 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00001853 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00001854
Nate Begemanbe2341d2008-07-14 18:02:46 +00001855 // Handle the case of a vector & extvector type of the same size and element
1856 // type. It would be nice if we only had one vector type someday.
1857 if (getLangOptions().LaxVectorConversions)
1858 if (const VectorType *LV = lhsType->getAsVectorType())
1859 if (const VectorType *RV = rhsType->getAsVectorType())
1860 if (LV->getElementType() == RV->getElementType() &&
1861 LV->getNumElements() == RV->getNumElements())
1862 return lhsType->isExtVectorType() ? lhsType : rhsType;
1863
1864 // If the lhs is an extended vector and the rhs is a scalar of the same type
1865 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001866 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001867 QualType eltType = V->getElementType();
1868
1869 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1870 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1871 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001872 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001873 return lhsType;
1874 }
1875 }
1876
Nate Begemanbe2341d2008-07-14 18:02:46 +00001877 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00001878 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00001879 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00001880 QualType eltType = V->getElementType();
1881
1882 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1883 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1884 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00001885 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001886 return rhsType;
1887 }
1888 }
1889
Reid Spencer5f016e22007-07-11 17:01:13 +00001890 // You cannot convert between vector values of different size.
1891 Diag(loc, diag::err_typecheck_vector_not_convertable,
1892 lex->getType().getAsString(), rex->getType().getAsString(),
1893 lex->getSourceRange(), rex->getSourceRange());
1894 return QualType();
1895}
1896
1897inline QualType Sema::CheckMultiplyDivideOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001898 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001899{
Steve Naroff90045e82007-07-13 23:32:42 +00001900 QualType lhsType = lex->getType(), rhsType = rex->getType();
1901
1902 if (lhsType->isVectorType() || rhsType->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001903 return CheckVectorOperands(loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00001904
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001905 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001906
Steve Naroffa4332e22007-07-17 00:58:39 +00001907 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001908 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001909 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001910}
1911
1912inline QualType Sema::CheckRemainderOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001913 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001914{
Steve Naroff90045e82007-07-13 23:32:42 +00001915 QualType lhsType = lex->getType(), rhsType = rex->getType();
1916
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001917 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001918
Steve Naroffa4332e22007-07-17 00:58:39 +00001919 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001920 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00001921 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001922}
1923
1924inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001925 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00001926{
Steve Naroff3e5e5562007-07-16 22:23:01 +00001927 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Steve Naroff49b45262007-07-13 16:58:59 +00001928 return CheckVectorOperands(loc, lex, rex);
1929
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001930 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00001931
Reid Spencer5f016e22007-07-11 17:01:13 +00001932 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001933 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001934 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00001935
Eli Friedmand72d16e2008-05-18 18:08:51 +00001936 // Put any potential pointer into PExp
1937 Expr* PExp = lex, *IExp = rex;
1938 if (IExp->getType()->isPointerType())
1939 std::swap(PExp, IExp);
1940
1941 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1942 if (IExp->getType()->isIntegerType()) {
1943 // Check for arithmetic on pointers to incomplete types
1944 if (!PTy->getPointeeType()->isObjectType()) {
1945 if (PTy->getPointeeType()->isVoidType()) {
1946 Diag(loc, diag::ext_gnu_void_ptr,
1947 lex->getSourceRange(), rex->getSourceRange());
1948 } else {
1949 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1950 lex->getType().getAsString(), lex->getSourceRange());
1951 return QualType();
1952 }
1953 }
1954 return PExp->getType();
1955 }
1956 }
1957
Chris Lattnerca5eede2007-12-12 05:47:28 +00001958 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001959}
1960
Chris Lattnereca7be62008-04-07 05:30:13 +00001961// C99 6.5.6
1962QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1963 SourceLocation loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00001964 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001965 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00001966
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001967 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00001968
Chris Lattner6e4ab612007-12-09 21:53:25 +00001969 // Enforce type constraints: C99 6.5.6p3.
1970
1971 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00001972 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00001973 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00001974
1975 // Either ptr - int or ptr - ptr.
1976 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00001977 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00001978
Chris Lattner6e4ab612007-12-09 21:53:25 +00001979 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00001980 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001981 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00001982 if (lpointee->isVoidType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00001983 Diag(loc, diag::ext_gnu_void_ptr,
1984 lex->getSourceRange(), rex->getSourceRange());
1985 } else {
1986 Diag(loc, diag::err_typecheck_sub_ptr_object,
1987 lex->getType().getAsString(), lex->getSourceRange());
1988 return QualType();
1989 }
1990 }
1991
1992 // The result type of a pointer-int computation is the pointer type.
1993 if (rex->getType()->isIntegerType())
1994 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00001995
Chris Lattner6e4ab612007-12-09 21:53:25 +00001996 // Handle pointer-pointer subtractions.
1997 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00001998 QualType rpointee = RHSPTy->getPointeeType();
1999
Chris Lattner6e4ab612007-12-09 21:53:25 +00002000 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00002001 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002002 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002003 if (rpointee->isVoidType()) {
2004 if (!lpointee->isVoidType())
Chris Lattner6e4ab612007-12-09 21:53:25 +00002005 Diag(loc, diag::ext_gnu_void_ptr,
2006 lex->getSourceRange(), rex->getSourceRange());
2007 } else {
2008 Diag(loc, diag::err_typecheck_sub_ptr_object,
2009 rex->getType().getAsString(), rex->getSourceRange());
2010 return QualType();
2011 }
2012 }
2013
2014 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00002015 if (!Context.typesAreCompatible(
2016 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2017 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002018 Diag(loc, diag::err_typecheck_sub_ptr_compatible,
2019 lex->getType().getAsString(), rex->getType().getAsString(),
2020 lex->getSourceRange(), rex->getSourceRange());
2021 return QualType();
2022 }
2023
2024 return Context.getPointerDiffType();
2025 }
2026 }
2027
Chris Lattnerca5eede2007-12-12 05:47:28 +00002028 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002029}
2030
Chris Lattnereca7be62008-04-07 05:30:13 +00002031// C99 6.5.7
2032QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2033 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002034 // C99 6.5.7p2: Each of the operands shall have integer type.
2035 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
2036 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002037
Chris Lattnerca5eede2007-12-12 05:47:28 +00002038 // Shifts don't perform usual arithmetic conversions, they just do integer
2039 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002040 if (!isCompAssign)
2041 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002042 UsualUnaryConversions(rex);
2043
2044 // "The type of the result is that of the promoted left operand."
2045 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002046}
2047
Eli Friedman3d815e72008-08-22 00:56:42 +00002048static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2049 ASTContext& Context) {
2050 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2051 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2052 // ID acts sort of like void* for ObjC interfaces
2053 if (LHSIface && Context.isObjCIdType(RHS))
2054 return true;
2055 if (RHSIface && Context.isObjCIdType(LHS))
2056 return true;
2057 if (!LHSIface || !RHSIface)
2058 return false;
2059 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2060 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2061}
2062
Chris Lattnereca7be62008-04-07 05:30:13 +00002063// C99 6.5.8
2064QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
2065 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002066 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2067 return CheckVectorCompareOperands(lex, rex, loc, isRelational);
2068
Chris Lattnera5937dd2007-08-26 01:18:55 +00002069 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002070 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2071 UsualArithmeticConversions(lex, rex);
2072 else {
2073 UsualUnaryConversions(lex);
2074 UsualUnaryConversions(rex);
2075 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002076 QualType lType = lex->getType();
2077 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002078
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002079 // For non-floating point types, check for self-comparisons of the form
2080 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2081 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002082 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002083 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2084 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002085 if (DRL->getDecl() == DRR->getDecl())
2086 Diag(loc, diag::warn_selfcomparison);
2087 }
2088
Chris Lattnera5937dd2007-08-26 01:18:55 +00002089 if (isRelational) {
2090 if (lType->isRealType() && rType->isRealType())
2091 return Context.IntTy;
2092 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002093 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002094 if (lType->isFloatingType()) {
2095 assert (rType->isFloatingType());
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002096 CheckFloatComparison(loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002097 }
2098
Chris Lattnera5937dd2007-08-26 01:18:55 +00002099 if (lType->isArithmeticType() && rType->isArithmeticType())
2100 return Context.IntTy;
2101 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002102
Chris Lattnerd28f8152007-08-26 01:10:14 +00002103 bool LHSIsNull = lex->isNullPointerConstant(Context);
2104 bool RHSIsNull = rex->isNullPointerConstant(Context);
2105
Chris Lattnera5937dd2007-08-26 01:18:55 +00002106 // All of the following pointer related warnings are GCC extensions, except
2107 // when handling null pointer constants. One day, we can consider making them
2108 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002109 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002110 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002111 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002112 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002113 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002114
Steve Naroff66296cb2007-11-13 14:57:38 +00002115 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002116 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2117 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002118 RCanPointeeTy.getUnqualifiedType()) &&
2119 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002120 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2121 lType.getAsString(), rType.getAsString(),
2122 lex->getSourceRange(), rex->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002123 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002124 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002125 return Context.IntTy;
2126 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002127 // Handle block pointer types.
2128 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2129 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2130 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2131
2132 if (!LHSIsNull && !RHSIsNull &&
2133 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2134 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2135 lType.getAsString(), rType.getAsString(),
2136 lex->getSourceRange(), rex->getSourceRange());
2137 }
2138 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2139 return Context.IntTy;
2140 }
Steve Naroff59f53942008-09-28 01:11:11 +00002141 // Allow block pointers to be compared with null pointer constants.
2142 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2143 (lType->isPointerType() && rType->isBlockPointerType())) {
2144 if (!LHSIsNull && !RHSIsNull) {
2145 Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2146 lType.getAsString(), rType.getAsString(),
2147 lex->getSourceRange(), rex->getSourceRange());
2148 }
2149 ImpCastExprToType(rex, lType); // promote the pointer to pointer
2150 return Context.IntTy;
2151 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002152
Steve Naroff20373222008-06-03 14:04:54 +00002153 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00002154 if (lType->isPointerType() || rType->isPointerType()) {
2155 if (!Context.typesAreCompatible(lType, rType)) {
2156 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2157 lType.getAsString(), rType.getAsString(),
2158 lex->getSourceRange(), rex->getSourceRange());
2159 ImpCastExprToType(rex, lType);
2160 return Context.IntTy;
2161 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002162 ImpCastExprToType(rex, lType);
Steve Naroff8970fea2008-10-22 22:40:28 +00002163 return Context.IntTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00002164 }
Steve Naroff20373222008-06-03 14:04:54 +00002165 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2166 ImpCastExprToType(rex, lType);
2167 return Context.IntTy;
Steve Naroff39579072008-10-14 22:18:38 +00002168 } else {
2169 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
2170 Diag(loc, diag::warn_incompatible_qualified_id_operands,
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002171 lType.getAsString(), rType.getAsString(),
Steve Naroff39579072008-10-14 22:18:38 +00002172 lex->getSourceRange(), rex->getSourceRange());
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002173 ImpCastExprToType(rex, lType);
Steve Naroff8970fea2008-10-22 22:40:28 +00002174 return Context.IntTy;
Steve Naroff39579072008-10-14 22:18:38 +00002175 }
Steve Naroff20373222008-06-03 14:04:54 +00002176 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00002177 }
Steve Naroff20373222008-06-03 14:04:54 +00002178 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2179 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002180 if (!RHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002181 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2182 lType.getAsString(), rType.getAsString(),
2183 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00002184 ImpCastExprToType(rex, lType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002185 return Context.IntTy;
2186 }
Steve Naroff20373222008-06-03 14:04:54 +00002187 if (lType->isIntegerType() &&
2188 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002189 if (!LHSIsNull)
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002190 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2191 lType.getAsString(), rType.getAsString(),
2192 lex->getSourceRange(), rex->getSourceRange());
Chris Lattner1e0a3902008-01-16 19:17:22 +00002193 ImpCastExprToType(lex, rType); // promote the integer to pointer
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002194 return Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002195 }
Steve Naroff39218df2008-09-04 16:56:14 +00002196 // Handle block pointers.
2197 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2198 if (!RHSIsNull)
2199 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2200 lType.getAsString(), rType.getAsString(),
2201 lex->getSourceRange(), rex->getSourceRange());
2202 ImpCastExprToType(rex, lType); // promote the integer to pointer
2203 return Context.IntTy;
2204 }
2205 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2206 if (!LHSIsNull)
2207 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2208 lType.getAsString(), rType.getAsString(),
2209 lex->getSourceRange(), rex->getSourceRange());
2210 ImpCastExprToType(lex, rType); // promote the integer to pointer
2211 return Context.IntTy;
2212 }
Chris Lattnerca5eede2007-12-12 05:47:28 +00002213 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002214}
2215
Nate Begemanbe2341d2008-07-14 18:02:46 +00002216/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2217/// operates on extended vector types. Instead of producing an IntTy result,
2218/// like a scalar comparison, a vector comparison produces a vector of integer
2219/// types.
2220QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2221 SourceLocation loc,
2222 bool isRelational) {
2223 // Check to make sure we're operating on vectors of the same type and width,
2224 // Allowing one side to be a scalar of element type.
2225 QualType vType = CheckVectorOperands(loc, lex, rex);
2226 if (vType.isNull())
2227 return vType;
2228
2229 QualType lType = lex->getType();
2230 QualType rType = rex->getType();
2231
2232 // For non-floating point types, check for self-comparisons of the form
2233 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2234 // often indicate logic errors in the program.
2235 if (!lType->isFloatingType()) {
2236 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2237 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2238 if (DRL->getDecl() == DRR->getDecl())
2239 Diag(loc, diag::warn_selfcomparison);
2240 }
2241
2242 // Check for comparisons of floating point operands using != and ==.
2243 if (!isRelational && lType->isFloatingType()) {
2244 assert (rType->isFloatingType());
2245 CheckFloatComparison(loc,lex,rex);
2246 }
2247
2248 // Return the type for the comparison, which is the same as vector type for
2249 // integer vectors, or an integer type of identical size and number of
2250 // elements for floating point vectors.
2251 if (lType->isIntegerType())
2252 return lType;
2253
2254 const VectorType *VTy = lType->getAsVectorType();
2255
2256 // FIXME: need to deal with non-32b int / non-64b long long
2257 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2258 if (TypeSize == 32) {
2259 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2260 }
2261 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2262 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2263}
2264
Reid Spencer5f016e22007-07-11 17:01:13 +00002265inline QualType Sema::CheckBitwiseOperands(
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002266 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002267{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002268 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002269 return CheckVectorOperands(loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002270
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002271 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002272
Steve Naroffa4332e22007-07-17 00:58:39 +00002273 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002274 return compType;
Chris Lattnerca5eede2007-12-12 05:47:28 +00002275 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002276}
2277
2278inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Steve Naroff49b45262007-07-13 16:58:59 +00002279 Expr *&lex, Expr *&rex, SourceLocation loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00002280{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002281 UsualUnaryConversions(lex);
2282 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002283
Eli Friedman5773a6c2008-05-13 20:16:47 +00002284 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002285 return Context.IntTy;
Chris Lattnerca5eede2007-12-12 05:47:28 +00002286 return InvalidOperands(loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002287}
2288
2289inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
Steve Narofff1120de2007-08-24 22:33:52 +00002290 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002291{
2292 QualType lhsType = lex->getType();
2293 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
Chris Lattner28be73f2008-07-26 21:30:36 +00002294 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002295
2296 switch (mlval) { // C99 6.5.16p2
Chris Lattner5cf216b2008-01-04 18:04:52 +00002297 case Expr::MLV_Valid:
2298 break;
2299 case Expr::MLV_ConstQualified:
2300 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2301 return QualType();
2302 case Expr::MLV_ArrayType:
2303 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2304 lhsType.getAsString(), lex->getSourceRange());
2305 return QualType();
2306 case Expr::MLV_NotObjectType:
2307 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2308 lhsType.getAsString(), lex->getSourceRange());
2309 return QualType();
2310 case Expr::MLV_InvalidExpression:
2311 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2312 lex->getSourceRange());
2313 return QualType();
2314 case Expr::MLV_IncompleteType:
2315 case Expr::MLV_IncompleteVoidType:
2316 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2317 lhsType.getAsString(), lex->getSourceRange());
2318 return QualType();
2319 case Expr::MLV_DuplicateVectorComponents:
2320 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2321 lex->getSourceRange());
2322 return QualType();
Steve Naroff4f6a7d72008-09-26 14:41:28 +00002323 case Expr::MLV_NotBlockQualified:
2324 Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2325 lex->getSourceRange());
2326 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002327 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00002328
Chris Lattner5cf216b2008-01-04 18:04:52 +00002329 AssignConvertType ConvTy;
Chris Lattner2c156472008-08-21 18:04:13 +00002330 if (compoundType.isNull()) {
2331 // Simple assignment "x = y".
Chris Lattner5cf216b2008-01-04 18:04:52 +00002332 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
Chris Lattner2c156472008-08-21 18:04:13 +00002333
2334 // If the RHS is a unary plus or minus, check to see if they = and + are
2335 // right next to each other. If so, the user may have typo'd "x =+ 4"
2336 // instead of "x += 4".
2337 Expr *RHSCheck = rex;
2338 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2339 RHSCheck = ICE->getSubExpr();
2340 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2341 if ((UO->getOpcode() == UnaryOperator::Plus ||
2342 UO->getOpcode() == UnaryOperator::Minus) &&
2343 loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2344 // Only if the two operators are exactly adjacent.
2345 loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2346 Diag(loc, diag::warn_not_compound_assign,
2347 UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2348 SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2349 }
2350 } else {
2351 // Compound assignment "x += y"
Chris Lattner5cf216b2008-01-04 18:04:52 +00002352 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
Chris Lattner2c156472008-08-21 18:04:13 +00002353 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00002354
2355 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2356 rex, "assigning"))
2357 return QualType();
2358
Reid Spencer5f016e22007-07-11 17:01:13 +00002359 // C99 6.5.16p3: The type of an assignment expression is the type of the
2360 // left operand unless the left operand has qualified type, in which case
2361 // it is the unqualified version of the type of the left operand.
2362 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2363 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002364 // C++ 5.17p1: the type of the assignment expression is that of its left
2365 // oprdu.
Chris Lattner5cf216b2008-01-04 18:04:52 +00002366 return lhsType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002367}
2368
2369inline QualType Sema::CheckCommaOperands( // C99 6.5.17
Steve Naroff49b45262007-07-13 16:58:59 +00002370 Expr *&lex, Expr *&rex, SourceLocation loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00002371
2372 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2373 DefaultFunctionArrayConversion(rex);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002374 return rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002375}
2376
Steve Naroff49b45262007-07-13 16:58:59 +00002377/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2378/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Reid Spencer5f016e22007-07-11 17:01:13 +00002379QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff49b45262007-07-13 16:58:59 +00002380 QualType resType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002381 assert(!resType.isNull() && "no type for increment/decrement expression");
2382
Steve Naroff084f9ed2007-08-24 17:20:07 +00002383 // C99 6.5.2.4p1: We allow complex as a GCC extension.
Steve Naroffd848a382007-11-11 14:15:57 +00002384 if (const PointerType *pt = resType->getAsPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00002385 if (pt->getPointeeType()->isVoidType()) {
2386 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2387 } else if (!pt->getPointeeType()->isObjectType()) {
2388 // C99 6.5.2.4p2, 6.5.6p2
Reid Spencer5f016e22007-07-11 17:01:13 +00002389 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2390 resType.getAsString(), op->getSourceRange());
2391 return QualType();
2392 }
Steve Naroff084f9ed2007-08-24 17:20:07 +00002393 } else if (!resType->isRealType()) {
2394 if (resType->isComplexType())
2395 // C99 does not support ++/-- on complex types.
2396 Diag(OpLoc, diag::ext_integer_increment_complex,
2397 resType.getAsString(), op->getSourceRange());
2398 else {
2399 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2400 resType.getAsString(), op->getSourceRange());
2401 return QualType();
2402 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002403 }
Steve Naroffdd10e022007-08-23 21:37:33 +00002404 // At this point, we know we have a real, complex or pointer type.
2405 // Now make sure the operand is a modifiable lvalue.
Chris Lattner28be73f2008-07-26 21:30:36 +00002406 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002407 if (mlval != Expr::MLV_Valid) {
2408 // FIXME: emit a more precise diagnostic...
2409 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2410 op->getSourceRange());
2411 return QualType();
2412 }
2413 return resType;
2414}
2415
Anders Carlsson369dee42008-02-01 07:15:58 +00002416/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00002417/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002418/// where the declaration is needed for type checking. We only need to
2419/// handle cases when the expression references a function designator
2420/// or is an lvalue. Here are some examples:
2421/// - &(x) => x
2422/// - &*****f => f for f a function designator.
2423/// - &s.xx => s
2424/// - &s.zz[1].yy -> s, if zz is an array
2425/// - *(x + 1) -> x, if x is an array
2426/// - &"123"[2] -> 0
2427/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002428static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002429 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002430 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002431 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002432 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00002433 // Fields cannot be declared with a 'register' storage class.
2434 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002435 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00002436 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00002437 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00002438 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002439 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00002440
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002441 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00002442 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00002443 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00002444 return 0;
2445 else
2446 return VD;
2447 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002448 case Stmt::UnaryOperatorClass: {
2449 UnaryOperator *UO = cast<UnaryOperator>(E);
2450
2451 switch(UO->getOpcode()) {
2452 case UnaryOperator::Deref: {
2453 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002454 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2455 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2456 if (!VD || VD->getType()->isPointerType())
2457 return 0;
2458 return VD;
2459 }
2460 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00002461 }
2462 case UnaryOperator::Real:
2463 case UnaryOperator::Imag:
2464 case UnaryOperator::Extension:
2465 return getPrimaryDecl(UO->getSubExpr());
2466 default:
2467 return 0;
2468 }
2469 }
2470 case Stmt::BinaryOperatorClass: {
2471 BinaryOperator *BO = cast<BinaryOperator>(E);
2472
2473 // Handle cases involving pointer arithmetic. The result of an
2474 // Assign or AddAssign is not an lvalue so they can be ignored.
2475
2476 // (x + n) or (n + x) => x
2477 if (BO->getOpcode() == BinaryOperator::Add) {
2478 if (BO->getLHS()->getType()->isPointerType()) {
2479 return getPrimaryDecl(BO->getLHS());
2480 } else if (BO->getRHS()->getType()->isPointerType()) {
2481 return getPrimaryDecl(BO->getRHS());
2482 }
2483 }
2484
2485 return 0;
2486 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002487 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00002488 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00002489 case Stmt::ImplicitCastExprClass:
2490 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002491 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00002492 default:
2493 return 0;
2494 }
2495}
2496
2497/// CheckAddressOfOperand - The operand of & must be either a function
2498/// designator or an lvalue designating an object. If it is an lvalue, the
2499/// object cannot be declared with storage class register or be a bit field.
2500/// Note: The usual conversions are *not* applied to the operand of the &
2501/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2502QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroff08f19672008-01-13 17:10:08 +00002503 if (getLangOptions().C99) {
2504 // Implement C99-only parts of addressof rules.
2505 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2506 if (uOp->getOpcode() == UnaryOperator::Deref)
2507 // Per C99 6.5.3.2, the address of a deref always returns a valid result
2508 // (assuming the deref expression is valid).
2509 return uOp->getSubExpr()->getType();
2510 }
2511 // Technically, there should be a check for array subscript
2512 // expressions here, but the result of one is always an lvalue anyway.
2513 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002514 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00002515 Expr::isLvalueResult lval = op->isLvalue(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00002516
2517 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00002518 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2519 // FIXME: emit more specific diag...
Reid Spencer5f016e22007-07-11 17:01:13 +00002520 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2521 op->getSourceRange());
2522 return QualType();
2523 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00002524 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2525 if (MemExpr->getMemberDecl()->isBitField()) {
2526 Diag(OpLoc, diag::err_typecheck_address_of,
2527 std::string("bit-field"), op->getSourceRange());
2528 return QualType();
2529 }
2530 // Check for Apple extension for accessing vector components.
2531 } else if (isa<ArraySubscriptExpr>(op) &&
2532 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2533 Diag(OpLoc, diag::err_typecheck_address_of,
2534 std::string("vector"), op->getSourceRange());
2535 return QualType();
2536 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00002537 // We have an lvalue with a decl. Make sure the decl is not declared
2538 // with the register storage-class specifier.
2539 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2540 if (vd->getStorageClass() == VarDecl::Register) {
Steve Naroffbcb2b612008-02-29 23:30:25 +00002541 Diag(OpLoc, diag::err_typecheck_address_of,
2542 std::string("register variable"), op->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002543 return QualType();
2544 }
2545 } else
2546 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002547 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00002548
Reid Spencer5f016e22007-07-11 17:01:13 +00002549 // If the operand has type "type", the result has type "pointer to type".
2550 return Context.getPointerType(op->getType());
2551}
2552
2553QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002554 UsualUnaryConversions(op);
2555 QualType qType = op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002556
Chris Lattnerbefee482007-07-31 16:53:04 +00002557 if (const PointerType *PT = qType->getAsPointerType()) {
Steve Naroff08f19672008-01-13 17:10:08 +00002558 // Note that per both C89 and C99, this is always legal, even
2559 // if ptype is an incomplete type or void.
2560 // It would be possible to warn about dereferencing a
2561 // void pointer, but it's completely well-defined,
2562 // and such a warning is unlikely to catch any mistakes.
2563 return PT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002564 }
2565 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2566 qType.getAsString(), op->getSourceRange());
2567 return QualType();
2568}
2569
2570static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2571 tok::TokenKind Kind) {
2572 BinaryOperator::Opcode Opc;
2573 switch (Kind) {
2574 default: assert(0 && "Unknown binop!");
2575 case tok::star: Opc = BinaryOperator::Mul; break;
2576 case tok::slash: Opc = BinaryOperator::Div; break;
2577 case tok::percent: Opc = BinaryOperator::Rem; break;
2578 case tok::plus: Opc = BinaryOperator::Add; break;
2579 case tok::minus: Opc = BinaryOperator::Sub; break;
2580 case tok::lessless: Opc = BinaryOperator::Shl; break;
2581 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
2582 case tok::lessequal: Opc = BinaryOperator::LE; break;
2583 case tok::less: Opc = BinaryOperator::LT; break;
2584 case tok::greaterequal: Opc = BinaryOperator::GE; break;
2585 case tok::greater: Opc = BinaryOperator::GT; break;
2586 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
2587 case tok::equalequal: Opc = BinaryOperator::EQ; break;
2588 case tok::amp: Opc = BinaryOperator::And; break;
2589 case tok::caret: Opc = BinaryOperator::Xor; break;
2590 case tok::pipe: Opc = BinaryOperator::Or; break;
2591 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
2592 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
2593 case tok::equal: Opc = BinaryOperator::Assign; break;
2594 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
2595 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
2596 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
2597 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
2598 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
2599 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
2600 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
2601 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
2602 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
2603 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
2604 case tok::comma: Opc = BinaryOperator::Comma; break;
2605 }
2606 return Opc;
2607}
2608
2609static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2610 tok::TokenKind Kind) {
2611 UnaryOperator::Opcode Opc;
2612 switch (Kind) {
2613 default: assert(0 && "Unknown unary op!");
2614 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
2615 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
2616 case tok::amp: Opc = UnaryOperator::AddrOf; break;
2617 case tok::star: Opc = UnaryOperator::Deref; break;
2618 case tok::plus: Opc = UnaryOperator::Plus; break;
2619 case tok::minus: Opc = UnaryOperator::Minus; break;
2620 case tok::tilde: Opc = UnaryOperator::Not; break;
2621 case tok::exclaim: Opc = UnaryOperator::LNot; break;
2622 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break;
2623 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2624 case tok::kw___real: Opc = UnaryOperator::Real; break;
2625 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
2626 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2627 }
2628 return Opc;
2629}
2630
2631// Binary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002632Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00002633 ExprTy *LHS, ExprTy *RHS) {
2634 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2635 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2636
Steve Narofff69936d2007-09-16 03:34:24 +00002637 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2638 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00002639
2640 QualType ResultTy; // Result type of the binary operator.
2641 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
2642
2643 switch (Opc) {
2644 default:
2645 assert(0 && "Unknown binary expr!");
2646 case BinaryOperator::Assign:
2647 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2648 break;
2649 case BinaryOperator::Mul:
2650 case BinaryOperator::Div:
2651 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2652 break;
2653 case BinaryOperator::Rem:
2654 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2655 break;
2656 case BinaryOperator::Add:
2657 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2658 break;
2659 case BinaryOperator::Sub:
2660 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2661 break;
2662 case BinaryOperator::Shl:
2663 case BinaryOperator::Shr:
2664 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2665 break;
2666 case BinaryOperator::LE:
2667 case BinaryOperator::LT:
2668 case BinaryOperator::GE:
2669 case BinaryOperator::GT:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002670 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 break;
2672 case BinaryOperator::EQ:
2673 case BinaryOperator::NE:
Chris Lattnera5937dd2007-08-26 01:18:55 +00002674 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002675 break;
2676 case BinaryOperator::And:
2677 case BinaryOperator::Xor:
2678 case BinaryOperator::Or:
2679 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2680 break;
2681 case BinaryOperator::LAnd:
2682 case BinaryOperator::LOr:
2683 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2684 break;
2685 case BinaryOperator::MulAssign:
2686 case BinaryOperator::DivAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002687 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002688 if (!CompTy.isNull())
2689 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2690 break;
2691 case BinaryOperator::RemAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002692 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002693 if (!CompTy.isNull())
2694 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2695 break;
2696 case BinaryOperator::AddAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002697 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002698 if (!CompTy.isNull())
2699 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2700 break;
2701 case BinaryOperator::SubAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002702 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002703 if (!CompTy.isNull())
2704 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2705 break;
2706 case BinaryOperator::ShlAssign:
2707 case BinaryOperator::ShrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002708 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002709 if (!CompTy.isNull())
2710 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2711 break;
2712 case BinaryOperator::AndAssign:
2713 case BinaryOperator::XorAssign:
2714 case BinaryOperator::OrAssign:
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002715 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002716 if (!CompTy.isNull())
2717 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2718 break;
2719 case BinaryOperator::Comma:
2720 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2721 break;
2722 }
2723 if (ResultTy.isNull())
2724 return true;
2725 if (CompTy.isNull())
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002726 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002727 else
Chris Lattner17d1b2a2007-08-28 18:36:55 +00002728 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002729}
2730
2731// Unary Operators. 'Tok' is the token for the operator.
Steve Narofff69936d2007-09-16 03:34:24 +00002732Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
Reid Spencer5f016e22007-07-11 17:01:13 +00002733 ExprTy *input) {
2734 Expr *Input = (Expr*)input;
2735 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2736 QualType resultType;
2737 switch (Opc) {
2738 default:
2739 assert(0 && "Unimplemented unary expr!");
2740 case UnaryOperator::PreInc:
2741 case UnaryOperator::PreDec:
2742 resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2743 break;
2744 case UnaryOperator::AddrOf:
2745 resultType = CheckAddressOfOperand(Input, OpLoc);
2746 break;
2747 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00002748 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002749 resultType = CheckIndirectionOperand(Input, OpLoc);
2750 break;
2751 case UnaryOperator::Plus:
2752 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002753 UsualUnaryConversions(Input);
2754 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002755 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1
2756 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2757 resultType.getAsString());
2758 break;
2759 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002760 UsualUnaryConversions(Input);
2761 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00002762 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2763 if (resultType->isComplexType() || resultType->isComplexIntegerType())
2764 // C99 does not support '~' for complex conjugation.
2765 Diag(OpLoc, diag::ext_integer_complement_complex,
2766 resultType.getAsString(), Input->getSourceRange());
2767 else if (!resultType->isIntegerType())
2768 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2769 resultType.getAsString(), Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002770 break;
2771 case UnaryOperator::LNot: // logical negation
2772 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002773 DefaultFunctionArrayConversion(Input);
2774 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002775 if (!resultType->isScalarType()) // C99 6.5.3.3p1
2776 return Diag(OpLoc, diag::err_typecheck_unary_expr,
2777 resultType.getAsString());
2778 // LNot always has type int. C99 6.5.3.3p5.
2779 resultType = Context.IntTy;
2780 break;
2781 case UnaryOperator::SizeOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002782 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2783 Input->getSourceRange(), true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002784 break;
2785 case UnaryOperator::AlignOf:
Chris Lattnerbb280a42008-07-25 21:45:37 +00002786 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2787 Input->getSourceRange(), false);
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00002789 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00002790 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00002791 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00002792 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002793 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00002794 resultType = Input->getType();
2795 break;
2796 }
2797 if (resultType.isNull())
2798 return true;
2799 return new UnaryOperator(Input, Opc, resultType, OpLoc);
2800}
2801
Steve Naroff1b273c42007-09-16 14:56:35 +00002802/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2803Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00002804 SourceLocation LabLoc,
2805 IdentifierInfo *LabelII) {
2806 // Look up the record for this label identifier.
2807 LabelStmt *&LabelDecl = LabelMap[LabelII];
2808
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00002809 // If we haven't seen this label yet, create a forward reference. It
2810 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00002811 if (LabelDecl == 0)
2812 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2813
2814 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00002815 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2816 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00002817}
2818
Steve Naroff1b273c42007-09-16 14:56:35 +00002819Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002820 SourceLocation RPLoc) { // "({..})"
2821 Stmt *SubStmt = static_cast<Stmt*>(substmt);
2822 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2823 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2824
2825 // FIXME: there are a variety of strange constraints to enforce here, for
2826 // example, it is not possible to goto into a stmt expression apparently.
2827 // More semantic analysis is needed.
2828
2829 // FIXME: the last statement in the compount stmt has its value used. We
2830 // should not warn about it being unused.
2831
2832 // If there are sub stmts in the compound stmt, take the type of the last one
2833 // as the type of the stmtexpr.
2834 QualType Ty = Context.VoidTy;
2835
Chris Lattner611b2ec2008-07-26 19:51:01 +00002836 if (!Compound->body_empty()) {
2837 Stmt *LastStmt = Compound->body_back();
2838 // If LastStmt is a label, skip down through into the body.
2839 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2840 LastStmt = Label->getSubStmt();
2841
2842 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002843 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00002844 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00002845
2846 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2847}
Steve Naroffd34e9152007-08-01 22:05:33 +00002848
Steve Naroff1b273c42007-09-16 14:56:35 +00002849Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002850 SourceLocation TypeLoc,
2851 TypeTy *argty,
2852 OffsetOfComponent *CompPtr,
2853 unsigned NumComponents,
2854 SourceLocation RPLoc) {
2855 QualType ArgTy = QualType::getFromOpaquePtr(argty);
2856 assert(!ArgTy.isNull() && "Missing type argument!");
2857
2858 // We must have at least one component that refers to the type, and the first
2859 // one is known to be a field designator. Verify that the ArgTy represents
2860 // a struct/union/class.
2861 if (!ArgTy->isRecordType())
2862 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2863
2864 // Otherwise, create a compound literal expression as the base, and
2865 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00002866 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002867
Chris Lattner9e2b75c2007-08-31 21:49:13 +00002868 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2869 // GCC extension, diagnose them.
2870 if (NumComponents != 1)
2871 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2872 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2873
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002874 for (unsigned i = 0; i != NumComponents; ++i) {
2875 const OffsetOfComponent &OC = CompPtr[i];
2876 if (OC.isBrackets) {
2877 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002878 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002879 if (!AT) {
2880 delete Res;
2881 return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2882 Res->getType().getAsString());
2883 }
2884
Chris Lattner704fe352007-08-30 17:59:59 +00002885 // FIXME: C++: Verify that operator[] isn't overloaded.
2886
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002887 // C99 6.5.2.1p1
2888 Expr *Idx = static_cast<Expr*>(OC.U.E);
2889 if (!Idx->getType()->isIntegerType())
2890 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2891 Idx->getSourceRange());
2892
2893 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2894 continue;
2895 }
2896
2897 const RecordType *RC = Res->getType()->getAsRecordType();
2898 if (!RC) {
2899 delete Res;
2900 return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2901 Res->getType().getAsString());
2902 }
2903
2904 // Get the decl corresponding to this.
2905 RecordDecl *RD = RC->getDecl();
2906 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2907 if (!MemberDecl)
2908 return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2909 OC.U.IdentInfo->getName(),
2910 SourceRange(OC.LocStart, OC.LocEnd));
Chris Lattner704fe352007-08-30 17:59:59 +00002911
2912 // FIXME: C++: Verify that MemberDecl isn't a static field.
2913 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00002914 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2915 // matter here.
Douglas Gregor9d293df2008-10-28 00:22:11 +00002916 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
2917 MemberDecl->getType().getNonReferenceType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002918 }
2919
2920 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2921 BuiltinLoc);
2922}
2923
2924
Steve Naroff1b273c42007-09-16 14:56:35 +00002925Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00002926 TypeTy *arg1, TypeTy *arg2,
2927 SourceLocation RPLoc) {
2928 QualType argT1 = QualType::getFromOpaquePtr(arg1);
2929 QualType argT2 = QualType::getFromOpaquePtr(arg2);
2930
2931 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2932
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002933 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00002934}
2935
Steve Naroff1b273c42007-09-16 14:56:35 +00002936Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00002937 ExprTy *expr1, ExprTy *expr2,
2938 SourceLocation RPLoc) {
2939 Expr *CondExpr = static_cast<Expr*>(cond);
2940 Expr *LHSExpr = static_cast<Expr*>(expr1);
2941 Expr *RHSExpr = static_cast<Expr*>(expr2);
2942
2943 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2944
2945 // The conditional expression is required to be a constant expression.
2946 llvm::APSInt condEval(32);
2947 SourceLocation ExpLoc;
2948 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2949 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2950 CondExpr->getSourceRange());
2951
2952 // If the condition is > zero, then the AST type is the same as the LSHExpr.
2953 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2954 RHSExpr->getType();
2955 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2956}
2957
Steve Naroff4eb206b2008-09-03 18:15:37 +00002958//===----------------------------------------------------------------------===//
2959// Clang Extensions.
2960//===----------------------------------------------------------------------===//
2961
2962/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00002963void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00002964 // Analyze block parameters.
2965 BlockSemaInfo *BSI = new BlockSemaInfo();
2966
2967 // Add BSI to CurBlock.
2968 BSI->PrevBlockInfo = CurBlock;
2969 CurBlock = BSI;
2970
2971 BSI->ReturnType = 0;
2972 BSI->TheScope = BlockScope;
2973
Steve Naroff090276f2008-10-10 01:28:17 +00002974 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
2975 PushDeclContext(BSI->TheDecl);
2976}
2977
2978void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00002979 // Analyze arguments to block.
2980 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2981 "Not a function declarator!");
2982 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2983
Steve Naroff090276f2008-10-10 01:28:17 +00002984 CurBlock->hasPrototype = FTI.hasPrototype;
2985 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002986
2987 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2988 // no arguments, not a function that takes a single void argument.
2989 if (FTI.hasPrototype &&
2990 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2991 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2992 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2993 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00002994 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002995 } else if (FTI.hasPrototype) {
2996 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00002997 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2998 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00002999 }
Steve Naroff090276f2008-10-10 01:28:17 +00003000 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3001
3002 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3003 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3004 // If this has an identifier, add it to the scope stack.
3005 if ((*AI)->getIdentifier())
3006 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003007}
3008
3009/// ActOnBlockError - If there is an error parsing a block, this callback
3010/// is invoked to pop the information about the block from the action impl.
3011void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3012 // Ensure that CurBlock is deleted.
3013 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3014
3015 // Pop off CurBlock, handle nested blocks.
3016 CurBlock = CurBlock->PrevBlockInfo;
3017
3018 // FIXME: Delete the ParmVarDecl objects as well???
3019
3020}
3021
3022/// ActOnBlockStmtExpr - This is called when the body of a block statement
3023/// literal was successfully completed. ^(int x){...}
3024Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3025 Scope *CurScope) {
3026 // Ensure that CurBlock is deleted.
3027 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3028 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3029
Steve Naroff090276f2008-10-10 01:28:17 +00003030 PopDeclContext();
3031
Steve Naroff4eb206b2008-09-03 18:15:37 +00003032 // Pop off CurBlock, handle nested blocks.
3033 CurBlock = CurBlock->PrevBlockInfo;
3034
3035 QualType RetTy = Context.VoidTy;
3036 if (BSI->ReturnType)
3037 RetTy = QualType(BSI->ReturnType, 0);
3038
3039 llvm::SmallVector<QualType, 8> ArgTypes;
3040 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3041 ArgTypes.push_back(BSI->Params[i]->getType());
3042
3043 QualType BlockTy;
3044 if (!BSI->hasPrototype)
3045 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3046 else
3047 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003048 BSI->isVariadic, 0);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003049
3050 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00003051
Steve Naroff1c90bfc2008-10-08 18:44:00 +00003052 BSI->TheDecl->setBody(Body.take());
3053 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003054}
3055
Nate Begeman67295d02008-01-30 20:50:20 +00003056/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00003057/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00003058/// The number of arguments has already been validated to match the number of
3059/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003060static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3061 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00003062 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00003063 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00003064 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3065 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00003066
3067 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00003068 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00003069 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003070 return true;
3071}
3072
3073Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3074 SourceLocation *CommaLocs,
3075 SourceLocation BuiltinLoc,
3076 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003077 // __builtin_overload requires at least 2 arguments
3078 if (NumArgs < 2)
3079 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3080 SourceRange(BuiltinLoc, RParenLoc));
Nate Begemane2ce1d92008-01-17 17:46:27 +00003081
Nate Begemane2ce1d92008-01-17 17:46:27 +00003082 // The first argument is required to be a constant expression. It tells us
3083 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003084 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003085 Expr *NParamsExpr = Args[0];
3086 llvm::APSInt constEval(32);
3087 SourceLocation ExpLoc;
3088 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
3089 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3090 NParamsExpr->getSourceRange());
3091
3092 // Verify that the number of parameters is > 0
3093 unsigned NumParams = constEval.getZExtValue();
3094 if (NumParams == 0)
3095 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
3096 NParamsExpr->getSourceRange());
3097 // Verify that we have at least 1 + NumParams arguments to the builtin.
3098 if ((NumParams + 1) > NumArgs)
3099 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
3100 SourceRange(BuiltinLoc, RParenLoc));
3101
3102 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00003103 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003104 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003105 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3106 // UsualUnaryConversions will convert the function DeclRefExpr into a
3107 // pointer to function.
3108 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00003109 const FunctionTypeProto *FnType = 0;
3110 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3111 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003112
3113 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3114 // parameters, and the number of parameters must match the value passed to
3115 // the builtin.
3116 if (!FnType || (FnType->getNumArgs() != NumParams))
Nate Begeman67295d02008-01-30 20:50:20 +00003117 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
3118 Fn->getSourceRange());
Nate Begemane2ce1d92008-01-17 17:46:27 +00003119
3120 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00003121 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00003122 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003123 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003124 if (OE)
3125 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
3126 OE->getFn()->getSourceRange());
3127 // Remember our match, and continue processing the remaining arguments
3128 // to catch any errors.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003129 OE = new OverloadExpr(Args, NumArgs, i,
3130 FnType->getResultType().getNonReferenceType(),
Nate Begeman796ef3d2008-01-31 05:38:29 +00003131 BuiltinLoc, RParenLoc);
3132 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003133 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00003134 // Return the newly created OverloadExpr node, if we succeded in matching
3135 // exactly one of the candidate functions.
3136 if (OE)
3137 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00003138
3139 // If we didn't find a matching function Expr in the __builtin_overload list
3140 // the return an error.
3141 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00003142 for (unsigned i = 0; i != NumParams; ++i) {
3143 if (i != 0) typeNames += ", ";
3144 typeNames += Args[i+1]->getType().getAsString();
3145 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003146
3147 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3148 SourceRange(BuiltinLoc, RParenLoc));
3149}
3150
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003151Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3152 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00003153 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003154 Expr *E = static_cast<Expr*>(expr);
3155 QualType T = QualType::getFromOpaquePtr(type);
3156
3157 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003158
3159 // Get the va_list type
3160 QualType VaListType = Context.getBuiltinVaListType();
3161 // Deal with implicit array decay; for example, on x86-64,
3162 // va_list is an array, but it's supposed to decay to
3163 // a pointer for va_arg.
3164 if (VaListType->isArrayType())
3165 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00003166 // Make sure the input expression also decays appropriately.
3167 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00003168
3169 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003170 return Diag(E->getLocStart(),
3171 diag::err_first_argument_to_va_arg_not_of_type_va_list,
3172 E->getType().getAsString(),
3173 E->getSourceRange());
3174
3175 // FIXME: Warn if a non-POD type is passed in.
3176
Douglas Gregor9d293df2008-10-28 00:22:11 +00003177 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003178}
3179
Chris Lattner5cf216b2008-01-04 18:04:52 +00003180bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3181 SourceLocation Loc,
3182 QualType DstType, QualType SrcType,
3183 Expr *SrcExpr, const char *Flavor) {
3184 // Decode the result (notice that AST's are still created for extensions).
3185 bool isInvalid = false;
3186 unsigned DiagKind;
3187 switch (ConvTy) {
3188 default: assert(0 && "Unknown conversion type");
3189 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003190 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00003191 DiagKind = diag::ext_typecheck_convert_pointer_int;
3192 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00003193 case IntToPointer:
3194 DiagKind = diag::ext_typecheck_convert_int_pointer;
3195 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003196 case IncompatiblePointer:
3197 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3198 break;
3199 case FunctionVoidPointer:
3200 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3201 break;
3202 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00003203 // If the qualifiers lost were because we were applying the
3204 // (deprecated) C++ conversion from a string literal to a char*
3205 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3206 // Ideally, this check would be performed in
3207 // CheckPointerTypesForAssignment. However, that would require a
3208 // bit of refactoring (so that the second argument is an
3209 // expression, rather than a type), which should be done as part
3210 // of a larger effort to fix CheckPointerTypesForAssignment for
3211 // C++ semantics.
3212 if (getLangOptions().CPlusPlus &&
3213 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3214 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003215 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3216 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003217 case IntToBlockPointer:
3218 DiagKind = diag::err_int_to_block_pointer;
3219 break;
3220 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00003221 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003222 break;
3223 case BlockVoidPointer:
3224 DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3225 break;
Steve Naroff39579072008-10-14 22:18:38 +00003226 case IncompatibleObjCQualifiedId:
3227 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3228 // it can give a more specific diagnostic.
3229 DiagKind = diag::warn_incompatible_qualified_id;
3230 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003231 case Incompatible:
3232 DiagKind = diag::err_typecheck_convert_incompatible;
3233 isInvalid = true;
3234 break;
3235 }
3236
3237 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3238 SrcExpr->getSourceRange());
3239 return isInvalid;
3240}