blob: 99714aee36114befbdfe9f3b81281175db0fc979 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor85dabae2009-12-16 01:38:02 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Ted Kremenekd6b87082010-01-25 04:41:41 +000017#include "clang/Analysis/AnalysisContext.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000020#include "clang/AST/DeclTemplate.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000021#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000022#include "clang/AST/ExprObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000024#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000025#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000026#include "clang/Lex/LiteralSupport.h"
27#include "clang/Lex/Preprocessor.h"
Steve Naroffc540d662008-09-03 18:15:37 +000028#include "clang/Parse/DeclSpec.h"
Chris Lattner07d754a2008-10-26 23:43:26 +000029#include "clang/Parse/Designator.h"
Steve Naroffc540d662008-09-03 18:15:37 +000030#include "clang/Parse/Scope.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000031#include "clang/Parse/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000032using namespace clang;
33
David Chisnall9f57c292009-08-17 16:35:33 +000034
Douglas Gregor171c45a2009-02-18 21:56:37 +000035/// \brief Determine whether the use of this declaration is valid, and
36/// emit any corresponding diagnostics.
37///
38/// This routine diagnoses various problems with referencing
39/// declarations that can occur when using a declaration. For example,
40/// it might warn if a deprecated or unavailable declaration is being
41/// used, or produce an error (and return true) if a C++0x deleted
42/// function is being used.
43///
Chris Lattnerb7df3c62009-10-25 22:31:57 +000044/// If IgnoreDeprecated is set to true, this should not want about deprecated
45/// decls.
46///
Douglas Gregor171c45a2009-02-18 21:56:37 +000047/// \returns true if there was an error (this declaration cannot be
48/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000049///
John McCall28a6aea2009-11-04 02:18:39 +000050bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000051 // See if the decl is deprecated.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000052 if (D->getAttr<DeprecatedAttr>()) {
John McCall28a6aea2009-11-04 02:18:39 +000053 EmitDeprecationWarning(D, Loc);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000054 }
55
Chris Lattnera27dd592009-10-25 17:21:40 +000056 // See if the decl is unavailable
57 if (D->getAttr<UnavailableAttr>()) {
58 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
59 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
60 }
61
Douglas Gregor171c45a2009-02-18 21:56:37 +000062 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000063 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000064 if (FD->isDeleted()) {
65 Diag(Loc, diag::err_deleted_function_use);
66 Diag(D->getLocation(), diag::note_unavailable_here) << true;
67 return true;
68 }
Douglas Gregorde681d42009-02-24 04:26:15 +000069 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000070
Douglas Gregor171c45a2009-02-18 21:56:37 +000071 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +000072}
73
Fariborz Jahanian027b8862009-05-13 18:09:35 +000074/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +000075/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +000076/// attribute. It warns if call does not have the sentinel argument.
77///
78void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +000079 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000080 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000081 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +000082 return;
Fariborz Jahanian9e877212009-05-13 23:20:50 +000083 int sentinelPos = attr->getSentinel();
84 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +000085
Mike Stump87c57ac2009-05-16 07:39:55 +000086 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
87 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +000088 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +000089 bool warnNotEnoughArgs = false;
90 int isMethod = 0;
91 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
92 // skip over named parameters.
93 ObjCMethodDecl::param_iterator P, E = MD->param_end();
94 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
95 if (nullPos)
96 --nullPos;
97 else
98 ++i;
99 }
100 warnNotEnoughArgs = (P != E || i >= NumArgs);
101 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000102 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000103 // skip over named parameters.
104 ObjCMethodDecl::param_iterator P, E = FD->param_end();
105 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
106 if (nullPos)
107 --nullPos;
108 else
109 ++i;
110 }
111 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000112 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000113 // block or function pointer call.
114 QualType Ty = V->getType();
115 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000116 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000117 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
118 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000119 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
120 unsigned NumArgsInProto = Proto->getNumArgs();
121 unsigned k;
122 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
123 if (nullPos)
124 --nullPos;
125 else
126 ++i;
127 }
128 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
129 }
130 if (Ty->isBlockPointerType())
131 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000132 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000133 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000134 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000135 return;
136
137 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000138 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000139 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000140 return;
141 }
142 int sentinel = i;
143 while (sentinelPos > 0 && i < NumArgs-1) {
144 --sentinelPos;
145 ++i;
146 }
147 if (sentinelPos > 0) {
148 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000149 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000150 return;
151 }
152 while (i < NumArgs-1) {
153 ++i;
154 ++sentinel;
155 }
156 Expr *sentinelExpr = Args[sentinel];
Anders Carlsson0b11a3e2009-11-24 17:24:21 +0000157 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
158 (!sentinelExpr->getType()->isPointerType() ||
159 !sentinelExpr->isNullPointerConstant(Context,
160 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000161 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000162 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000163 }
164 return;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000165}
166
Douglas Gregor87f95b02009-02-26 21:00:50 +0000167SourceRange Sema::getExprRange(ExprTy *E) const {
168 Expr *Ex = (Expr *)E;
169 return Ex? Ex->getSourceRange() : SourceRange();
170}
171
Chris Lattner513165e2008-07-25 21:10:04 +0000172//===----------------------------------------------------------------------===//
173// Standard Promotions and Conversions
174//===----------------------------------------------------------------------===//
175
Chris Lattner513165e2008-07-25 21:10:04 +0000176/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
177void Sema::DefaultFunctionArrayConversion(Expr *&E) {
178 QualType Ty = E->getType();
179 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
180
Chris Lattner513165e2008-07-25 21:10:04 +0000181 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000182 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlsson6904f642009-09-01 20:37:18 +0000183 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000184 else if (Ty->isArrayType()) {
185 // In C90 mode, arrays only promote to pointers if the array expression is
186 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
187 // type 'array of type' is converted to an expression that has type 'pointer
188 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
189 // that has type 'array of type' ...". The relevant change is "an lvalue"
190 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000191 //
192 // C++ 4.2p1:
193 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
194 // T" can be converted to an rvalue of type "pointer to T".
195 //
196 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
197 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000198 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
199 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000200 }
Chris Lattner513165e2008-07-25 21:10:04 +0000201}
202
Douglas Gregorb92a1562010-02-03 00:27:59 +0000203void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
204 DefaultFunctionArrayConversion(E);
205
206 QualType Ty = E->getType();
207 assert(!Ty.isNull() && "DefaultFunctionArrayLvalueConversion - missing type");
208 if (!Ty->isDependentType() && Ty.hasQualifiers() &&
209 (!getLangOptions().CPlusPlus || !Ty->isRecordType()) &&
210 E->isLvalue(Context) == Expr::LV_Valid) {
211 // C++ [conv.lval]p1:
212 // [...] If T is a non-class type, the type of the rvalue is the
213 // cv-unqualified version of T. Otherwise, the type of the
214 // rvalue is T
215 //
216 // C99 6.3.2.1p2:
217 // If the lvalue has qualified type, the value has the unqualified
218 // version of the type of the lvalue; otherwise, the value has the
219 // type of the lvalue.
220 ImpCastExprToType(E, Ty.getUnqualifiedType(), CastExpr::CK_NoOp);
221 }
222}
223
224
Chris Lattner513165e2008-07-25 21:10:04 +0000225/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000226/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000227/// sometimes surpressed. For example, the array->pointer conversion doesn't
228/// apply if the array is an argument to the sizeof or address (&) operators.
229/// In these instances, this routine should *not* be called.
230Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
231 QualType Ty = Expr->getType();
232 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000233
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000234 // C99 6.3.1.1p2:
235 //
236 // The following may be used in an expression wherever an int or
237 // unsigned int may be used:
238 // - an object or expression with an integer type whose integer
239 // conversion rank is less than or equal to the rank of int
240 // and unsigned int.
241 // - A bit-field of type _Bool, int, signed int, or unsigned int.
242 //
243 // If an int can represent all values of the original type, the
244 // value is converted to an int; otherwise, it is converted to an
245 // unsigned int. These are called the integer promotions. All
246 // other types are unchanged by the integer promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000247 QualType PTy = Context.isPromotableBitField(Expr);
248 if (!PTy.isNull()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +0000249 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman629ffb92009-08-20 04:21:42 +0000250 return Expr;
251 }
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000252 if (Ty->isPromotableIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000253 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman06ed2a52009-10-20 08:27:19 +0000254 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000255 return Expr;
Eli Friedman629ffb92009-08-20 04:21:42 +0000256 }
257
Douglas Gregorb92a1562010-02-03 00:27:59 +0000258 DefaultFunctionArrayLvalueConversion(Expr);
Chris Lattner513165e2008-07-25 21:10:04 +0000259 return Expr;
260}
261
Chris Lattner2ce500f2008-07-25 22:25:12 +0000262/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000263/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000264/// double. All other argument types are converted by UsualUnaryConversions().
265void Sema::DefaultArgumentPromotion(Expr *&Expr) {
266 QualType Ty = Expr->getType();
267 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000268
Chris Lattner2ce500f2008-07-25 22:25:12 +0000269 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall9dd450b2009-09-21 23:43:11 +0000270 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner2ce500f2008-07-25 22:25:12 +0000271 if (BT->getKind() == BuiltinType::Float)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000272 return ImpCastExprToType(Expr, Context.DoubleTy,
273 CastExpr::CK_FloatingCast);
Mike Stump11289f42009-09-09 15:08:12 +0000274
Chris Lattner2ce500f2008-07-25 22:25:12 +0000275 UsualUnaryConversions(Expr);
276}
277
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000278/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
279/// will warn if the resulting type is not a POD type, and rejects ObjC
280/// interfaces passed by value. This returns true if the argument type is
281/// completely illegal.
282bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000283 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000284
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000285 if (Expr->getType()->isObjCInterfaceType() &&
286 DiagRuntimeBehavior(Expr->getLocStart(),
287 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
288 << Expr->getType() << CT))
289 return true;
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000290
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000291 if (!Expr->getType()->isPODType() &&
292 DiagRuntimeBehavior(Expr->getLocStart(),
293 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
294 << Expr->getType() << CT))
295 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000296
297 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000298}
299
300
Chris Lattner513165e2008-07-25 21:10:04 +0000301/// UsualArithmeticConversions - Performs various conversions that are common to
302/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000303/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000304/// responsible for emitting appropriate error diagnostics.
305/// FIXME: verify the conversion rules for "complex int" are consistent with
306/// GCC.
307QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
308 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000309 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000310 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000311
312 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000313
Mike Stump11289f42009-09-09 15:08:12 +0000314 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000315 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000316 QualType lhs =
317 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000318 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000319 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000320
321 // If both types are identical, no conversion is needed.
322 if (lhs == rhs)
323 return lhs;
324
325 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
326 // The caller can deal with this (e.g. pointer + int).
327 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
328 return lhs;
329
Douglas Gregord2c2d172009-05-02 00:36:19 +0000330 // Perform bitfield promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000331 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000332 if (!LHSBitfieldPromoteTy.isNull())
333 lhs = LHSBitfieldPromoteTy;
Eli Friedman629ffb92009-08-20 04:21:42 +0000334 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000335 if (!RHSBitfieldPromoteTy.isNull())
336 rhs = RHSBitfieldPromoteTy;
337
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000338 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000339 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000340 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
341 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregora11693b2008-11-12 17:17:38 +0000342 return destType;
343}
344
Chris Lattner513165e2008-07-25 21:10:04 +0000345//===----------------------------------------------------------------------===//
346// Semantic Analysis for various Expression Types
347//===----------------------------------------------------------------------===//
348
349
Steve Naroff83895f72007-09-16 03:34:24 +0000350/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000351/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
352/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
353/// multiple tokens. However, the common case is that StringToks points to one
354/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000355///
356Action::OwningExprResult
Steve Naroff83895f72007-09-16 03:34:24 +0000357Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000358 assert(NumStringToks && "Must have at least one string!");
359
Chris Lattner8a24e582009-01-16 18:51:42 +0000360 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000361 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000362 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000363
Chris Lattner23b7eb62007-06-15 23:05:46 +0000364 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000365 for (unsigned i = 0; i != NumStringToks; ++i)
366 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000367
Chris Lattner36fc8792008-02-11 00:02:17 +0000368 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000369 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000370 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000371
372 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
373 if (getLangOptions().CPlusPlus)
374 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000375
Chris Lattner36fc8792008-02-11 00:02:17 +0000376 // Get an array type for the string, according to C99 6.4.5. This includes
377 // the nul terminator character as well as the string length for pascal
378 // strings.
379 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000380 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000381 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000382
Chris Lattner5b183d82006-11-10 05:03:26 +0000383 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump11289f42009-09-09 15:08:12 +0000384 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000385 Literal.GetStringLength(),
386 Literal.AnyWide, StrTy,
387 &StringTokLocs[0],
388 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000389}
390
Chris Lattner2a9d9892008-10-20 05:16:36 +0000391/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
392/// CurBlock to VD should cause it to be snapshotted (as we do for auto
393/// variables defined outside the block) or false if this is not needed (e.g.
394/// for values inside the block or for globals).
395///
Chris Lattner497d7b02009-04-21 22:26:47 +0000396/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
397/// up-to-date.
398///
Chris Lattner2a9d9892008-10-20 05:16:36 +0000399static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
400 ValueDecl *VD) {
401 // If the value is defined inside the block, we couldn't snapshot it even if
402 // we wanted to.
403 if (CurBlock->TheDecl == VD->getDeclContext())
404 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000405
Chris Lattner2a9d9892008-10-20 05:16:36 +0000406 // If this is an enum constant or function, it is constant, don't snapshot.
407 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
408 return false;
409
410 // If this is a reference to an extern, static, or global variable, no need to
411 // snapshot it.
412 // FIXME: What about 'const' variables in C++?
413 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000414 if (!Var->hasLocalStorage())
415 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000416
Chris Lattner497d7b02009-04-21 22:26:47 +0000417 // Blocks that have these can't be constant.
418 CurBlock->hasBlockDeclRefExprs = true;
419
420 // If we have nested blocks, the decl may be declared in an outer block (in
421 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
422 // be defined outside all of the current blocks (in which case the blocks do
423 // all get the bit). Walk the nesting chain.
424 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
425 NextBlock = NextBlock->PrevBlockInfo) {
426 // If we found the defining block for the variable, don't mark the block as
427 // having a reference outside it.
428 if (NextBlock->TheDecl == VD->getDeclContext())
429 break;
Mike Stump11289f42009-09-09 15:08:12 +0000430
Chris Lattner497d7b02009-04-21 22:26:47 +0000431 // Otherwise, the DeclRef from the inner block causes the outer one to need
432 // a snapshot as well.
433 NextBlock->hasBlockDeclRefExprs = true;
434 }
Mike Stump11289f42009-09-09 15:08:12 +0000435
Chris Lattner2a9d9892008-10-20 05:16:36 +0000436 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000437}
438
Chris Lattner2a9d9892008-10-20 05:16:36 +0000439
440
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000441/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlsson946b86d2009-06-24 00:10:43 +0000442Sema::OwningExprResult
John McCallce546572009-12-08 09:08:17 +0000443Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000444 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000445 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
446 Diag(Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000447 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000448 << D->getDeclName();
449 return ExprError();
450 }
Mike Stump11289f42009-09-09 15:08:12 +0000451
Anders Carlsson946b86d2009-06-24 00:10:43 +0000452 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
453 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
454 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
455 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump11289f42009-09-09 15:08:12 +0000456 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000457 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000458 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000459 << D->getIdentifier();
460 return ExprError();
461 }
462 }
463 }
464 }
Mike Stump11289f42009-09-09 15:08:12 +0000465
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000466 MarkDeclarationReferenced(Loc, D);
Mike Stump11289f42009-09-09 15:08:12 +0000467
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000468 return Owned(DeclRefExpr::Create(Context,
469 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
470 SS? SS->getRange() : SourceRange(),
Douglas Gregored6c7442009-11-23 11:41:28 +0000471 D, Loc, Ty));
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000472}
473
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000474/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
475/// variable corresponding to the anonymous union or struct whose type
476/// is Record.
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000477static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
478 RecordDecl *Record) {
Mike Stump11289f42009-09-09 15:08:12 +0000479 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000480 "Record must be an anonymous struct or union!");
Mike Stump11289f42009-09-09 15:08:12 +0000481
Mike Stump87c57ac2009-05-16 07:39:55 +0000482 // FIXME: Once Decls are directly linked together, this will be an O(1)
483 // operation rather than a slow walk through DeclContext's vector (which
484 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000485 DeclContext *Ctx = Record->getDeclContext();
Mike Stump11289f42009-09-09 15:08:12 +0000486 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000487 DEnd = Ctx->decls_end();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000488 D != DEnd; ++D) {
489 if (*D == Record) {
490 // The object for the anonymous struct/union directly
491 // follows its type in the list of declarations.
492 ++D;
493 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000494 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000495 return *D;
496 }
497 }
498
499 assert(false && "Missing object for anonymous record");
500 return 0;
501}
502
Douglas Gregord5846a12009-04-15 06:41:24 +0000503/// \brief Given a field that represents a member of an anonymous
504/// struct/union, build the path from that field's context to the
505/// actual member.
506///
507/// Construct the sequence of field member references we'll have to
508/// perform to get to the field in the anonymous union/struct. The
509/// list of members is built from the field outward, so traverse it
510/// backwards to go from an object in the current context to the field
511/// we found.
512///
513/// \returns The variable from which the field access should begin,
514/// for an anonymous struct/union that is not a member of another
515/// class. Otherwise, returns NULL.
516VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
517 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000518 assert(Field->getDeclContext()->isRecord() &&
519 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
520 && "Field must be stored inside an anonymous struct or union");
521
Douglas Gregord5846a12009-04-15 06:41:24 +0000522 Path.push_back(Field);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000523 VarDecl *BaseObject = 0;
524 DeclContext *Ctx = Field->getDeclContext();
525 do {
526 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000527 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000528 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregord5846a12009-04-15 06:41:24 +0000529 Path.push_back(AnonField);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000530 else {
531 BaseObject = cast<VarDecl>(AnonObject);
532 break;
533 }
534 Ctx = Ctx->getParent();
Mike Stump11289f42009-09-09 15:08:12 +0000535 } while (Ctx->isRecord() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000536 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregord5846a12009-04-15 06:41:24 +0000537
538 return BaseObject;
539}
540
541Sema::OwningExprResult
542Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
543 FieldDecl *Field,
544 Expr *BaseObjectExpr,
545 SourceLocation OpLoc) {
546 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump11289f42009-09-09 15:08:12 +0000547 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregord5846a12009-04-15 06:41:24 +0000548 AnonFields);
549
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000550 // Build the expression that refers to the base object, from
551 // which we will build a sequence of member references to each
552 // of the anonymous union objects and, eventually, the field we
553 // found via name lookup.
554 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000555 Qualifiers BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000556 if (BaseObject) {
557 // BaseObject is an anonymous struct/union variable (and is,
558 // therefore, not part of another non-anonymous record).
Ted Kremenek5a201952009-02-07 01:47:29 +0000559 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000560 MarkDeclarationReferenced(Loc, BaseObject);
Steve Narofff6009ed2009-01-21 00:14:39 +0000561 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000562 SourceLocation());
John McCall8ccfcb52009-09-24 19:53:00 +0000563 BaseQuals
564 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000565 } else if (BaseObjectExpr) {
566 // The caller provided the base object expression. Determine
567 // whether its a pointer and whether it adds any qualifiers to the
568 // anonymous struct/union fields we're looking into.
569 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000570 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000571 BaseObjectIsPointer = true;
572 ObjectType = ObjectPtr->getPointeeType();
573 }
John McCall8ccfcb52009-09-24 19:53:00 +0000574 BaseQuals
575 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000576 } else {
577 // We've found a member of an anonymous struct/union that is
578 // inside a non-anonymous struct/union, so in a well-formed
579 // program our base object expression is "this".
580 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
581 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000582 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000583 = Context.getTagDeclType(
584 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
585 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000586 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000587 == Context.getCanonicalType(ThisType)) ||
588 IsDerivedFrom(ThisType, AnonFieldType)) {
589 // Our base object expression is "this".
Douglas Gregor4b654412009-12-24 20:23:34 +0000590 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000591 MD->getThisType(Context),
592 /*isImplicit=*/true);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000593 BaseObjectIsPointer = true;
594 }
595 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000596 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
597 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000598 }
John McCall8ccfcb52009-09-24 19:53:00 +0000599 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000600 }
601
Mike Stump11289f42009-09-09 15:08:12 +0000602 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000603 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
604 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000605 }
606
607 // Build the implicit member references to the field of the
608 // anonymous struct/union.
609 Expr *Result = BaseObjectExpr;
John McCall8ccfcb52009-09-24 19:53:00 +0000610 Qualifiers ResultQuals = BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000611 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
612 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
613 FI != FIEnd; ++FI) {
614 QualType MemberType = (*FI)->getType();
John McCall8ccfcb52009-09-24 19:53:00 +0000615 Qualifiers MemberTypeQuals =
616 Context.getCanonicalType(MemberType).getQualifiers();
617
618 // CVR attributes from the base are picked up by members,
619 // except that 'mutable' members don't pick up 'const'.
620 if ((*FI)->isMutable())
621 ResultQuals.removeConst();
622
623 // GC attributes are never picked up by members.
624 ResultQuals.removeObjCGCAttr();
625
626 // TR 18037 does not allow fields to be declared with address spaces.
627 assert(!MemberTypeQuals.hasAddressSpace());
628
629 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
630 if (NewQuals != MemberTypeQuals)
631 MemberType = Context.getQualifiedType(MemberType, NewQuals);
632
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000633 MarkDeclarationReferenced(Loc, *FI);
Eli Friedman78cde142009-12-04 07:18:51 +0000634 PerformObjectMemberConversion(Result, *FI);
Douglas Gregorc1905232009-08-26 22:36:53 +0000635 // FIXME: Might this end up being a qualified name?
Steve Narofff6009ed2009-01-21 00:14:39 +0000636 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
637 OpLoc, MemberType);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000638 BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000639 ResultQuals = NewQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000640 }
641
Sebastian Redlffbcf962009-01-18 18:53:16 +0000642 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000643}
644
John McCall10eae182009-11-30 22:42:35 +0000645/// Decomposes the given name into a DeclarationName, its location, and
646/// possibly a list of template arguments.
647///
648/// If this produces template arguments, it is permitted to call
649/// DecomposeTemplateName.
650///
651/// This actually loses a lot of source location information for
652/// non-standard name kinds; we should consider preserving that in
653/// some way.
654static void DecomposeUnqualifiedId(Sema &SemaRef,
655 const UnqualifiedId &Id,
656 TemplateArgumentListInfo &Buffer,
657 DeclarationName &Name,
658 SourceLocation &NameLoc,
659 const TemplateArgumentListInfo *&TemplateArgs) {
660 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
661 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
662 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
663
664 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
665 Id.TemplateId->getTemplateArgs(),
666 Id.TemplateId->NumArgs);
667 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
668 TemplateArgsPtr.release();
669
670 TemplateName TName =
671 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
672
673 Name = SemaRef.Context.getNameForTemplate(TName);
674 NameLoc = Id.TemplateId->TemplateNameLoc;
675 TemplateArgs = &Buffer;
676 } else {
677 Name = SemaRef.GetNameFromUnqualifiedId(Id);
678 NameLoc = Id.StartLocation;
679 TemplateArgs = 0;
680 }
681}
682
683/// Decompose the given template name into a list of lookup results.
684///
685/// The unqualified ID must name a non-dependent template, which can
686/// be more easily tested by checking whether DecomposeUnqualifiedId
687/// found template arguments.
688static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
689 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
690 TemplateName TName =
691 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
692
John McCalle66edc12009-11-24 19:00:30 +0000693 if (TemplateDecl *TD = TName.getAsTemplateDecl())
694 R.addDecl(TD);
John McCalld28ae272009-12-02 08:04:21 +0000695 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
696 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
697 I != E; ++I)
John McCalle66edc12009-11-24 19:00:30 +0000698 R.addDecl(*I);
John McCalla9ee3252009-11-22 02:49:43 +0000699
John McCalle66edc12009-11-24 19:00:30 +0000700 R.resolveKind();
Douglas Gregora121b752009-11-03 16:56:39 +0000701}
702
John McCall10eae182009-11-30 22:42:35 +0000703static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
704 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
705 E = Record->bases_end(); I != E; ++I) {
706 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
707 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
708 if (!BaseRT) return false;
709
710 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
711 if (!BaseRecord->isDefinition() ||
712 !IsFullyFormedScope(SemaRef, BaseRecord))
713 return false;
714 }
715
716 return true;
717}
718
John McCallf786fb12009-11-30 23:50:49 +0000719/// Determines whether we can lookup this id-expression now or whether
720/// we have to wait until template instantiation is complete.
721static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall10eae182009-11-30 22:42:35 +0000722 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall10eae182009-11-30 22:42:35 +0000723
John McCallf786fb12009-11-30 23:50:49 +0000724 // If the qualifier scope isn't computable, it's definitely dependent.
725 if (!DC) return true;
726
727 // If the qualifier scope doesn't name a record, we can always look into it.
728 if (!isa<CXXRecordDecl>(DC)) return false;
729
730 // We can't look into record types unless they're fully-formed.
731 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
732
John McCall2d74de92009-12-01 22:10:20 +0000733 return false;
734}
John McCallf786fb12009-11-30 23:50:49 +0000735
John McCall2d74de92009-12-01 22:10:20 +0000736/// Determines if the given class is provably not derived from all of
737/// the prospective base classes.
738static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
739 CXXRecordDecl *Record,
740 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +0000741 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +0000742 return false;
743
John McCalla6d407c2009-12-01 22:28:41 +0000744 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
745 if (!RD) return false;
746 Record = cast<CXXRecordDecl>(RD);
747
John McCall2d74de92009-12-01 22:10:20 +0000748 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
749 E = Record->bases_end(); I != E; ++I) {
750 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
751 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
752 if (!BaseRT) return false;
753
754 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +0000755 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
756 return false;
757 }
758
759 return true;
760}
761
John McCall5af04502009-12-02 20:26:00 +0000762/// Determines if this is an instance member of a class.
763static bool IsInstanceMember(NamedDecl *D) {
John McCall57500772009-12-16 12:17:52 +0000764 assert(D->isCXXClassMember() &&
John McCall2d74de92009-12-01 22:10:20 +0000765 "checking whether non-member is instance member");
766
767 if (isa<FieldDecl>(D)) return true;
768
769 if (isa<CXXMethodDecl>(D))
770 return !cast<CXXMethodDecl>(D)->isStatic();
771
772 if (isa<FunctionTemplateDecl>(D)) {
773 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
774 return !cast<CXXMethodDecl>(D)->isStatic();
775 }
776
777 return false;
778}
779
780enum IMAKind {
781 /// The reference is definitely not an instance member access.
782 IMA_Static,
783
784 /// The reference may be an implicit instance member access.
785 IMA_Mixed,
786
787 /// The reference may be to an instance member, but it is invalid if
788 /// so, because the context is not an instance method.
789 IMA_Mixed_StaticContext,
790
791 /// The reference may be to an instance member, but it is invalid if
792 /// so, because the context is from an unrelated class.
793 IMA_Mixed_Unrelated,
794
795 /// The reference is definitely an implicit instance member access.
796 IMA_Instance,
797
798 /// The reference may be to an unresolved using declaration.
799 IMA_Unresolved,
800
801 /// The reference may be to an unresolved using declaration and the
802 /// context is not an instance method.
803 IMA_Unresolved_StaticContext,
804
805 /// The reference is to a member of an anonymous structure in a
806 /// non-class context.
807 IMA_AnonymousMember,
808
809 /// All possible referrents are instance members and the current
810 /// context is not an instance method.
811 IMA_Error_StaticContext,
812
813 /// All possible referrents are instance members of an unrelated
814 /// class.
815 IMA_Error_Unrelated
816};
817
818/// The given lookup names class member(s) and is not being used for
819/// an address-of-member expression. Classify the type of access
820/// according to whether it's possible that this reference names an
821/// instance member. This is best-effort; it is okay to
822/// conservatively answer "yes", in which case some errors will simply
823/// not be caught until template-instantiation.
824static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
825 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +0000826 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +0000827
828 bool isStaticContext =
829 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
830 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
831
832 if (R.isUnresolvableResult())
833 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
834
835 // Collect all the declaring classes of instance members we find.
836 bool hasNonInstance = false;
837 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
838 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
839 NamedDecl *D = (*I)->getUnderlyingDecl();
840 if (IsInstanceMember(D)) {
841 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
842
843 // If this is a member of an anonymous record, move out to the
844 // innermost non-anonymous struct or union. If there isn't one,
845 // that's a special case.
846 while (R->isAnonymousStructOrUnion()) {
847 R = dyn_cast<CXXRecordDecl>(R->getParent());
848 if (!R) return IMA_AnonymousMember;
849 }
850 Classes.insert(R->getCanonicalDecl());
851 }
852 else
853 hasNonInstance = true;
854 }
855
856 // If we didn't find any instance members, it can't be an implicit
857 // member reference.
858 if (Classes.empty())
859 return IMA_Static;
860
861 // If the current context is not an instance method, it can't be
862 // an implicit member reference.
863 if (isStaticContext)
864 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
865
866 // If we can prove that the current context is unrelated to all the
867 // declaring classes, it can't be an implicit member reference (in
868 // which case it's an error if any of those members are selected).
869 if (IsProvablyNotDerivedFrom(SemaRef,
870 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
871 Classes))
872 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
873
874 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
875}
876
877/// Diagnose a reference to a field with no object available.
878static void DiagnoseInstanceReference(Sema &SemaRef,
879 const CXXScopeSpec &SS,
880 const LookupResult &R) {
881 SourceLocation Loc = R.getNameLoc();
882 SourceRange Range(Loc);
883 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
884
885 if (R.getAsSingle<FieldDecl>()) {
886 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
887 if (MD->isStatic()) {
888 // "invalid use of member 'x' in static member function"
889 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
890 << Range << R.getLookupName();
891 return;
892 }
893 }
894
895 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
896 << R.getLookupName() << Range;
897 return;
898 }
899
900 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +0000901}
902
John McCalld681c392009-12-16 08:11:27 +0000903/// Diagnose an empty lookup.
904///
905/// \return false if new lookup candidates were found
Douglas Gregor598b08f2009-12-31 05:20:13 +0000906bool Sema::DiagnoseEmptyLookup(Scope *S, const CXXScopeSpec &SS,
John McCalld681c392009-12-16 08:11:27 +0000907 LookupResult &R) {
908 DeclarationName Name = R.getLookupName();
909
John McCalld681c392009-12-16 08:11:27 +0000910 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000911 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +0000912 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
913 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +0000914 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +0000915 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000916 diagnostic_suggest = diag::err_undeclared_use_suggest;
917 }
John McCalld681c392009-12-16 08:11:27 +0000918
Douglas Gregor598b08f2009-12-31 05:20:13 +0000919 // If the original lookup was an unqualified lookup, fake an
920 // unqualified lookup. This is useful when (for example) the
921 // original lookup would not have found something because it was a
922 // dependent name.
923 for (DeclContext *DC = SS.isEmpty()? CurContext : 0;
924 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +0000925 if (isa<CXXRecordDecl>(DC)) {
926 LookupQualifiedName(R, DC);
927
928 if (!R.empty()) {
929 // Don't give errors about ambiguities in this lookup.
930 R.suppressDiagnostics();
931
932 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
933 bool isInstance = CurMethod &&
934 CurMethod->isInstance() &&
935 DC == CurMethod->getParent();
936
937 // Give a code modification hint to insert 'this->'.
938 // TODO: fixit for inserting 'Base<T>::' in the other cases.
939 // Actually quite difficult!
940 if (isInstance)
941 Diag(R.getNameLoc(), diagnostic) << Name
942 << CodeModificationHint::CreateInsertion(R.getNameLoc(),
943 "this->");
944 else
945 Diag(R.getNameLoc(), diagnostic) << Name;
946
947 // Do we really want to note all of these?
948 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
949 Diag((*I)->getLocation(), diag::note_dependent_var_use);
950
951 // Tell the callee to try to recover.
952 return false;
953 }
954 }
955 }
956
Douglas Gregor598b08f2009-12-31 05:20:13 +0000957 // We didn't find anything, so try to correct for a typo.
Douglas Gregor25363982010-01-01 00:15:04 +0000958 if (S && CorrectTypo(R, S, &SS)) {
959 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
960 if (SS.isEmpty())
961 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
962 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
Douglas Gregor598b08f2009-12-31 05:20:13 +0000963 R.getLookupName().getAsString());
Douglas Gregor25363982010-01-01 00:15:04 +0000964 else
965 Diag(R.getNameLoc(), diag::err_no_member_suggest)
966 << Name << computeDeclContext(SS, false) << R.getLookupName()
967 << SS.getRange()
968 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
Douglas Gregor598b08f2009-12-31 05:20:13 +0000969 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000970 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
971 Diag(ND->getLocation(), diag::note_previous_decl)
972 << ND->getDeclName();
973
Douglas Gregor25363982010-01-01 00:15:04 +0000974 // Tell the callee to try to recover.
975 return false;
976 }
977
978 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
979 // FIXME: If we ended up with a typo for a type name or
980 // Objective-C class name, we're in trouble because the parser
981 // is in the wrong place to recover. Suggest the typo
982 // correction, but don't make it a fix-it since we're not going
983 // to recover well anyway.
984 if (SS.isEmpty())
985 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
986 else
987 Diag(R.getNameLoc(), diag::err_no_member_suggest)
988 << Name << computeDeclContext(SS, false) << R.getLookupName()
989 << SS.getRange();
990
991 // Don't try to recover; it won't work.
992 return true;
993 }
994
995 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +0000996 }
997
998 // Emit a special diagnostic for failed member lookups.
999 // FIXME: computing the declaration context might fail here (?)
1000 if (!SS.isEmpty()) {
1001 Diag(R.getNameLoc(), diag::err_no_member)
1002 << Name << computeDeclContext(SS, false)
1003 << SS.getRange();
1004 return true;
1005 }
1006
John McCalld681c392009-12-16 08:11:27 +00001007 // Give up, we can't recover.
1008 Diag(R.getNameLoc(), diagnostic) << Name;
1009 return true;
1010}
1011
John McCalle66edc12009-11-24 19:00:30 +00001012Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
1013 const CXXScopeSpec &SS,
1014 UnqualifiedId &Id,
1015 bool HasTrailingLParen,
1016 bool isAddressOfOperand) {
1017 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1018 "cannot be direct & operand and have a trailing lparen");
1019
1020 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001021 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001022
John McCall10eae182009-11-30 22:42:35 +00001023 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001024
1025 // Decompose the UnqualifiedId into the following data.
1026 DeclarationName Name;
1027 SourceLocation NameLoc;
1028 const TemplateArgumentListInfo *TemplateArgs;
John McCall10eae182009-11-30 22:42:35 +00001029 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
1030 Name, NameLoc, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001031
Douglas Gregor4ea80432008-11-18 15:03:34 +00001032 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCalld14a8642009-11-21 08:51:07 +00001033
John McCalle66edc12009-11-24 19:00:30 +00001034 // C++ [temp.dep.expr]p3:
1035 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001036 // -- an identifier that was declared with a dependent type,
1037 // (note: handled after lookup)
1038 // -- a template-id that is dependent,
1039 // (note: handled in BuildTemplateIdExpr)
1040 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001041 // -- a nested-name-specifier that contains a class-name that
1042 // names a dependent type.
1043 // Determine whether this is a member of an unknown specialization;
1044 // we need to handle these differently.
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001045 if ((Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1046 Name.getCXXNameType()->isDependentType()) ||
1047 (SS.isSet() && IsDependentIdExpression(*this, SS))) {
John McCalle66edc12009-11-24 19:00:30 +00001048 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +00001049 isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001050 TemplateArgs);
1051 }
John McCalld14a8642009-11-21 08:51:07 +00001052
John McCalle66edc12009-11-24 19:00:30 +00001053 // Perform the required lookup.
1054 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1055 if (TemplateArgs) {
John McCalle66edc12009-11-24 19:00:30 +00001056 // Just re-use the lookup done by isTemplateName.
John McCall10eae182009-11-30 22:42:35 +00001057 DecomposeTemplateName(R, Id);
John McCalle66edc12009-11-24 19:00:30 +00001058 } else {
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001059 bool IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1060 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001061
John McCalle66edc12009-11-24 19:00:30 +00001062 // If this reference is in an Objective-C method, then we need to do
1063 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001064 if (IvarLookupFollowUp) {
1065 OwningExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001066 if (E.isInvalid())
1067 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001068
John McCalle66edc12009-11-24 19:00:30 +00001069 Expr *Ex = E.takeAs<Expr>();
1070 if (Ex) return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001071 }
Chris Lattner59a25942008-03-31 00:36:02 +00001072 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001073
John McCalle66edc12009-11-24 19:00:30 +00001074 if (R.isAmbiguous())
1075 return ExprError();
1076
Douglas Gregor171c45a2009-02-18 21:56:37 +00001077 // Determine whether this name might be a candidate for
1078 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001079 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001080
John McCalle66edc12009-11-24 19:00:30 +00001081 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001082 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001083 // in C90, extension in C99, forbidden in C++).
1084 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1085 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1086 if (D) R.addDecl(D);
1087 }
1088
1089 // If this name wasn't predeclared and if this is not a function
1090 // call, diagnose the problem.
1091 if (R.empty()) {
Douglas Gregor598b08f2009-12-31 05:20:13 +00001092 if (DiagnoseEmptyLookup(S, SS, R))
John McCalld681c392009-12-16 08:11:27 +00001093 return ExprError();
1094
1095 assert(!R.empty() &&
1096 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001097
1098 // If we found an Objective-C instance variable, let
1099 // LookupInObjCMethod build the appropriate expression to
1100 // reference the ivar.
1101 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1102 R.clear();
1103 OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1104 assert(E.isInvalid() || E.get());
1105 return move(E);
1106 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001107 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001108 }
Mike Stump11289f42009-09-09 15:08:12 +00001109
John McCalle66edc12009-11-24 19:00:30 +00001110 // This is guaranteed from this point on.
1111 assert(!R.empty() || ADL);
1112
1113 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001114 // Warn about constructs like:
1115 // if (void *X = foo()) { ... } else { X }.
1116 // In the else block, the pointer is always false.
Mike Stump11289f42009-09-09 15:08:12 +00001117
Douglas Gregor3256d042009-06-30 15:47:41 +00001118 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1119 Scope *CheckS = S;
Douglas Gregor13a2c032009-11-05 17:49:26 +00001120 while (CheckS && CheckS->getControlParent()) {
Mike Stump11289f42009-09-09 15:08:12 +00001121 if (CheckS->isWithinElse() &&
Douglas Gregor3256d042009-06-30 15:47:41 +00001122 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCalle66edc12009-11-24 19:00:30 +00001123 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor13a2c032009-11-05 17:49:26 +00001124 << Var->getDeclName()
1125 << (Var->getType()->isPointerType()? 2 :
1126 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor3256d042009-06-30 15:47:41 +00001127 break;
1128 }
Mike Stump11289f42009-09-09 15:08:12 +00001129
Douglas Gregor13a2c032009-11-05 17:49:26 +00001130 // Move to the parent of this scope.
1131 CheckS = CheckS->getParent();
Douglas Gregor3256d042009-06-30 15:47:41 +00001132 }
1133 }
John McCalle66edc12009-11-24 19:00:30 +00001134 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001135 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1136 // C99 DR 316 says that, if a function type comes from a
1137 // function definition (without a prototype), that type is only
1138 // used for checking compatibility. Therefore, when referencing
1139 // the function, we pretend that we don't have the full function
1140 // type.
John McCalle66edc12009-11-24 19:00:30 +00001141 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001142 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001143
Douglas Gregor3256d042009-06-30 15:47:41 +00001144 QualType T = Func->getType();
1145 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001146 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor3256d042009-06-30 15:47:41 +00001147 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCalle66edc12009-11-24 19:00:30 +00001148 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001149 }
1150 }
Mike Stump11289f42009-09-09 15:08:12 +00001151
John McCall2d74de92009-12-01 22:10:20 +00001152 // Check whether this might be a C++ implicit instance member access.
1153 // C++ [expr.prim.general]p6:
1154 // Within the definition of a non-static member function, an
1155 // identifier that names a non-static member is transformed to a
1156 // class member access expression.
1157 // But note that &SomeClass::foo is grammatically distinct, even
1158 // though we don't parse it that way.
John McCall57500772009-12-16 12:17:52 +00001159 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCalle66edc12009-11-24 19:00:30 +00001160 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall57500772009-12-16 12:17:52 +00001161 if (!isAbstractMemberPointer)
1162 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001163 }
1164
John McCalle66edc12009-11-24 19:00:30 +00001165 if (TemplateArgs)
1166 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001167
John McCalle66edc12009-11-24 19:00:30 +00001168 return BuildDeclarationNameExpr(SS, R, ADL);
1169}
1170
John McCall57500772009-12-16 12:17:52 +00001171/// Builds an expression which might be an implicit member expression.
1172Sema::OwningExprResult
1173Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1174 LookupResult &R,
1175 const TemplateArgumentListInfo *TemplateArgs) {
1176 switch (ClassifyImplicitMemberAccess(*this, R)) {
1177 case IMA_Instance:
1178 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1179
1180 case IMA_AnonymousMember:
1181 assert(R.isSingleResult());
1182 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1183 R.getAsSingle<FieldDecl>());
1184
1185 case IMA_Mixed:
1186 case IMA_Mixed_Unrelated:
1187 case IMA_Unresolved:
1188 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1189
1190 case IMA_Static:
1191 case IMA_Mixed_StaticContext:
1192 case IMA_Unresolved_StaticContext:
1193 if (TemplateArgs)
1194 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1195 return BuildDeclarationNameExpr(SS, R, false);
1196
1197 case IMA_Error_StaticContext:
1198 case IMA_Error_Unrelated:
1199 DiagnoseInstanceReference(*this, SS, R);
1200 return ExprError();
1201 }
1202
1203 llvm_unreachable("unexpected instance member access kind");
1204 return ExprError();
1205}
1206
John McCall10eae182009-11-30 22:42:35 +00001207/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1208/// declaration name, generally during template instantiation.
1209/// There's a large number of things which don't need to be done along
1210/// this path.
John McCalle66edc12009-11-24 19:00:30 +00001211Sema::OwningExprResult
1212Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1213 DeclarationName Name,
1214 SourceLocation NameLoc) {
1215 DeclContext *DC;
1216 if (!(DC = computeDeclContext(SS, false)) ||
1217 DC->isDependentContext() ||
1218 RequireCompleteDeclContext(SS))
1219 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1220
1221 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1222 LookupQualifiedName(R, DC);
1223
1224 if (R.isAmbiguous())
1225 return ExprError();
1226
1227 if (R.empty()) {
1228 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1229 return ExprError();
1230 }
1231
1232 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1233}
1234
1235/// LookupInObjCMethod - The parser has read a name in, and Sema has
1236/// detected that we're currently inside an ObjC method. Perform some
1237/// additional lookup.
1238///
1239/// Ideally, most of this would be done by lookup, but there's
1240/// actually quite a lot of extra work involved.
1241///
1242/// Returns a null sentinel to indicate trivial success.
1243Sema::OwningExprResult
1244Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001245 IdentifierInfo *II,
1246 bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001247 SourceLocation Loc = Lookup.getNameLoc();
1248
1249 // There are two cases to handle here. 1) scoped lookup could have failed,
1250 // in which case we should look for an ivar. 2) scoped lookup could have
1251 // found a decl, but that decl is outside the current instance method (i.e.
1252 // a global variable). In these two cases, we do a lookup for an ivar with
1253 // this name, if the lookup sucedes, we replace it our current decl.
1254
1255 // If we're in a class method, we don't normally want to look for
1256 // ivars. But if we don't find anything else, and there's an
1257 // ivar, that's an error.
1258 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1259
1260 bool LookForIvars;
1261 if (Lookup.empty())
1262 LookForIvars = true;
1263 else if (IsClassMethod)
1264 LookForIvars = false;
1265 else
1266 LookForIvars = (Lookup.isSingleResult() &&
1267 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1268
1269 if (LookForIvars) {
1270 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1271 ObjCInterfaceDecl *ClassDeclared;
1272 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1273 // Diagnose using an ivar in a class method.
1274 if (IsClassMethod)
1275 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1276 << IV->getDeclName());
1277
1278 // If we're referencing an invalid decl, just return this as a silent
1279 // error node. The error diagnostic was already emitted on the decl.
1280 if (IV->isInvalidDecl())
1281 return ExprError();
1282
1283 // Check if referencing a field with __attribute__((deprecated)).
1284 if (DiagnoseUseOfDecl(IV, Loc))
1285 return ExprError();
1286
1287 // Diagnose the use of an ivar outside of the declaring class.
1288 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1289 ClassDeclared != IFace)
1290 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1291
1292 // FIXME: This should use a new expr for a direct reference, don't
1293 // turn this into Self->ivar, just return a BareIVarExpr or something.
1294 IdentifierInfo &II = Context.Idents.get("self");
1295 UnqualifiedId SelfName;
1296 SelfName.setIdentifier(&II, SourceLocation());
1297 CXXScopeSpec SelfScopeSpec;
1298 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1299 SelfName, false, false);
1300 MarkDeclarationReferenced(Loc, IV);
1301 return Owned(new (Context)
1302 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1303 SelfExpr.takeAs<Expr>(), true, true));
1304 }
1305 } else if (getCurMethodDecl()->isInstanceMethod()) {
1306 // We should warn if a local variable hides an ivar.
1307 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1308 ObjCInterfaceDecl *ClassDeclared;
1309 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1310 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1311 IFace == ClassDeclared)
1312 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1313 }
1314 }
1315
1316 // Needed to implement property "super.method" notation.
1317 if (Lookup.empty() && II->isStr("super")) {
1318 QualType T;
1319
1320 if (getCurMethodDecl()->isInstanceMethod())
1321 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1322 getCurMethodDecl()->getClassInterface()));
1323 else
1324 T = Context.getObjCClassType();
1325 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1326 }
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001327 if (Lookup.empty() && II && AllowBuiltinCreation) {
1328 // FIXME. Consolidate this with similar code in LookupName.
1329 if (unsigned BuiltinID = II->getBuiltinID()) {
1330 if (!(getLangOptions().CPlusPlus &&
1331 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1332 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1333 S, Lookup.isForRedeclaration(),
1334 Lookup.getNameLoc());
1335 if (D) Lookup.addDecl(D);
1336 }
1337 }
1338 }
John McCalle66edc12009-11-24 19:00:30 +00001339 // Sentinel value saying that we didn't do anything special.
1340 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001341}
John McCalld14a8642009-11-21 08:51:07 +00001342
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001343/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001344bool
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001345Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1346 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump11289f42009-09-09 15:08:12 +00001347 if (CXXRecordDecl *RD =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001348 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump11289f42009-09-09 15:08:12 +00001349 QualType DestType =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001350 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001351 if (DestType->isDependentType() || From->getType()->isDependentType())
1352 return false;
1353 QualType FromRecordType = From->getType();
1354 QualType DestRecordType = DestType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001355 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001356 DestType = Context.getPointerType(DestType);
1357 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001358 }
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001359 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1360 CheckDerivedToBaseConversion(FromRecordType,
1361 DestRecordType,
1362 From->getSourceRange().getBegin(),
1363 From->getSourceRange()))
1364 return true;
Anders Carlssona076d142009-07-31 01:23:52 +00001365 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1366 /*isLvalue=*/true);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001367 }
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001368 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001369}
Douglas Gregor3256d042009-06-30 15:47:41 +00001370
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001371/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001372static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001373 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalle66edc12009-11-24 19:00:30 +00001374 SourceLocation Loc, QualType Ty,
1375 const TemplateArgumentListInfo *TemplateArgs = 0) {
1376 NestedNameSpecifier *Qualifier = 0;
1377 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001378 if (SS.isSet()) {
1379 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1380 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001381 }
Mike Stump11289f42009-09-09 15:08:12 +00001382
John McCalle66edc12009-11-24 19:00:30 +00001383 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1384 Member, Loc, TemplateArgs, Ty);
Douglas Gregorc1905232009-08-26 22:36:53 +00001385}
1386
John McCall2d74de92009-12-01 22:10:20 +00001387/// Builds an implicit member access expression. The current context
1388/// is known to be an instance method, and the given unqualified lookup
1389/// set is known to contain only instance members, at least one of which
1390/// is from an appropriate type.
John McCallb53bbd42009-11-22 01:44:31 +00001391Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00001392Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1393 LookupResult &R,
1394 const TemplateArgumentListInfo *TemplateArgs,
1395 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00001396 assert(!R.empty() && !R.isAmbiguous());
1397
John McCalld14a8642009-11-21 08:51:07 +00001398 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00001399
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001400 // We may have found a field within an anonymous union or struct
1401 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00001402 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00001403 // FIXME: template-ids inside anonymous structs?
John McCall10eae182009-11-30 22:42:35 +00001404 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001405 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCallb53bbd42009-11-22 01:44:31 +00001406 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001407
John McCall2d74de92009-12-01 22:10:20 +00001408 // If this is known to be an instance access, go ahead and build a
1409 // 'this' expression now.
1410 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1411 Expr *This = 0; // null signifies implicit access
1412 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00001413 SourceLocation Loc = R.getNameLoc();
1414 if (SS.getRange().isValid())
1415 Loc = SS.getRange().getBegin();
1416 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001417 }
1418
John McCall2d74de92009-12-01 22:10:20 +00001419 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1420 /*OpLoc*/ SourceLocation(),
1421 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00001422 SS,
1423 /*FirstQualifierInScope*/ 0,
1424 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00001425}
1426
John McCalle66edc12009-11-24 19:00:30 +00001427bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001428 const LookupResult &R,
1429 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00001430 // Only when used directly as the postfix-expression of a call.
1431 if (!HasTrailingLParen)
1432 return false;
1433
1434 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00001435 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00001436 return false;
1437
1438 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00001439 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00001440 return false;
1441
1442 // Turn off ADL when we find certain kinds of declarations during
1443 // normal lookup:
1444 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1445 NamedDecl *D = *I;
1446
1447 // C++0x [basic.lookup.argdep]p3:
1448 // -- a declaration of a class member
1449 // Since using decls preserve this property, we check this on the
1450 // original decl.
John McCall57500772009-12-16 12:17:52 +00001451 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00001452 return false;
1453
1454 // C++0x [basic.lookup.argdep]p3:
1455 // -- a block-scope function declaration that is not a
1456 // using-declaration
1457 // NOTE: we also trigger this for function templates (in fact, we
1458 // don't check the decl type at all, since all other decl types
1459 // turn off ADL anyway).
1460 if (isa<UsingShadowDecl>(D))
1461 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1462 else if (D->getDeclContext()->isFunctionOrMethod())
1463 return false;
1464
1465 // C++0x [basic.lookup.argdep]p3:
1466 // -- a declaration that is neither a function or a function
1467 // template
1468 // And also for builtin functions.
1469 if (isa<FunctionDecl>(D)) {
1470 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1471
1472 // But also builtin functions.
1473 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1474 return false;
1475 } else if (!isa<FunctionTemplateDecl>(D))
1476 return false;
1477 }
1478
1479 return true;
1480}
1481
1482
John McCalld14a8642009-11-21 08:51:07 +00001483/// Diagnoses obvious problems with the use of the given declaration
1484/// as an expression. This is only actually called for lookups that
1485/// were not overloaded, and it doesn't promise that the declaration
1486/// will in fact be used.
1487static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1488 if (isa<TypedefDecl>(D)) {
1489 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1490 return true;
1491 }
1492
1493 if (isa<ObjCInterfaceDecl>(D)) {
1494 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1495 return true;
1496 }
1497
1498 if (isa<NamespaceDecl>(D)) {
1499 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1500 return true;
1501 }
1502
1503 return false;
1504}
1505
1506Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001507Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001508 LookupResult &R,
1509 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00001510 // If this is a single, fully-resolved result and we don't need ADL,
1511 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00001512 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
John McCallb53bbd42009-11-22 01:44:31 +00001513 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00001514
1515 // We only need to check the declaration if there's exactly one
1516 // result, because in the overloaded case the results can only be
1517 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00001518 if (R.isSingleResult() &&
1519 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00001520 return ExprError();
1521
John McCall58cc69d2010-01-27 01:50:18 +00001522 // Otherwise, just build an unresolved lookup expression. Suppress
1523 // any lookup-related diagnostics; we'll hash these out later, when
1524 // we've picked a target.
1525 R.suppressDiagnostics();
1526
John McCalle66edc12009-11-24 19:00:30 +00001527 bool Dependent
1528 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCalld14a8642009-11-21 08:51:07 +00001529 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001530 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001531 (NestedNameSpecifier*) SS.getScopeRep(),
1532 SS.getRange(),
John McCallb53bbd42009-11-22 01:44:31 +00001533 R.getLookupName(), R.getNameLoc(),
1534 NeedsADL, R.isOverloadedResult());
John McCall58cc69d2010-01-27 01:50:18 +00001535 ULE->addDecls(R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00001536
1537 return Owned(ULE);
1538}
1539
1540
1541/// \brief Complete semantic analysis for a reference to the given declaration.
1542Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001543Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCalld14a8642009-11-21 08:51:07 +00001544 SourceLocation Loc, NamedDecl *D) {
1545 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00001546 assert(!isa<FunctionTemplateDecl>(D) &&
1547 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00001548
1549 if (CheckDeclInExpr(*this, Loc, D))
1550 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00001551
Douglas Gregore7488b92009-12-01 16:58:18 +00001552 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1553 // Specifically diagnose references to class templates that are missing
1554 // a template argument list.
1555 Diag(Loc, diag::err_template_decl_ref)
1556 << Template << SS.getRange();
1557 Diag(Template->getLocation(), diag::note_template_decl_here);
1558 return ExprError();
1559 }
1560
1561 // Make sure that we're referring to a value.
1562 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1563 if (!VD) {
1564 Diag(Loc, diag::err_ref_non_value)
1565 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00001566 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00001567 return ExprError();
1568 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001569
Douglas Gregor171c45a2009-02-18 21:56:37 +00001570 // Check whether this declaration can be used. Note that we suppress
1571 // this check when we're going to perform argument-dependent lookup
1572 // on this function name, because this might not be the function
1573 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00001574 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00001575 return ExprError();
1576
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001577 // Only create DeclRefExpr's for valid Decl's.
1578 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001579 return ExprError();
1580
Chris Lattner2a9d9892008-10-20 05:16:36 +00001581 // If the identifier reference is inside a block, and it refers to a value
1582 // that is outside the block, create a BlockDeclRefExpr instead of a
1583 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1584 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001585 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00001586 // We do not do this for things like enum constants, global variables, etc,
1587 // as they do not get snapshotted.
1588 //
1589 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stump7dafa0d2010-01-05 02:56:35 +00001590 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1591 Diag(Loc, diag::err_ref_vm_type);
1592 Diag(D->getLocation(), diag::note_declared_at);
1593 return ExprError();
1594 }
1595
Mike Stump8971a862010-01-05 03:10:36 +00001596 if (VD->getType()->isArrayType()) {
1597 Diag(Loc, diag::err_ref_array_type);
1598 Diag(D->getLocation(), diag::note_declared_at);
1599 return ExprError();
1600 }
1601
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001602 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001603 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001604 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001605 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001606 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001607 // This is to record that a 'const' was actually synthesize and added.
1608 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001609 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001610
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001611 ExprTy.addConst();
Mike Stump11289f42009-09-09 15:08:12 +00001612 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001613 constAdded));
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001614 }
1615 // If this reference is not in a block or if the referenced variable is
1616 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00001617
John McCalle66edc12009-11-24 19:00:30 +00001618 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001619}
Chris Lattnere168f762006-11-10 05:29:30 +00001620
Sebastian Redlffbcf962009-01-18 18:53:16 +00001621Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1622 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001623 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001624
Chris Lattnere168f762006-11-10 05:29:30 +00001625 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001626 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00001627 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1628 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1629 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00001630 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001631
Chris Lattnera81a0272008-01-12 08:14:25 +00001632 // Pre-defined identifiers are of type char[x], where x is the length of the
1633 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001634
Anders Carlsson2fb08242009-09-08 18:24:21 +00001635 Decl *currentDecl = getCurFunctionOrMethodDecl();
1636 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001637 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001638 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001639 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001640
Anders Carlsson0b209a82009-09-11 01:22:35 +00001641 QualType ResTy;
1642 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1643 ResTy = Context.DependentTy;
1644 } else {
1645 unsigned Length =
1646 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001647
Anders Carlsson0b209a82009-09-11 01:22:35 +00001648 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001649 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001650 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1651 }
Steve Narofff6009ed2009-01-21 00:14:39 +00001652 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001653}
1654
Sebastian Redlffbcf962009-01-18 18:53:16 +00001655Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001656 llvm::SmallString<16> CharBuffer;
Steve Naroffae4143e2007-04-26 20:39:23 +00001657 CharBuffer.resize(Tok.getLength());
1658 const char *ThisTokBegin = &CharBuffer[0];
1659 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001660
Steve Naroffae4143e2007-04-26 20:39:23 +00001661 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1662 Tok.getLocation(), PP);
1663 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001664 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001665
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001666 QualType Ty;
1667 if (!getLangOptions().CPlusPlus)
1668 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1669 else if (Literal.isWide())
1670 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00001671 else if (Literal.isMultiChar())
1672 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001673 else
1674 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00001675
Sebastian Redl20614a72009-01-20 22:23:13 +00001676 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1677 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001678 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001679}
1680
Sebastian Redlffbcf962009-01-18 18:53:16 +00001681Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1682 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00001683 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1684 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001685 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001686 unsigned IntSize = Context.Target.getIntWidth();
Steve Narofff6009ed2009-01-21 00:14:39 +00001687 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001688 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001689 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001690
Chris Lattner23b7eb62007-06-15 23:05:46 +00001691 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001692 // Add padding so that NumericLiteralParser can overread by one character.
1693 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001694 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001695
Chris Lattner67ca9252007-05-21 01:08:44 +00001696 // Get the spelling of the token, which eliminates trigraphs, etc.
Steve Naroff8160ea22007-03-06 01:09:46 +00001697 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001698
Mike Stump11289f42009-09-09 15:08:12 +00001699 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001700 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001701 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001702 return ExprError();
1703
Chris Lattner1c20a172007-08-26 03:42:43 +00001704 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001705
Chris Lattner1c20a172007-08-26 03:42:43 +00001706 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001707 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001708 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001709 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001710 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001711 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001712 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001713 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001714
1715 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1716
John McCall53b93a02009-12-24 09:08:04 +00001717 using llvm::APFloat;
1718 APFloat Val(Format);
1719
1720 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00001721
1722 // Overflow is always an error, but underflow is only an error if
1723 // we underflowed to zero (APFloat reports denormals as underflow).
1724 if ((result & APFloat::opOverflow) ||
1725 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00001726 unsigned diagnostic;
1727 llvm::SmallVector<char, 20> buffer;
1728 if (result & APFloat::opOverflow) {
1729 diagnostic = diag::err_float_overflow;
1730 APFloat::getLargest(Format).toString(buffer);
1731 } else {
1732 diagnostic = diag::err_float_underflow;
1733 APFloat::getSmallest(Format).toString(buffer);
1734 }
1735
1736 Diag(Tok.getLocation(), diagnostic)
1737 << Ty
1738 << llvm::StringRef(buffer.data(), buffer.size());
1739 }
1740
1741 bool isExact = (result == APFloat::opOK);
Chris Lattnere4edb8e2009-06-29 17:34:55 +00001742 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00001743
Chris Lattner1c20a172007-08-26 03:42:43 +00001744 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001745 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00001746 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001747 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00001748
Neil Boothac582c52007-08-29 22:00:19 +00001749 // long long is a C99 feature.
1750 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00001751 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00001752 Diag(Tok.getLocation(), diag::ext_longlong);
1753
Chris Lattner67ca9252007-05-21 01:08:44 +00001754 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00001755 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001756
Chris Lattner67ca9252007-05-21 01:08:44 +00001757 if (Literal.GetIntegerValue(ResultVal)) {
1758 // If this value didn't fit into uintmax_t, warn and force to ull.
1759 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001760 Ty = Context.UnsignedLongLongTy;
1761 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00001762 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00001763 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00001764 // If this value fits into a ULL, try to figure out what else it fits into
1765 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001766
Chris Lattner67ca9252007-05-21 01:08:44 +00001767 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1768 // be an unsigned int.
1769 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1770
1771 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00001772 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00001773 if (!Literal.isLong && !Literal.isLongLong) {
1774 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00001775 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001776
Chris Lattner67ca9252007-05-21 01:08:44 +00001777 // Does it fit in a unsigned int?
1778 if (ResultVal.isIntN(IntSize)) {
1779 // Does it fit in a signed int?
1780 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001781 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001782 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001783 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001784 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001785 }
Chris Lattner67ca9252007-05-21 01:08:44 +00001786 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001787
Chris Lattner67ca9252007-05-21 01:08:44 +00001788 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001789 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001790 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001791
Chris Lattner67ca9252007-05-21 01:08:44 +00001792 // Does it fit in a unsigned long?
1793 if (ResultVal.isIntN(LongSize)) {
1794 // Does it fit in a signed long?
1795 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001796 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001797 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001798 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001799 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001800 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001801 }
1802
Chris Lattner67ca9252007-05-21 01:08:44 +00001803 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001804 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001805 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001806
Chris Lattner67ca9252007-05-21 01:08:44 +00001807 // Does it fit in a unsigned long long?
1808 if (ResultVal.isIntN(LongLongSize)) {
1809 // Does it fit in a signed long long?
1810 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001811 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001812 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001813 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001814 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001815 }
1816 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001817
Chris Lattner67ca9252007-05-21 01:08:44 +00001818 // If we still couldn't decide a type, we probably have something that
1819 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001820 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00001821 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001822 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001823 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00001824 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001825
Chris Lattner55258cf2008-05-09 05:59:00 +00001826 if (ResultVal.getBitWidth() != Width)
1827 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00001828 }
Sebastian Redl20614a72009-01-20 22:23:13 +00001829 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00001830 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001831
Chris Lattner1c20a172007-08-26 03:42:43 +00001832 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1833 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00001834 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00001835 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00001836
1837 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00001838}
1839
Sebastian Redlffbcf962009-01-18 18:53:16 +00001840Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1841 SourceLocation R, ExprArg Val) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001842 Expr *E = Val.takeAs<Expr>();
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001843 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00001844 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00001845}
1846
Steve Naroff71b59a92007-06-04 22:22:31 +00001847/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00001848/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001849bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00001850 SourceLocation OpLoc,
1851 const SourceRange &ExprRange,
1852 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001853 if (exprType->isDependentType())
1854 return false;
1855
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001856 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1857 // the result is the size of the referenced type."
1858 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1859 // result shall be the alignment of the referenced type."
1860 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1861 exprType = Ref->getPointeeType();
1862
Steve Naroff043d45d2007-05-15 02:32:35 +00001863 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00001864 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001865 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001866 if (isSizeof)
1867 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1868 return false;
1869 }
Mike Stump11289f42009-09-09 15:08:12 +00001870
Chris Lattner62975a72009-04-24 00:30:45 +00001871 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001872 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001873 Diag(OpLoc, diag::ext_sizeof_void_type)
1874 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00001875 return false;
1876 }
Mike Stump11289f42009-09-09 15:08:12 +00001877
Chris Lattner62975a72009-04-24 00:30:45 +00001878 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00001879 PDiag(diag::err_sizeof_alignof_incomplete_type)
1880 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00001881 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001882
Chris Lattner62975a72009-04-24 00:30:45 +00001883 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanian1dcb3222009-04-24 17:34:33 +00001884 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001885 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00001886 << exprType << isSizeof << ExprRange;
1887 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00001888 }
Mike Stump11289f42009-09-09 15:08:12 +00001889
Chris Lattner62975a72009-04-24 00:30:45 +00001890 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00001891}
1892
Chris Lattner8dff0172009-01-24 20:17:12 +00001893bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1894 const SourceRange &ExprRange) {
1895 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001896
Mike Stump11289f42009-09-09 15:08:12 +00001897 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00001898 if (isa<DeclRefExpr>(E))
1899 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001900
1901 // Cannot know anything else if the expression is dependent.
1902 if (E->isTypeDependent())
1903 return false;
1904
Douglas Gregor71235ec2009-05-02 02:18:30 +00001905 if (E->getBitField()) {
1906 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1907 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00001908 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00001909
1910 // Alignment of a field access is always okay, so long as it isn't a
1911 // bit-field.
1912 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00001913 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00001914 return false;
1915
Chris Lattner8dff0172009-01-24 20:17:12 +00001916 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1917}
1918
Douglas Gregor0950e412009-03-13 21:01:28 +00001919/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump11289f42009-09-09 15:08:12 +00001920Action::OwningExprResult
John McCallbcd03502009-12-07 02:54:59 +00001921Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00001922 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001923 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00001924 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00001925 return ExprError();
1926
John McCallbcd03502009-12-07 02:54:59 +00001927 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00001928
Douglas Gregor0950e412009-03-13 21:01:28 +00001929 if (!T->isDependentType() &&
1930 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1931 return ExprError();
1932
1933 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00001934 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00001935 Context.getSizeType(), OpLoc,
1936 R.getEnd()));
1937}
1938
1939/// \brief Build a sizeof or alignof expression given an expression
1940/// operand.
Mike Stump11289f42009-09-09 15:08:12 +00001941Action::OwningExprResult
1942Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001943 bool isSizeOf, SourceRange R) {
1944 // Verify that the operand is valid.
1945 bool isInvalid = false;
1946 if (E->isTypeDependent()) {
1947 // Delay type-checking for type-dependent expressions.
1948 } else if (!isSizeOf) {
1949 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00001950 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00001951 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1952 isInvalid = true;
1953 } else {
1954 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1955 }
1956
1957 if (isInvalid)
1958 return ExprError();
1959
1960 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1961 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1962 Context.getSizeType(), OpLoc,
1963 R.getEnd()));
1964}
1965
Sebastian Redl6f282892008-11-11 17:56:53 +00001966/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1967/// the same for @c alignof and @c __alignof
1968/// Note that the ArgRange is invalid if isType is false.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001969Action::OwningExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00001970Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1971 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001972 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001973 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00001974
Sebastian Redl6f282892008-11-11 17:56:53 +00001975 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00001976 TypeSourceInfo *TInfo;
1977 (void) GetTypeFromParser(TyOrEx, &TInfo);
1978 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00001979 }
Sebastian Redl6f282892008-11-11 17:56:53 +00001980
Douglas Gregor0950e412009-03-13 21:01:28 +00001981 Expr *ArgEx = (Expr *)TyOrEx;
1982 Action::OwningExprResult Result
1983 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1984
1985 if (Result.isInvalid())
1986 DeleteExpr(ArgEx);
1987
1988 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00001989}
1990
Chris Lattner709322b2009-02-17 08:12:06 +00001991QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001992 if (V->isTypeDependent())
1993 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00001994
Chris Lattnere267f5d2007-08-26 05:39:26 +00001995 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00001996 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00001997 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001998
Chris Lattnere267f5d2007-08-26 05:39:26 +00001999 // Otherwise they pass through real integer and floating point types here.
2000 if (V->getType()->isArithmeticType())
2001 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002002
Chris Lattnere267f5d2007-08-26 05:39:26 +00002003 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00002004 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
2005 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002006 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002007}
2008
2009
Chris Lattnere168f762006-11-10 05:29:30 +00002010
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002011Action::OwningExprResult
2012Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2013 tok::TokenKind Kind, ExprArg Input) {
Chris Lattnere168f762006-11-10 05:29:30 +00002014 UnaryOperator::Opcode Opc;
2015 switch (Kind) {
2016 default: assert(0 && "Unknown unary op!");
2017 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
2018 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
2019 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002020
Eli Friedmancfdd40c2009-11-18 03:38:04 +00002021 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Chris Lattnere168f762006-11-10 05:29:30 +00002022}
2023
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002024Action::OwningExprResult
2025Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
2026 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002027 // Since this might be a postfix expression, get rid of ParenListExprs.
2028 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2029
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002030 Expr *LHSExp = static_cast<Expr*>(Base.get()),
2031 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump11289f42009-09-09 15:08:12 +00002032
Douglas Gregor40412ac2008-11-19 17:17:41 +00002033 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002034 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2035 Base.release();
2036 Idx.release();
2037 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2038 Context.DependentTy, RLoc));
2039 }
2040
Mike Stump11289f42009-09-09 15:08:12 +00002041 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002042 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002043 LHSExp->getType()->isEnumeralType() ||
2044 RHSExp->getType()->isRecordType() ||
2045 RHSExp->getType()->isEnumeralType())) {
Sebastian Redladba46e2009-10-29 20:17:01 +00002046 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor40412ac2008-11-19 17:17:41 +00002047 }
2048
Sebastian Redladba46e2009-10-29 20:17:01 +00002049 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
2050}
2051
2052
2053Action::OwningExprResult
2054Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
2055 ExprArg Idx, SourceLocation RLoc) {
2056 Expr *LHSExp = static_cast<Expr*>(Base.get());
2057 Expr *RHSExp = static_cast<Expr*>(Idx.get());
2058
Chris Lattner36d572b2007-07-16 00:14:47 +00002059 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002060 if (!LHSExp->getType()->getAs<VectorType>())
2061 DefaultFunctionArrayLvalueConversion(LHSExp);
2062 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002063
Chris Lattner36d572b2007-07-16 00:14:47 +00002064 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00002065
Steve Naroffc1aadb12007-03-28 21:49:40 +00002066 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002067 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002068 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002069 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002070 Expr *BaseExpr, *IndexExpr;
2071 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002072 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2073 BaseExpr = LHSExp;
2074 IndexExpr = RHSExp;
2075 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002076 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002077 BaseExpr = LHSExp;
2078 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002079 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002080 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002081 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002082 BaseExpr = RHSExp;
2083 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002084 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002085 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002086 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002087 BaseExpr = LHSExp;
2088 IndexExpr = RHSExp;
2089 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002090 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002091 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002092 // Handle the uncommon case of "123[Ptr]".
2093 BaseExpr = RHSExp;
2094 IndexExpr = LHSExp;
2095 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00002096 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00002097 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00002098 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00002099
Chris Lattner36d572b2007-07-16 00:14:47 +00002100 // FIXME: need to deal with const...
2101 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002102 } else if (LHSTy->isArrayType()) {
2103 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00002104 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00002105 // wasn't promoted because of the C90 rule that doesn't
2106 // allow promoting non-lvalue arrays. Warn, then
2107 // force the promotion here.
2108 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2109 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002110 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2111 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002112 LHSTy = LHSExp->getType();
2113
2114 BaseExpr = LHSExp;
2115 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002116 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002117 } else if (RHSTy->isArrayType()) {
2118 // Same as previous, except for 123[f().a] case
2119 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2120 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002121 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2122 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002123 RHSTy = RHSExp->getType();
2124
2125 BaseExpr = RHSExp;
2126 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002127 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00002128 } else {
Chris Lattner003af242009-04-25 22:50:55 +00002129 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2130 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002131 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00002132 // C99 6.5.2.1p1
Nate Begeman5ec4b312009-08-10 23:49:36 +00002133 if (!(IndexExpr->getType()->isIntegerType() &&
2134 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00002135 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2136 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00002137
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002138 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00002139 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2140 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00002141 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2142
Douglas Gregorac1fb652009-03-24 19:52:54 +00002143 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00002144 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2145 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00002146 // incomplete types are not object types.
2147 if (ResultType->isFunctionType()) {
2148 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2149 << ResultType << BaseExpr->getSourceRange();
2150 return ExprError();
2151 }
Mike Stump11289f42009-09-09 15:08:12 +00002152
Douglas Gregorac1fb652009-03-24 19:52:54 +00002153 if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00002154 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00002155 PDiag(diag::err_subscript_incomplete_type)
2156 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00002157 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002158
Chris Lattner62975a72009-04-24 00:30:45 +00002159 // Diagnose bad cases where we step over interface counts.
2160 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
2161 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2162 << ResultType << BaseExpr->getSourceRange();
2163 return ExprError();
2164 }
Mike Stump11289f42009-09-09 15:08:12 +00002165
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002166 Base.release();
2167 Idx.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002168 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00002169 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00002170}
2171
Steve Narofff8fd09e2007-07-27 22:15:19 +00002172QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002173CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002174 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00002175 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00002176 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2177 // see FIXME there.
2178 //
2179 // FIXME: This logic can be greatly simplified by splitting it along
2180 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00002181 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002182
Steve Narofff8fd09e2007-07-27 22:15:19 +00002183 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002184 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002185
Mike Stump4e1f26a2009-02-19 03:04:26 +00002186 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00002187 // special names that indicate a subset of exactly half the elements are
2188 // to be selected.
2189 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002190
Nate Begemanbb70bf62009-01-18 01:47:54 +00002191 // This flag determines whether or not CompName has an 's' char prefix,
2192 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00002193 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00002194
2195 // Check that we've found one of the special components, or that the component
2196 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002197 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002198 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2199 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00002200 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002201 do
2202 compStr++;
2203 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00002204 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002205 do
2206 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002207 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00002208 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002209
Mike Stump4e1f26a2009-02-19 03:04:26 +00002210 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002211 // We didn't get to the end of the string. This means the component names
2212 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner3b054132008-11-19 05:08:23 +00002213 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2214 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002215 return QualType();
2216 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002217
Nate Begemanbb70bf62009-01-18 01:47:54 +00002218 // Ensure no component accessor exceeds the width of the vector type it
2219 // operates on.
2220 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002221 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002222
2223 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002224 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002225
2226 while (*compStr) {
2227 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2228 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2229 << baseType << SourceRange(CompLoc);
2230 return QualType();
2231 }
2232 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002233 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002234
Steve Narofff8fd09e2007-07-27 22:15:19 +00002235 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002236 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002237 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002238 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002239 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00002240 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002241 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002242 if (HexSwizzle)
2243 CompSize--;
2244
Steve Narofff8fd09e2007-07-27 22:15:19 +00002245 if (CompSize == 1)
2246 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002247
Nate Begemance4d7fc2008-04-18 23:10:10 +00002248 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002249 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00002250 // diagostics look bad. We want extended vector types to appear built-in.
2251 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2252 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2253 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00002254 }
2255 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00002256}
2257
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002258static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00002259 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002260 const Selector &Sel,
2261 ASTContext &Context) {
Mike Stump11289f42009-09-09 15:08:12 +00002262
Anders Carlssonf571c112009-08-26 18:25:21 +00002263 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002264 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002265 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002266 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00002267
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002268 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2269 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002270 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002271 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002272 return D;
2273 }
2274 return 0;
2275}
2276
Steve Narofffb4330f2009-06-17 22:40:22 +00002277static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlssonf571c112009-08-26 18:25:21 +00002278 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002279 const Selector &Sel,
2280 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002281 // Check protocols on qualified interfaces.
2282 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00002283 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002284 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002285 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002286 GDecl = PD;
2287 break;
2288 }
2289 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002290 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002291 GDecl = OMD;
2292 break;
2293 }
2294 }
2295 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002296 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002297 E = QIdTy->qual_end(); I != E; ++I) {
2298 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002299 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002300 if (GDecl)
2301 return GDecl;
2302 }
2303 }
2304 return GDecl;
2305}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00002306
John McCall10eae182009-11-30 22:42:35 +00002307Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002308Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2309 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002310 const CXXScopeSpec &SS,
2311 NamedDecl *FirstQualifierInScope,
2312 DeclarationName Name, SourceLocation NameLoc,
2313 const TemplateArgumentListInfo *TemplateArgs) {
2314 Expr *BaseExpr = Base.takeAs<Expr>();
2315
2316 // Even in dependent contexts, try to diagnose base expressions with
2317 // obviously wrong types, e.g.:
2318 //
2319 // T* t;
2320 // t.f;
2321 //
2322 // In Obj-C++, however, the above expression is valid, since it could be
2323 // accessing the 'f' property if T is an Obj-C interface. The extra check
2324 // allows this, while still reporting an error if T is a struct pointer.
2325 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00002326 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00002327 if (PT && (!getLangOptions().ObjC1 ||
2328 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00002329 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall10eae182009-11-30 22:42:35 +00002330 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00002331 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00002332 return ExprError();
2333 }
2334 }
2335
Douglas Gregorea0a0a92010-01-11 18:40:55 +00002336 assert(BaseType->isDependentType() || Name.isDependentName());
John McCall10eae182009-11-30 22:42:35 +00002337
2338 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2339 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00002340 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00002341 IsArrow, OpLoc,
2342 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2343 SS.getRange(),
2344 FirstQualifierInScope,
2345 Name, NameLoc,
2346 TemplateArgs));
2347}
2348
2349/// We know that the given qualified member reference points only to
2350/// declarations which do not belong to the static type of the base
2351/// expression. Diagnose the problem.
2352static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2353 Expr *BaseExpr,
2354 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002355 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002356 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00002357 // If this is an implicit member access, use a different set of
2358 // diagnostics.
2359 if (!BaseExpr)
2360 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00002361
2362 // FIXME: this is an exceedingly lame diagnostic for some of the more
2363 // complicated cases here.
John McCallcd4b4772009-12-02 03:53:29 +00002364 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall10eae182009-11-30 22:42:35 +00002365 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCallcd4b4772009-12-02 03:53:29 +00002366 << SS.getRange() << DC << BaseType;
John McCall10eae182009-11-30 22:42:35 +00002367}
2368
2369// Check whether the declarations we found through a nested-name
2370// specifier in a member expression are actually members of the base
2371// type. The restriction here is:
2372//
2373// C++ [expr.ref]p2:
2374// ... In these cases, the id-expression shall name a
2375// member of the class or of one of its base classes.
2376//
2377// So it's perfectly legitimate for the nested-name specifier to name
2378// an unrelated class, and for us to find an overload set including
2379// decls from classes which are not superclasses, as long as the decl
2380// we actually pick through overload resolution is from a superclass.
2381bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2382 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002383 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002384 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00002385 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2386 if (!BaseRT) {
2387 // We can't check this yet because the base type is still
2388 // dependent.
2389 assert(BaseType->isDependentType());
2390 return false;
2391 }
2392 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00002393
2394 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00002395 // If this is an implicit member reference and we find a
2396 // non-instance member, it's not an error.
2397 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2398 return false;
John McCall10eae182009-11-30 22:42:35 +00002399
John McCall2d74de92009-12-01 22:10:20 +00002400 // Note that we use the DC of the decl, not the underlying decl.
2401 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2402 while (RecordD->isAnonymousStructOrUnion())
2403 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2404
2405 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2406 MemberRecord.insert(RecordD->getCanonicalDecl());
2407
2408 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2409 return false;
2410 }
2411
John McCallcd4b4772009-12-02 03:53:29 +00002412 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00002413 return true;
2414}
2415
2416static bool
2417LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2418 SourceRange BaseRange, const RecordType *RTy,
2419 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2420 RecordDecl *RDecl = RTy->getDecl();
2421 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2422 PDiag(diag::err_typecheck_incomplete_tag)
2423 << BaseRange))
2424 return true;
2425
2426 DeclContext *DC = RDecl;
2427 if (SS.isSet()) {
2428 // If the member name was a qualified-id, look into the
2429 // nested-name-specifier.
2430 DC = SemaRef.computeDeclContext(SS, false);
2431
John McCallcd4b4772009-12-02 03:53:29 +00002432 if (SemaRef.RequireCompleteDeclContext(SS)) {
2433 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2434 << SS.getRange() << DC;
2435 return true;
2436 }
2437
John McCall2d74de92009-12-01 22:10:20 +00002438 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2439
2440 if (!isa<TypeDecl>(DC)) {
2441 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2442 << DC << SS.getRange();
2443 return true;
John McCall10eae182009-11-30 22:42:35 +00002444 }
2445 }
2446
John McCall2d74de92009-12-01 22:10:20 +00002447 // The record definition is complete, now look up the member.
2448 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00002449
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002450 if (!R.empty())
2451 return false;
2452
2453 // We didn't find anything with the given name, so try to correct
2454 // for typos.
2455 DeclarationName Name = R.getLookupName();
2456 if (SemaRef.CorrectTypo(R, 0, &SS, DC) &&
2457 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2458 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2459 << Name << DC << R.getLookupName() << SS.getRange()
2460 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
2461 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00002462 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2463 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2464 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002465 return false;
2466 } else {
2467 R.clear();
2468 }
2469
John McCall10eae182009-11-30 22:42:35 +00002470 return false;
2471}
2472
2473Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002474Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00002475 SourceLocation OpLoc, bool IsArrow,
2476 const CXXScopeSpec &SS,
2477 NamedDecl *FirstQualifierInScope,
2478 DeclarationName Name, SourceLocation NameLoc,
2479 const TemplateArgumentListInfo *TemplateArgs) {
2480 Expr *Base = BaseArg.takeAs<Expr>();
2481
John McCallcd4b4772009-12-02 03:53:29 +00002482 if (BaseType->isDependentType() ||
2483 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall2d74de92009-12-01 22:10:20 +00002484 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall10eae182009-11-30 22:42:35 +00002485 IsArrow, OpLoc,
2486 SS, FirstQualifierInScope,
2487 Name, NameLoc,
2488 TemplateArgs);
2489
2490 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00002491
John McCall2d74de92009-12-01 22:10:20 +00002492 // Implicit member accesses.
2493 if (!Base) {
2494 QualType RecordTy = BaseType;
2495 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2496 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2497 RecordTy->getAs<RecordType>(),
2498 OpLoc, SS))
2499 return ExprError();
2500
2501 // Explicit member accesses.
2502 } else {
2503 OwningExprResult Result =
2504 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall38836f02010-01-15 08:34:02 +00002505 SS, /*ObjCImpDecl*/ DeclPtrTy());
John McCall2d74de92009-12-01 22:10:20 +00002506
2507 if (Result.isInvalid()) {
2508 Owned(Base);
2509 return ExprError();
2510 }
2511
2512 if (Result.get())
2513 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00002514 }
2515
John McCall2d74de92009-12-01 22:10:20 +00002516 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
John McCall38836f02010-01-15 08:34:02 +00002517 OpLoc, IsArrow, SS, FirstQualifierInScope,
2518 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002519}
2520
2521Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002522Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2523 SourceLocation OpLoc, bool IsArrow,
2524 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00002525 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00002526 LookupResult &R,
2527 const TemplateArgumentListInfo *TemplateArgs) {
2528 Expr *BaseExpr = Base.takeAs<Expr>();
John McCall2d74de92009-12-01 22:10:20 +00002529 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00002530 if (IsArrow) {
2531 assert(BaseType->isPointerType());
2532 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2533 }
2534
2535 NestedNameSpecifier *Qualifier =
2536 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2537 DeclarationName MemberName = R.getLookupName();
2538 SourceLocation MemberLoc = R.getNameLoc();
2539
2540 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00002541 return ExprError();
2542
John McCall10eae182009-11-30 22:42:35 +00002543 if (R.empty()) {
2544 // Rederive where we looked up.
2545 DeclContext *DC = (SS.isSet()
2546 ? computeDeclContext(SS, false)
2547 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00002548
John McCall10eae182009-11-30 22:42:35 +00002549 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00002550 << MemberName << DC
2551 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00002552 return ExprError();
2553 }
2554
John McCall38836f02010-01-15 08:34:02 +00002555 // Diagnose lookups that find only declarations from a non-base
2556 // type. This is possible for either qualified lookups (which may
2557 // have been qualified with an unrelated type) or implicit member
2558 // expressions (which were found with unqualified lookup and thus
2559 // may have come from an enclosing scope). Note that it's okay for
2560 // lookup to find declarations from a non-base type as long as those
2561 // aren't the ones picked by overload resolution.
2562 if ((SS.isSet() || !BaseExpr ||
2563 (isa<CXXThisExpr>(BaseExpr) &&
2564 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
2565 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00002566 return ExprError();
2567
2568 // Construct an unresolved result if we in fact got an unresolved
2569 // result.
2570 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall2d74de92009-12-01 22:10:20 +00002571 bool Dependent =
John McCall71739032009-12-19 02:05:44 +00002572 BaseExprType->isDependentType() ||
John McCall2d74de92009-12-01 22:10:20 +00002573 R.isUnresolvableResult() ||
John McCall1acbbb52010-02-02 06:20:04 +00002574 OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002575
John McCall58cc69d2010-01-27 01:50:18 +00002576 // Suppress any lookup-related diagnostics; we'll do these when we
2577 // pick a member.
2578 R.suppressDiagnostics();
2579
John McCall10eae182009-11-30 22:42:35 +00002580 UnresolvedMemberExpr *MemExpr
2581 = UnresolvedMemberExpr::Create(Context, Dependent,
2582 R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00002583 BaseExpr, BaseExprType,
2584 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002585 Qualifier, SS.getRange(),
2586 MemberName, MemberLoc,
2587 TemplateArgs);
John McCall58cc69d2010-01-27 01:50:18 +00002588 MemExpr->addDecls(R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00002589
2590 return Owned(MemExpr);
2591 }
2592
2593 assert(R.isSingleResult());
2594 NamedDecl *MemberDecl = R.getFoundDecl();
2595
2596 // FIXME: diagnose the presence of template arguments now.
2597
2598 // If the decl being referenced had an error, return an error for this
2599 // sub-expr without emitting another error, in order to avoid cascading
2600 // error cases.
2601 if (MemberDecl->isInvalidDecl())
2602 return ExprError();
2603
John McCall2d74de92009-12-01 22:10:20 +00002604 // Handle the implicit-member-access case.
2605 if (!BaseExpr) {
2606 // If this is not an instance member, convert to a non-member access.
2607 if (!IsInstanceMember(MemberDecl))
2608 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2609
Douglas Gregorb15af892010-01-07 23:12:05 +00002610 SourceLocation Loc = R.getNameLoc();
2611 if (SS.getRange().isValid())
2612 Loc = SS.getRange().getBegin();
2613 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00002614 }
2615
John McCall10eae182009-11-30 22:42:35 +00002616 bool ShouldCheckUse = true;
2617 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2618 // Don't diagnose the use of a virtual member function unless it's
2619 // explicitly qualified.
2620 if (MD->isVirtual() && !SS.isSet())
2621 ShouldCheckUse = false;
2622 }
2623
2624 // Check the use of this member.
2625 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2626 Owned(BaseExpr);
2627 return ExprError();
2628 }
2629
2630 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2631 // We may have found a field within an anonymous union or struct
2632 // (C++ [class.union]).
Eli Friedman78cde142009-12-04 07:18:51 +00002633 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2634 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall10eae182009-11-30 22:42:35 +00002635 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2636 BaseExpr, OpLoc);
2637
2638 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2639 QualType MemberType = FD->getType();
2640 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2641 MemberType = Ref->getPointeeType();
2642 else {
2643 Qualifiers BaseQuals = BaseType.getQualifiers();
2644 BaseQuals.removeObjCGCAttr();
2645 if (FD->isMutable()) BaseQuals.removeConst();
2646
2647 Qualifiers MemberQuals
2648 = Context.getCanonicalType(MemberType).getQualifiers();
2649
2650 Qualifiers Combined = BaseQuals + MemberQuals;
2651 if (Combined != MemberQuals)
2652 MemberType = Context.getQualifiedType(MemberType, Combined);
2653 }
2654
2655 MarkDeclarationReferenced(MemberLoc, FD);
2656 if (PerformObjectMemberConversion(BaseExpr, FD))
2657 return ExprError();
2658 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2659 FD, MemberLoc, MemberType));
2660 }
2661
2662 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2663 MarkDeclarationReferenced(MemberLoc, Var);
2664 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2665 Var, MemberLoc,
2666 Var->getType().getNonReferenceType()));
2667 }
2668
2669 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2670 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2671 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2672 MemberFn, MemberLoc,
2673 MemberFn->getType()));
2674 }
2675
2676 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2677 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2678 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2679 Enum, MemberLoc, Enum->getType()));
2680 }
2681
2682 Owned(BaseExpr);
2683
2684 if (isa<TypeDecl>(MemberDecl))
2685 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2686 << MemberName << int(IsArrow));
2687
2688 // We found a declaration kind that we didn't expect. This is a
2689 // generic error message that tells the user that she can't refer
2690 // to this member with '.' or '->'.
2691 return ExprError(Diag(MemberLoc,
2692 diag::err_typecheck_member_reference_unknown)
2693 << MemberName << int(IsArrow));
2694}
2695
2696/// Look up the given member of the given non-type-dependent
2697/// expression. This can return in one of two ways:
2698/// * If it returns a sentinel null-but-valid result, the caller will
2699/// assume that lookup was performed and the results written into
2700/// the provided structure. It will take over from there.
2701/// * Otherwise, the returned expression will be produced in place of
2702/// an ordinary member expression.
2703///
2704/// The ObjCImpDecl bit is a gross hack that will need to be properly
2705/// fixed for ObjC++.
2706Sema::OwningExprResult
2707Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00002708 bool &IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002709 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002710 DeclPtrTy ObjCImpDecl) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00002711 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00002712
Steve Naroffeaaae462007-12-16 21:42:28 +00002713 // Perform default conversions.
2714 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002715
Steve Naroff185616f2007-07-26 03:11:44 +00002716 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00002717 assert(!BaseType->isDependentType());
2718
2719 DeclarationName MemberName = R.getLookupName();
2720 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00002721
2722 // If the user is trying to apply -> or . to a function pointer
John McCall10eae182009-11-30 22:42:35 +00002723 // type, it's probably because they forgot parentheses to call that
Douglas Gregord82ae382009-11-06 06:30:47 +00002724 // function. Suggest the addition of those parentheses, build the
2725 // call, and continue on.
2726 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2727 if (const FunctionProtoType *Fun
2728 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2729 QualType ResultTy = Fun->getResultType();
2730 if (Fun->getNumArgs() == 0 &&
John McCall10eae182009-11-30 22:42:35 +00002731 ((!IsArrow && ResultTy->isRecordType()) ||
2732 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregord82ae382009-11-06 06:30:47 +00002733 ResultTy->getAs<PointerType>()->getPointeeType()
2734 ->isRecordType()))) {
2735 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2736 Diag(Loc, diag::err_member_reference_needs_call)
2737 << QualType(Fun, 0)
2738 << CodeModificationHint::CreateInsertion(Loc, "()");
2739
2740 OwningExprResult NewBase
John McCall10eae182009-11-30 22:42:35 +00002741 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregord82ae382009-11-06 06:30:47 +00002742 MultiExprArg(*this, 0, 0), 0, Loc);
2743 if (NewBase.isInvalid())
John McCall10eae182009-11-30 22:42:35 +00002744 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00002745
2746 BaseExpr = NewBase.takeAs<Expr>();
2747 DefaultFunctionArrayConversion(BaseExpr);
2748 BaseType = BaseExpr->getType();
2749 }
2750 }
2751 }
2752
David Chisnall9f57c292009-08-17 16:35:33 +00002753 // If this is an Objective-C pseudo-builtin and a definition is provided then
2754 // use that.
2755 if (BaseType->isObjCIdType()) {
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002756 if (IsArrow) {
2757 // Handle the following exceptional case PObj->isa.
2758 if (const ObjCObjectPointerType *OPT =
2759 BaseType->getAs<ObjCObjectPointerType>()) {
2760 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2761 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00002762 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2763 Context.getObjCClassType()));
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002764 }
2765 }
David Chisnall9f57c292009-08-17 16:35:33 +00002766 // We have an 'id' type. Rather than fall through, we check if this
2767 // is a reference to 'isa'.
2768 if (BaseType != Context.ObjCIdRedefinitionType) {
2769 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002770 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00002771 }
David Chisnall9f57c292009-08-17 16:35:33 +00002772 }
John McCall10eae182009-11-30 22:42:35 +00002773
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00002774 // If this is an Objective-C pseudo-builtin and a definition is provided then
2775 // use that.
2776 if (Context.isObjCSelType(BaseType)) {
2777 // We have an 'SEL' type. Rather than fall through, we check if this
2778 // is a reference to 'sel_id'.
2779 if (BaseType != Context.ObjCSelRedefinitionType) {
2780 BaseType = Context.ObjCSelRedefinitionType;
2781 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2782 }
2783 }
John McCall10eae182009-11-30 22:42:35 +00002784
Steve Naroff185616f2007-07-26 03:11:44 +00002785 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002786
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002787 // Handle properties on ObjC 'Class' types.
John McCall10eae182009-11-30 22:42:35 +00002788 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002789 // Also must look for a getter name which uses property syntax.
2790 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2791 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2792 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2793 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2794 ObjCMethodDecl *Getter;
2795 // FIXME: need to also look locally in the implementation.
2796 if ((Getter = IFace->lookupClassMethod(Sel))) {
2797 // Check the use of this method.
2798 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2799 return ExprError();
2800 }
2801 // If we found a getter then this may be a valid dot-reference, we
2802 // will look for the matching setter, in case it is needed.
2803 Selector SetterSel =
2804 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2805 PP.getSelectorTable(), Member);
2806 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2807 if (!Setter) {
2808 // If this reference is in an @implementation, also check for 'private'
2809 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002810 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002811 }
2812 // Look through local category implementations associated with the class.
2813 if (!Setter)
2814 Setter = IFace->getCategoryClassMethod(SetterSel);
2815
2816 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2817 return ExprError();
2818
2819 if (Getter || Setter) {
2820 QualType PType;
2821
2822 if (Getter)
2823 PType = Getter->getResultType();
2824 else
2825 // Get the expression type from Setter's incoming parameter.
2826 PType = (*(Setter->param_end() -1))->getType();
2827 // FIXME: we must check that the setter has property type.
2828 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2829 PType,
2830 Setter, MemberLoc, BaseExpr));
2831 }
2832 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2833 << MemberName << BaseType);
2834 }
2835 }
2836
2837 if (BaseType->isObjCClassType() &&
2838 BaseType != Context.ObjCClassRedefinitionType) {
2839 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002840 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002841 }
Mike Stump11289f42009-09-09 15:08:12 +00002842
John McCall10eae182009-11-30 22:42:35 +00002843 if (IsArrow) {
2844 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00002845 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002846 else if (BaseType->isObjCObjectPointerType())
2847 ;
John McCalla928c652009-12-07 22:46:59 +00002848 else if (BaseType->isRecordType()) {
2849 // Recover from arrow accesses to records, e.g.:
2850 // struct MyRecord foo;
2851 // foo->bar
2852 // This is actually well-formed in C++ if MyRecord has an
2853 // overloaded operator->, but that should have been dealt with
2854 // by now.
2855 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2856 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2857 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2858 IsArrow = false;
2859 } else {
John McCall10eae182009-11-30 22:42:35 +00002860 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2861 << BaseType << BaseExpr->getSourceRange();
2862 return ExprError();
Anders Carlsson524d5a42009-05-16 20:31:20 +00002863 }
John McCalla928c652009-12-07 22:46:59 +00002864 } else {
2865 // Recover from dot accesses to pointers, e.g.:
2866 // type *foo;
2867 // foo.bar
2868 // This is actually well-formed in two cases:
2869 // - 'type' is an Objective C type
2870 // - 'bar' is a pseudo-destructor name which happens to refer to
2871 // the appropriate pointer type
2872 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
2873 const PointerType *PT = BaseType->getAs<PointerType>();
2874 if (PT && PT->getPointeeType()->isRecordType()) {
2875 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2876 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2877 << CodeModificationHint::CreateReplacement(OpLoc, "->");
2878 BaseType = PT->getPointeeType();
2879 IsArrow = true;
2880 }
2881 }
John McCall10eae182009-11-30 22:42:35 +00002882 }
John McCalla928c652009-12-07 22:46:59 +00002883
John McCall10eae182009-11-30 22:42:35 +00002884 // Handle field access to simple records. This also handles access
2885 // to fields of the ObjC 'id' struct.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002886 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCall2d74de92009-12-01 22:10:20 +00002887 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2888 RTy, OpLoc, SS))
Douglas Gregordd430f72009-01-19 19:26:10 +00002889 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00002890 return Owned((Expr*) 0);
Chris Lattnerb63a7452008-07-21 04:28:12 +00002891 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002892
Douglas Gregorad8a3362009-09-04 17:36:40 +00002893 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2894 // into a record type was handled above, any destructor we see here is a
2895 // pseudo-destructor.
2896 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2897 // C++ [expr.pseudo]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002898 // The left hand side of the dot operator shall be of scalar type. The
2899 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregorad8a3362009-09-04 17:36:40 +00002900 // type.
2901 if (!BaseType->isScalarType())
2902 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2903 << BaseType << BaseExpr->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +00002904
Douglas Gregorad8a3362009-09-04 17:36:40 +00002905 // [...] The type designated by the pseudo-destructor-name shall be the
2906 // same as the object type.
2907 if (!MemberName.getCXXNameType()->isDependentType() &&
2908 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2909 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2910 << BaseType << MemberName.getCXXNameType()
2911 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump11289f42009-09-09 15:08:12 +00002912
2913 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregorad8a3362009-09-04 17:36:40 +00002914 // the form
2915 //
Mike Stump11289f42009-09-09 15:08:12 +00002916 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2917 //
Douglas Gregorad8a3362009-09-04 17:36:40 +00002918 // shall designate the same scalar type.
2919 //
2920 // FIXME: DPG can't see any way to trigger this particular clause, so it
2921 // isn't checked here.
Mike Stump11289f42009-09-09 15:08:12 +00002922
Douglas Gregorad8a3362009-09-04 17:36:40 +00002923 // FIXME: We've lost the precise spelling of the type by going through
2924 // DeclarationName. Can we do better?
2925 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002926 IsArrow, OpLoc,
2927 (NestedNameSpecifier *) SS.getScopeRep(),
2928 SS.getRange(),
Douglas Gregorad8a3362009-09-04 17:36:40 +00002929 MemberName.getCXXNameType(),
2930 MemberLoc));
2931 }
Mike Stump11289f42009-09-09 15:08:12 +00002932
Chris Lattnerdc420f42008-07-21 04:59:05 +00002933 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2934 // (*Obj).ivar.
John McCall10eae182009-11-30 22:42:35 +00002935 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2936 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002937 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002938 const ObjCInterfaceType *IFaceT =
John McCall9dd450b2009-09-21 23:43:11 +00002939 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffa057ba92009-07-16 00:25:06 +00002940 if (IFaceT) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002941 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2942
Steve Naroffa057ba92009-07-16 00:25:06 +00002943 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2944 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00002945 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00002946
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002947 if (!IV) {
2948 // Attempt to correct for typos in ivar names.
2949 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
2950 LookupMemberName);
2951 if (CorrectTypo(Res, 0, 0, IDecl) &&
2952 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
2953 Diag(R.getNameLoc(),
2954 diag::err_typecheck_member_reference_ivar_suggest)
2955 << IDecl->getDeclName() << MemberName << IV->getDeclName()
2956 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
2957 IV->getNameAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00002958 Diag(IV->getLocation(), diag::note_previous_decl)
2959 << IV->getDeclName();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00002960 }
2961 }
2962
Steve Naroffa057ba92009-07-16 00:25:06 +00002963 if (IV) {
2964 // If the decl being referenced had an error, return an error for this
2965 // sub-expr without emitting another error, in order to avoid cascading
2966 // error cases.
2967 if (IV->isInvalidDecl())
2968 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002969
Steve Naroffa057ba92009-07-16 00:25:06 +00002970 // Check whether we can reference this field.
2971 if (DiagnoseUseOfDecl(IV, MemberLoc))
2972 return ExprError();
2973 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2974 IV->getAccessControl() != ObjCIvarDecl::Package) {
2975 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2976 if (ObjCMethodDecl *MD = getCurMethodDecl())
2977 ClassOfMethodDecl = MD->getClassInterface();
2978 else if (ObjCImpDecl && getCurFunctionDecl()) {
2979 // Case of a c-function declared inside an objc implementation.
2980 // FIXME: For a c-style function nested inside an objc implementation
2981 // class, there is no implementation context available, so we pass
2982 // down the context as argument to this routine. Ideally, this context
2983 // need be passed down in the AST node and somehow calculated from the
2984 // AST for a function decl.
2985 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump11289f42009-09-09 15:08:12 +00002986 if (ObjCImplementationDecl *IMPD =
Steve Naroffa057ba92009-07-16 00:25:06 +00002987 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2988 ClassOfMethodDecl = IMPD->getClassInterface();
2989 else if (ObjCCategoryImplDecl* CatImplClass =
2990 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2991 ClassOfMethodDecl = CatImplClass->getClassInterface();
2992 }
Mike Stump11289f42009-09-09 15:08:12 +00002993
2994 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2995 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00002996 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00002997 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002998 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00002999 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3000 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00003001 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00003002 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00003003 }
Steve Naroffa057ba92009-07-16 00:25:06 +00003004
3005 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3006 MemberLoc, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00003007 IsArrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00003008 }
Steve Naroffa057ba92009-07-16 00:25:06 +00003009 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00003010 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00003011 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00003012 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00003013 }
Steve Naroff1329fa02009-07-15 18:40:39 +00003014 // Handle properties on 'id' and qualified "id".
John McCall10eae182009-11-30 22:42:35 +00003015 if (!IsArrow && (BaseType->isObjCIdType() ||
3016 BaseType->isObjCQualifiedIdType())) {
John McCall9dd450b2009-09-21 23:43:11 +00003017 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00003018 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003019
Steve Naroff7cae42b2009-07-10 23:34:53 +00003020 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00003021 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003022 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
3023 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3024 // Check the use of this declaration
3025 if (DiagnoseUseOfDecl(PD, MemberLoc))
3026 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003027
Steve Naroff7cae42b2009-07-10 23:34:53 +00003028 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3029 MemberLoc, BaseExpr));
3030 }
3031 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3032 // Check the use of this method.
3033 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3034 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003035
Steve Naroff7cae42b2009-07-10 23:34:53 +00003036 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump11289f42009-09-09 15:08:12 +00003037 OMD->getResultType(),
3038 OMD, OpLoc, MemberLoc,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003039 NULL, 0));
3040 }
3041 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003042
Steve Naroff7cae42b2009-07-10 23:34:53 +00003043 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00003044 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003045 }
Chris Lattnerdc420f42008-07-21 04:59:05 +00003046 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3047 // pointer to a (potentially qualified) interface type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003048 const ObjCObjectPointerType *OPT;
John McCall10eae182009-11-30 22:42:35 +00003049 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003050 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
3051 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlssonf571c112009-08-26 18:25:21 +00003052 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003053
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003054 // Search for a declared property first.
Anders Carlssonf571c112009-08-26 18:25:21 +00003055 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003056 // Check whether we can reference this property.
3057 if (DiagnoseUseOfDecl(PD, MemberLoc))
3058 return ExprError();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00003059 QualType ResTy = PD->getType();
Anders Carlssonf571c112009-08-26 18:25:21 +00003060 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003061 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianfe9e3942009-05-08 20:20:55 +00003062 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
3063 ResTy = Getter->getResultType();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00003064 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner43df5562009-02-16 18:35:08 +00003065 MemberLoc, BaseExpr));
3066 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003067 // Check protocols on qualified interfaces.
Steve Naroffaccc4882009-07-20 17:56:53 +00003068 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3069 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00003070 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003071 // Check whether we can reference this property.
3072 if (DiagnoseUseOfDecl(PD, MemberLoc))
3073 return ExprError();
Chris Lattner43df5562009-02-16 18:35:08 +00003074
Steve Narofff6009ed2009-01-21 00:14:39 +00003075 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner43df5562009-02-16 18:35:08 +00003076 MemberLoc, BaseExpr));
3077 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003078 // If that failed, look for an "implicit" property by seeing if the nullary
3079 // selector is implemented.
3080
3081 // FIXME: The logic for looking up nullary and unary selectors should be
3082 // shared with the code in ActOnInstanceMessage.
3083
Anders Carlssonf571c112009-08-26 18:25:21 +00003084 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003085 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003086
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003087 // If this reference is in an @implementation, check for 'private' methods.
3088 if (!Getter)
Steve Naroffbb69c942009-10-01 23:46:04 +00003089 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003090
Steve Naroff1df62692008-10-22 19:16:27 +00003091 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00003092 if (!Getter)
3093 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00003094 if (Getter) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003095 // Check if we can reference this property.
3096 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3097 return ExprError();
Steve Naroff1d984fe2009-03-11 13:48:17 +00003098 }
3099 // If we found a getter then this may be a valid dot-reference, we
3100 // will look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00003101 Selector SetterSel =
3102 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlssonf571c112009-08-26 18:25:21 +00003103 PP.getSelectorTable(), Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003104 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00003105 if (!Setter) {
3106 // If this reference is in an @implementation, also check for 'private'
3107 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00003108 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00003109 }
3110 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00003111 if (!Setter)
3112 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003113
Steve Naroff1d984fe2009-03-11 13:48:17 +00003114 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3115 return ExprError();
3116
Fariborz Jahanianc1d2fa52010-01-19 17:48:02 +00003117 if (Getter) {
Steve Naroff1d984fe2009-03-11 13:48:17 +00003118 QualType PType;
Fariborz Jahanianc1d2fa52010-01-19 17:48:02 +00003119 PType = Getter->getResultType();
Fariborz Jahanian9a846652009-08-20 17:02:02 +00003120 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1d984fe2009-03-11 13:48:17 +00003121 Setter, MemberLoc, BaseExpr));
3122 }
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003123
3124 // Attempt to correct for typos in property names.
3125 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3126 LookupOrdinaryName);
3127 if (CorrectTypo(Res, 0, 0, IFace, false, OPT) &&
3128 Res.getAsSingle<ObjCPropertyDecl>()) {
3129 Diag(R.getNameLoc(), diag::err_property_not_found_suggest)
3130 << MemberName << BaseType << Res.getLookupName()
3131 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
3132 Res.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003133 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
3134 Diag(Property->getLocation(), diag::note_previous_decl)
3135 << Property->getDeclName();
3136
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003137 return LookupMemberExpr(Res, BaseExpr, IsArrow, OpLoc, SS,
John McCall38836f02010-01-15 08:34:02 +00003138 ObjCImpDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003139 }
3140
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003141 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00003142 << MemberName << BaseType);
Fariborz Jahanian21f54ee2007-11-12 22:29:28 +00003143 }
Mike Stump11289f42009-09-09 15:08:12 +00003144
Steve Naroffe87026a2009-07-24 17:54:45 +00003145 // Handle the following exceptional case (*Obj).isa.
John McCall10eae182009-11-30 22:42:35 +00003146 if (!IsArrow &&
Steve Naroffe87026a2009-07-24 17:54:45 +00003147 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlssonf571c112009-08-26 18:25:21 +00003148 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00003149 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00003150 Context.getObjCClassType()));
Steve Naroffe87026a2009-07-24 17:54:45 +00003151
Chris Lattnerb63a7452008-07-21 04:28:12 +00003152 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003153 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00003154 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00003155 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3156 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003157 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00003158 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00003159 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003160 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003161
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003162 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3163 << BaseType << BaseExpr->getSourceRange();
3164
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003165 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00003166}
3167
John McCall10eae182009-11-30 22:42:35 +00003168static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
3169 SourceLocation NameLoc,
3170 Sema::ExprArg MemExpr) {
3171 Expr *E = (Expr *) MemExpr.get();
3172 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
3173 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00003174 << isa<CXXPseudoDestructorExpr>(E)
3175 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
3176
John McCall10eae182009-11-30 22:42:35 +00003177 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
3178 move(MemExpr),
3179 /*LPLoc*/ ExpectedLParenLoc,
3180 Sema::MultiExprArg(SemaRef, 0, 0),
3181 /*CommaLocs*/ 0,
3182 /*RPLoc*/ ExpectedLParenLoc);
3183}
3184
3185/// The main callback when the parser finds something like
3186/// expression . [nested-name-specifier] identifier
3187/// expression -> [nested-name-specifier] identifier
3188/// where 'identifier' encompasses a fairly broad spectrum of
3189/// possibilities, including destructor and operator references.
3190///
3191/// \param OpKind either tok::arrow or tok::period
3192/// \param HasTrailingLParen whether the next token is '(', which
3193/// is used to diagnose mis-uses of special members that can
3194/// only be called
3195/// \param ObjCImpDecl the current ObjC @implementation decl;
3196/// this is an ugly hack around the fact that ObjC @implementations
3197/// aren't properly put in the context chain
3198Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3199 SourceLocation OpLoc,
3200 tok::TokenKind OpKind,
3201 const CXXScopeSpec &SS,
3202 UnqualifiedId &Id,
3203 DeclPtrTy ObjCImpDecl,
3204 bool HasTrailingLParen) {
3205 if (SS.isSet() && SS.isInvalid())
3206 return ExprError();
3207
3208 TemplateArgumentListInfo TemplateArgsBuffer;
3209
3210 // Decompose the name into its component parts.
3211 DeclarationName Name;
3212 SourceLocation NameLoc;
3213 const TemplateArgumentListInfo *TemplateArgs;
3214 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3215 Name, NameLoc, TemplateArgs);
3216
3217 bool IsArrow = (OpKind == tok::arrow);
3218
3219 NamedDecl *FirstQualifierInScope
3220 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3221 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3222
3223 // This is a postfix expression, so get rid of ParenListExprs.
3224 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3225
3226 Expr *Base = BaseArg.takeAs<Expr>();
3227 OwningExprResult Result(*this);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003228 if (Base->getType()->isDependentType() || Name.isDependentName()) {
John McCall2d74de92009-12-01 22:10:20 +00003229 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00003230 IsArrow, OpLoc,
3231 SS, FirstQualifierInScope,
3232 Name, NameLoc,
3233 TemplateArgs);
3234 } else {
3235 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3236 if (TemplateArgs) {
3237 // Re-use the lookup done for the template name.
3238 DecomposeTemplateName(R, Id);
3239 } else {
3240 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall38836f02010-01-15 08:34:02 +00003241 SS, ObjCImpDecl);
John McCall10eae182009-11-30 22:42:35 +00003242
3243 if (Result.isInvalid()) {
3244 Owned(Base);
3245 return ExprError();
3246 }
3247
3248 if (Result.get()) {
3249 // The only way a reference to a destructor can be used is to
3250 // immediately call it, which falls into this case. If the
3251 // next token is not a '(', produce a diagnostic and build the
3252 // call now.
3253 if (!HasTrailingLParen &&
3254 Id.getKind() == UnqualifiedId::IK_DestructorName)
3255 return DiagnoseDtorReference(*this, NameLoc, move(Result));
3256
3257 return move(Result);
3258 }
3259 }
3260
John McCall2d74de92009-12-01 22:10:20 +00003261 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00003262 OpLoc, IsArrow, SS, FirstQualifierInScope,
3263 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003264 }
3265
3266 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003267}
3268
Anders Carlsson355933d2009-08-25 03:49:14 +00003269Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3270 FunctionDecl *FD,
3271 ParmVarDecl *Param) {
3272 if (Param->hasUnparsedDefaultArg()) {
3273 Diag (CallLoc,
3274 diag::err_use_of_default_argument_to_function_declared_later) <<
3275 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003276 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00003277 diag::note_default_argument_declared_here);
3278 } else {
3279 if (Param->hasUninstantiatedDefaultArg()) {
3280 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3281
3282 // Instantiate the expression.
Douglas Gregor01afeef2009-08-28 20:31:08 +00003283 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson657bad42009-09-05 05:14:19 +00003284
Mike Stump11289f42009-09-09 15:08:12 +00003285 InstantiatingTemplate Inst(*this, CallLoc, Param,
3286 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00003287 ArgList.getInnermost().flat_size());
Anders Carlsson355933d2009-08-25 03:49:14 +00003288
John McCall76d824f2009-08-25 22:02:44 +00003289 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump11289f42009-09-09 15:08:12 +00003290 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003291 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003292
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003293 // Check the expression as an initializer for the parameter.
3294 InitializedEntity Entity
3295 = InitializedEntity::InitializeParameter(Param);
3296 InitializationKind Kind
3297 = InitializationKind::CreateCopy(Param->getLocation(),
3298 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3299 Expr *ResultE = Result.takeAs<Expr>();
3300
3301 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3302 Result = InitSeq.Perform(*this, Entity, Kind,
3303 MultiExprArg(*this, (void**)&ResultE, 1));
3304 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003305 return ExprError();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003306
3307 // Build the default argument expression.
Douglas Gregor033f6752009-12-23 23:03:06 +00003308 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003309 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003310 }
Mike Stump11289f42009-09-09 15:08:12 +00003311
Anders Carlsson355933d2009-08-25 03:49:14 +00003312 // If the default expression creates temporaries, we need to
3313 // push them to the current stack of expression temporaries so they'll
3314 // be properly destroyed.
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003315 // FIXME: We should really be rebuilding the default argument with new
3316 // bound temporaries; see the comment in PR5810.
Anders Carlsson714d0962009-12-15 19:16:31 +00003317 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3318 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson355933d2009-08-25 03:49:14 +00003319 }
3320
3321 // We already type-checked the argument, so we know it works.
Douglas Gregor033f6752009-12-23 23:03:06 +00003322 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003323}
3324
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003325/// ConvertArgumentsForCall - Converts the arguments specified in
3326/// Args/NumArgs to the parameter types of the function FDecl with
3327/// function prototype Proto. Call is the call expression itself, and
3328/// Fn is the function expression. For a C++ member function, this
3329/// routine does not attempt to convert the object argument. Returns
3330/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003331bool
3332Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003333 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003334 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003335 Expr **Args, unsigned NumArgs,
3336 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003337 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003338 // assignment, to the types of the corresponding parameter, ...
3339 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003340 bool Invalid = false;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003341
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003342 // If too few arguments are available (and we don't have default
3343 // arguments for the remaining parameters), don't make the call.
3344 if (NumArgs < NumArgsInProto) {
3345 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3346 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3347 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003348 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003349 }
3350
3351 // If too many are passed and not variadic, error on the extras and drop
3352 // them.
3353 if (NumArgs > NumArgsInProto) {
3354 if (!Proto->isVariadic()) {
3355 Diag(Args[NumArgsInProto]->getLocStart(),
3356 diag::err_typecheck_call_too_many_args)
3357 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3358 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3359 Args[NumArgs-1]->getLocEnd());
3360 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003361 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003362 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003363 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003364 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003365 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003366 VariadicCallType CallType =
3367 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3368 if (Fn->getType()->isBlockPointerType())
3369 CallType = VariadicBlock; // Block
3370 else if (isa<MemberExpr>(Fn))
3371 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003372 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003373 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003374 if (Invalid)
3375 return true;
3376 unsigned TotalNumArgs = AllArgs.size();
3377 for (unsigned i = 0; i < TotalNumArgs; ++i)
3378 Call->setArg(i, AllArgs[i]);
3379
3380 return false;
3381}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003382
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003383bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3384 FunctionDecl *FDecl,
3385 const FunctionProtoType *Proto,
3386 unsigned FirstProtoArg,
3387 Expr **Args, unsigned NumArgs,
3388 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003389 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003390 unsigned NumArgsInProto = Proto->getNumArgs();
3391 unsigned NumArgsToCheck = NumArgs;
3392 bool Invalid = false;
3393 if (NumArgs != NumArgsInProto)
3394 // Use default arguments for missing arguments
3395 NumArgsToCheck = NumArgsInProto;
3396 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003397 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003398 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003399 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003400
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003401 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003402 if (ArgIx < NumArgs) {
3403 Arg = Args[ArgIx++];
3404
Eli Friedman3164fb12009-03-22 22:00:50 +00003405 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3406 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003407 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003408 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003409 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003410
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003411 // Pass the argument
3412 ParmVarDecl *Param = 0;
3413 if (FDecl && i < FDecl->getNumParams())
3414 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003415
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003416
3417 InitializedEntity Entity =
3418 Param? InitializedEntity::InitializeParameter(Param)
3419 : InitializedEntity::InitializeParameter(ProtoArgType);
3420 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3421 SourceLocation(),
3422 Owned(Arg));
3423 if (ArgE.isInvalid())
3424 return true;
3425
3426 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003427 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003428 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003429
Mike Stump11289f42009-09-09 15:08:12 +00003430 OwningExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003431 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003432 if (ArgExpr.isInvalid())
3433 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003434
Anders Carlsson355933d2009-08-25 03:49:14 +00003435 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003436 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003437 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003438 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003439
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003440 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003441 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003442 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003443 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003444 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00003445 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003446 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003447 }
3448 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003449 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003450}
3451
Steve Naroff83895f72007-09-16 03:34:24 +00003452/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003453/// This provides the location of the left/right parens and a list of comma
3454/// locations.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003455Action::OwningExprResult
3456Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3457 MultiExprArg args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003458 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003459 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003460
3461 // Since this might be a postfix expression, get rid of ParenListExprs.
3462 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump11289f42009-09-09 15:08:12 +00003463
Anders Carlsson3cbc8592009-05-01 19:30:39 +00003464 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003465 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner38dbdb22007-07-21 03:03:59 +00003466 assert(Fn && "no function call expression");
Mike Stump11289f42009-09-09 15:08:12 +00003467
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003468 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003469 // If this is a pseudo-destructor expression, build the call immediately.
3470 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3471 if (NumArgs > 0) {
3472 // Pseudo-destructor calls should not have any arguments.
3473 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3474 << CodeModificationHint::CreateRemoval(
3475 SourceRange(Args[0]->getLocStart(),
3476 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003477
Douglas Gregorad8a3362009-09-04 17:36:40 +00003478 for (unsigned I = 0; I != NumArgs; ++I)
3479 Args[I]->Destroy(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003480
Douglas Gregorad8a3362009-09-04 17:36:40 +00003481 NumArgs = 0;
3482 }
Mike Stump11289f42009-09-09 15:08:12 +00003483
Douglas Gregorad8a3362009-09-04 17:36:40 +00003484 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3485 RParenLoc));
3486 }
Mike Stump11289f42009-09-09 15:08:12 +00003487
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003488 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003489 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003490 // FIXME: Will need to cache the results of name lookup (including ADL) in
3491 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003492 bool Dependent = false;
3493 if (Fn->isTypeDependent())
3494 Dependent = true;
3495 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3496 Dependent = true;
3497
3498 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003499 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003500 Context.DependentTy, RParenLoc));
3501
3502 // Determine whether this is a call to an object (C++ [over.call.object]).
3503 if (Fn->getType()->isRecordType())
3504 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3505 CommaLocs, RParenLoc));
3506
John McCall10eae182009-11-30 22:42:35 +00003507 Expr *NakedFn = Fn->IgnoreParens();
3508
3509 // Determine whether this is a call to an unresolved member function.
3510 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3511 // If lookup was unresolved but not dependent (i.e. didn't find
3512 // an unresolved using declaration), it has to be an overloaded
3513 // function set, which means it must contain either multiple
3514 // declarations (all methods or method templates) or a single
3515 // method template.
3516 assert((MemE->getNumDecls() > 1) ||
3517 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00003518 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00003519
John McCall2d74de92009-12-01 22:10:20 +00003520 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3521 CommaLocs, RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003522 }
3523
Douglas Gregore254f902009-02-04 00:32:51 +00003524 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00003525 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003526 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00003527 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00003528 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3529 CommaLocs, RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003530 }
Anders Carlsson61914b52009-10-03 17:40:22 +00003531
3532 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00003533 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson61914b52009-10-03 17:40:22 +00003534 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3535 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003536 if (const FunctionProtoType *FPT =
3537 dyn_cast<FunctionProtoType>(BO->getType())) {
3538 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson61914b52009-10-03 17:40:22 +00003539
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003540 ExprOwningPtr<CXXMemberCallExpr>
3541 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3542 NumArgs, ResultTy,
3543 RParenLoc));
Anders Carlsson61914b52009-10-03 17:40:22 +00003544
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003545 if (CheckCallReturnType(FPT->getResultType(),
3546 BO->getRHS()->getSourceRange().getBegin(),
3547 TheCall.get(), 0))
3548 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00003549
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003550 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3551 RParenLoc))
3552 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00003553
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003554 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3555 }
3556 return ExprError(Diag(Fn->getLocStart(),
3557 diag::err_typecheck_call_not_function)
3558 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00003559 }
3560 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003561 }
3562
Douglas Gregore254f902009-02-04 00:32:51 +00003563 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003564 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00003565 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003566
Eli Friedmane14b1992009-12-26 03:35:45 +00003567 Expr *NakedFn = Fn->IgnoreParens();
John McCall57500772009-12-16 12:17:52 +00003568 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3569 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
3570 return BuildOverloadedCallExpr(Fn, ULE, LParenLoc, Args, NumArgs,
3571 CommaLocs, RParenLoc);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003572 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003573
John McCall57500772009-12-16 12:17:52 +00003574 NamedDecl *NDecl = 0;
3575 if (isa<DeclRefExpr>(NakedFn))
3576 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3577
John McCall2d74de92009-12-01 22:10:20 +00003578 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3579}
3580
John McCall57500772009-12-16 12:17:52 +00003581/// BuildResolvedCallExpr - Build a call to a resolved expression,
3582/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003583/// unary-convert to an expression of function-pointer or
3584/// block-pointer type.
3585///
3586/// \param NDecl the declaration being called, if available
3587Sema::OwningExprResult
3588Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3589 SourceLocation LParenLoc,
3590 Expr **Args, unsigned NumArgs,
3591 SourceLocation RParenLoc) {
3592 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3593
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003594 // Promote the function operand.
3595 UsualUnaryConversions(Fn);
3596
Chris Lattner08464942007-12-28 05:29:59 +00003597 // Make the call expr early, before semantic checks. This guarantees cleanup
3598 // of arguments and function on error.
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003599 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3600 Args, NumArgs,
3601 Context.BoolTy,
3602 RParenLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003603
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003604 const FunctionType *FuncT;
3605 if (!Fn->getType()->isBlockPointerType()) {
3606 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3607 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003608 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003609 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003610 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3611 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00003612 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003613 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003614 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00003615 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003616 }
Chris Lattner08464942007-12-28 05:29:59 +00003617 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003618 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3619 << Fn->getType() << Fn->getSourceRange());
3620
Eli Friedman3164fb12009-03-22 22:00:50 +00003621 // Check for a valid return type
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003622 if (CheckCallReturnType(FuncT->getResultType(),
3623 Fn->getSourceRange().getBegin(), TheCall.get(),
3624 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003625 return ExprError();
3626
Chris Lattner08464942007-12-28 05:29:59 +00003627 // We know the result type of the call, set it.
Douglas Gregor786ab212008-10-29 02:00:59 +00003628 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003629
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003630 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003631 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003632 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003633 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003634 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003635 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003636
Douglas Gregord8e97de2009-04-02 15:37:10 +00003637 if (FDecl) {
3638 // Check if we have too few/too many template arguments, based
3639 // on our knowledge of the function definition.
3640 const FunctionDecl *Def = 0;
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00003641 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003642 const FunctionProtoType *Proto =
John McCall9dd450b2009-09-21 23:43:11 +00003643 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003644 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3645 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3646 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3647 }
3648 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00003649 }
3650
Steve Naroff0b661582007-08-28 23:30:39 +00003651 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003652 for (unsigned i = 0; i != NumArgs; i++) {
3653 Expr *Arg = Args[i];
3654 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00003655 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3656 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00003657 PDiag(diag::err_call_incomplete_argument)
3658 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003659 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003660 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003661 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003662 }
Chris Lattner08464942007-12-28 05:29:59 +00003663
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003664 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3665 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003666 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3667 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003668
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003669 // Check for sentinels
3670 if (NDecl)
3671 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003672
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003673 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003674 if (FDecl) {
3675 if (CheckFunctionCall(FDecl, TheCall.get()))
3676 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003677
Douglas Gregor15fc9562009-09-12 00:22:50 +00003678 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003679 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3680 } else if (NDecl) {
3681 if (CheckBlockCall(NDecl, TheCall.get()))
3682 return ExprError();
3683 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003684
Anders Carlssonf8984012009-08-16 03:06:32 +00003685 return MaybeBindToTemporary(TheCall.take());
Chris Lattnere168f762006-11-10 05:29:30 +00003686}
3687
Sebastian Redlb5d49352009-01-19 22:31:54 +00003688Action::OwningExprResult
3689Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3690 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003691 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003692 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003693 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003694
3695 TypeSourceInfo *TInfo;
3696 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3697 if (!TInfo)
3698 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3699
3700 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, move(InitExpr));
3701}
3702
3703Action::OwningExprResult
3704Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
3705 SourceLocation RParenLoc, ExprArg InitExpr) {
3706 QualType literalType = TInfo->getType();
Sebastian Redlb5d49352009-01-19 22:31:54 +00003707 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003708
Eli Friedman37a186d2008-05-20 05:22:08 +00003709 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003710 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003711 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3712 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003713 } else if (!literalType->isDependentType() &&
3714 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003715 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003716 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003717 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003718 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003719
Douglas Gregor85dabae2009-12-16 01:38:02 +00003720 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003721 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003722 InitializationKind Kind
3723 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
3724 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00003725 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3726 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3727 MultiExprArg(*this, (void**)&literalExpr, 1),
3728 &literalType);
3729 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003730 return ExprError();
Eli Friedmana553d4a2009-12-22 02:35:53 +00003731 InitExpr.release();
3732 literalExpr = static_cast<Expr*>(Result.get());
Steve Naroffd32419d2008-01-14 18:19:28 +00003733
Chris Lattner79413952008-12-04 23:50:19 +00003734 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003735 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003736 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003737 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003738 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003739
3740 Result.release();
Douglas Gregor85dabae2009-12-16 01:38:02 +00003741
John McCall5d7aa7f2010-01-19 22:33:45 +00003742 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003743 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003744}
3745
Sebastian Redlb5d49352009-01-19 22:31:54 +00003746Action::OwningExprResult
3747Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003748 SourceLocation RBraceLoc) {
3749 unsigned NumInit = initlist.size();
3750 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson4692db02007-08-31 04:56:16 +00003751
Steve Naroff30d242c2007-09-15 18:49:24 +00003752 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003753 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003754
Mike Stump4e1f26a2009-02-19 03:04:26 +00003755 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00003756 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003757 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003758 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003759}
3760
Anders Carlsson094c4592009-10-18 18:12:03 +00003761static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3762 QualType SrcTy, QualType DestTy) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003763 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson094c4592009-10-18 18:12:03 +00003764 return CastExpr::CK_NoOp;
3765
3766 if (SrcTy->hasPointerRepresentation()) {
3767 if (DestTy->hasPointerRepresentation())
Fariborz Jahanian2b9fc832009-12-15 21:34:52 +00003768 return DestTy->isObjCObjectPointerType() ?
3769 CastExpr::CK_AnyPointerToObjCPointerCast :
3770 CastExpr::CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003771 if (DestTy->isIntegerType())
3772 return CastExpr::CK_PointerToIntegral;
3773 }
3774
3775 if (SrcTy->isIntegerType()) {
3776 if (DestTy->isIntegerType())
3777 return CastExpr::CK_IntegralCast;
3778 if (DestTy->hasPointerRepresentation())
3779 return CastExpr::CK_IntegralToPointer;
3780 if (DestTy->isRealFloatingType())
3781 return CastExpr::CK_IntegralToFloating;
3782 }
3783
3784 if (SrcTy->isRealFloatingType()) {
3785 if (DestTy->isRealFloatingType())
3786 return CastExpr::CK_FloatingCast;
3787 if (DestTy->isIntegerType())
3788 return CastExpr::CK_FloatingToIntegral;
3789 }
3790
3791 // FIXME: Assert here.
3792 // assert(false && "Unhandled cast combination!");
3793 return CastExpr::CK_Unknown;
3794}
3795
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003796/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003797bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003798 CastExpr::CastKind& Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003799 CXXMethodDecl *& ConversionDecl,
3800 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003801 if (getLangOptions().CPlusPlus)
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003802 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3803 ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003804
Douglas Gregorb92a1562010-02-03 00:27:59 +00003805 DefaultFunctionArrayLvalueConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003806
3807 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3808 // type needs to be scalar.
3809 if (castType->isVoidType()) {
3810 // Cast to void allows any expr type.
Anders Carlssonef918ac2009-10-16 02:35:04 +00003811 Kind = CastExpr::CK_ToVoid;
3812 return false;
3813 }
3814
3815 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003816 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003817 (castType->isStructureType() || castType->isUnionType())) {
3818 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003819 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003820 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3821 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003822 Kind = CastExpr::CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003823 return false;
3824 }
3825
3826 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003827 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003828 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003829 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003830 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003831 Field != FieldEnd; ++Field) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003832 if (Context.hasSameUnqualifiedType(Field->getType(),
3833 castExpr->getType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003834 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3835 << castExpr->getSourceRange();
3836 break;
3837 }
3838 }
3839 if (Field == FieldEnd)
3840 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3841 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003842 Kind = CastExpr::CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003843 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003844 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00003845
3846 // Reject any other conversions to non-scalar types.
3847 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3848 << castType << castExpr->getSourceRange();
3849 }
3850
3851 if (!castExpr->getType()->isScalarType() &&
3852 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003853 return Diag(castExpr->getLocStart(),
3854 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003855 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003856 }
3857
Anders Carlsson43d70f82009-10-16 05:23:41 +00003858 if (castType->isExtVectorType())
3859 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3860
Anders Carlsson525b76b2009-10-16 02:48:28 +00003861 if (castType->isVectorType())
3862 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3863 if (castExpr->getType()->isVectorType())
3864 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3865
3866 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffb47acdb2009-04-08 23:52:26 +00003867 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003868
Anders Carlsson43d70f82009-10-16 05:23:41 +00003869 if (isa<ObjCSelectorExpr>(castExpr))
3870 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3871
Anders Carlsson525b76b2009-10-16 02:48:28 +00003872 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003873 QualType castExprType = castExpr->getType();
3874 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3875 return Diag(castExpr->getLocStart(),
3876 diag::err_cast_pointer_from_non_pointer_int)
3877 << castExprType << castExpr->getSourceRange();
3878 } else if (!castExpr->getType()->isArithmeticType()) {
3879 if (!castType->isIntegralType() && castType->isArithmeticType())
3880 return Diag(castExpr->getLocStart(),
3881 diag::err_cast_pointer_to_non_pointer_int)
3882 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003883 }
Anders Carlsson094c4592009-10-18 18:12:03 +00003884
3885 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003886 return false;
3887}
3888
Anders Carlsson525b76b2009-10-16 02:48:28 +00003889bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3890 CastExpr::CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00003891 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00003892
Anders Carlssonde71adf2007-11-27 05:51:55 +00003893 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00003894 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00003895 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00003896 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00003897 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00003898 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003899 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003900 } else
3901 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003902 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003903 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003904
Anders Carlsson525b76b2009-10-16 02:48:28 +00003905 Kind = CastExpr::CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003906 return false;
3907}
3908
Anders Carlsson43d70f82009-10-16 05:23:41 +00003909bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3910 CastExpr::CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00003911 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson43d70f82009-10-16 05:23:41 +00003912
3913 QualType SrcTy = CastExpr->getType();
3914
Nate Begemanc8961a42009-06-27 22:05:55 +00003915 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3916 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00003917 if (SrcTy->isVectorType()) {
3918 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3919 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3920 << DestTy << SrcTy << R;
Anders Carlsson43d70f82009-10-16 05:23:41 +00003921 Kind = CastExpr::CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00003922 return false;
3923 }
3924
Nate Begemanbd956c42009-06-28 02:36:38 +00003925 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00003926 // conversion will take place first from scalar to elt type, and then
3927 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00003928 if (SrcTy->isPointerType())
3929 return Diag(R.getBegin(),
3930 diag::err_invalid_conversion_between_vector_and_scalar)
3931 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00003932
3933 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3934 ImpCastExprToType(CastExpr, DestElemTy,
3935 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson43d70f82009-10-16 05:23:41 +00003936
3937 Kind = CastExpr::CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00003938 return false;
3939}
3940
Sebastian Redlb5d49352009-01-19 22:31:54 +00003941Action::OwningExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00003942Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003943 SourceLocation RParenLoc, ExprArg Op) {
3944 assert((Ty != 0) && (Op.get() != 0) &&
3945 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00003946
John McCall97513962010-01-15 18:39:57 +00003947 TypeSourceInfo *castTInfo;
3948 QualType castType = GetTypeFromParser(Ty, &castTInfo);
3949 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00003950 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00003951
Nate Begeman5ec4b312009-08-10 23:49:36 +00003952 // If the Expr being casted is a ParenListExpr, handle it specially.
John McCallebe54742010-01-15 18:56:44 +00003953 Expr *castExpr = (Expr *)Op.get();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003954 if (isa<ParenListExpr>(castExpr))
John McCalle15bbff2010-01-18 19:35:47 +00003955 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),
3956 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00003957
3958 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, move(Op));
3959}
3960
3961Action::OwningExprResult
3962Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
3963 SourceLocation RParenLoc, ExprArg Op) {
3964 Expr *castExpr = static_cast<Expr*>(Op.get());
3965
Anders Carlssone9766d52009-09-09 21:33:21 +00003966 CXXMethodDecl *Method = 0;
John McCallebe54742010-01-15 18:56:44 +00003967 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3968 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
Anders Carlssone9766d52009-09-09 21:33:21 +00003969 Kind, Method))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003970 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00003971
3972 if (Method) {
John McCallebe54742010-01-15 18:56:44 +00003973 // FIXME: preserve type source info here
3974 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, Ty->getType(),
3975 Kind, Method, move(Op));
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003976
Anders Carlssone9766d52009-09-09 21:33:21 +00003977 if (CastArg.isInvalid())
3978 return ExprError();
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003979
Anders Carlssone9766d52009-09-09 21:33:21 +00003980 castExpr = CastArg.takeAs<Expr>();
3981 } else {
3982 Op.release();
Fariborz Jahanian3df87672009-08-29 19:15:16 +00003983 }
Mike Stump11289f42009-09-09 15:08:12 +00003984
John McCallebe54742010-01-15 18:56:44 +00003985 return Owned(new (Context) CStyleCastExpr(Ty->getType().getNonReferenceType(),
3986 Kind, castExpr, Ty,
Anders Carlssonf10e4142009-08-07 22:21:05 +00003987 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003988}
3989
Nate Begeman5ec4b312009-08-10 23:49:36 +00003990/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3991/// of comma binary operators.
3992Action::OwningExprResult
3993Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3994 Expr *expr = EA.takeAs<Expr>();
3995 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3996 if (!E)
3997 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00003998
Nate Begeman5ec4b312009-08-10 23:49:36 +00003999 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004000
Nate Begeman5ec4b312009-08-10 23:49:36 +00004001 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4002 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
4003 Owned(E->getExpr(i)));
Mike Stump11289f42009-09-09 15:08:12 +00004004
Nate Begeman5ec4b312009-08-10 23:49:36 +00004005 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
4006}
4007
4008Action::OwningExprResult
4009Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
4010 SourceLocation RParenLoc, ExprArg Op,
John McCalle15bbff2010-01-18 19:35:47 +00004011 TypeSourceInfo *TInfo) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004012 ParenListExpr *PE = (ParenListExpr *)Op.get();
John McCalle15bbff2010-01-18 19:35:47 +00004013 QualType Ty = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004014
4015 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman5ec4b312009-08-10 23:49:36 +00004016 // then handle it as such.
4017 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4018 if (PE->getNumExprs() == 0) {
4019 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4020 return ExprError();
4021 }
4022
4023 llvm::SmallVector<Expr *, 8> initExprs;
4024 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4025 initExprs.push_back(PE->getExpr(i));
4026
4027 // FIXME: This means that pretty-printing the final AST will produce curly
4028 // braces instead of the original commas.
4029 Op.release();
Mike Stump11289f42009-09-09 15:08:12 +00004030 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00004031 initExprs.size(), RParenLoc);
4032 E->setType(Ty);
John McCalle15bbff2010-01-18 19:35:47 +00004033 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, Owned(E));
Nate Begeman5ec4b312009-08-10 23:49:36 +00004034 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004035 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00004036 // sequence of BinOp comma operators.
4037 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
John McCalle15bbff2010-01-18 19:35:47 +00004038 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, move(Op));
Nate Begeman5ec4b312009-08-10 23:49:36 +00004039 }
4040}
4041
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004042Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004043 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004044 MultiExprArg Val,
4045 TypeTy *TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004046 unsigned nexprs = Val.size();
4047 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004048 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4049 Expr *expr;
4050 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4051 expr = new (Context) ParenExpr(L, R, exprs[0]);
4052 else
4053 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004054 return Owned(expr);
4055}
4056
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004057/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4058/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004059/// C99 6.5.15
4060QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4061 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004062 // C++ is sufficiently different to merit its own checker.
4063 if (getLangOptions().CPlusPlus)
4064 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
4065
John McCall1fa36b72009-11-05 09:23:39 +00004066 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
4067
Chris Lattner432cff52009-02-18 04:28:32 +00004068 UsualUnaryConversions(Cond);
4069 UsualUnaryConversions(LHS);
4070 UsualUnaryConversions(RHS);
4071 QualType CondTy = Cond->getType();
4072 QualType LHSTy = LHS->getType();
4073 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004074
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004075 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004076 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4077 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4078 << CondTy;
4079 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004080 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004081
Chris Lattnere2949f42008-01-06 22:42:25 +00004082 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004083 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4084 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00004085
Chris Lattnere2949f42008-01-06 22:42:25 +00004086 // If both operands have arithmetic type, do the usual arithmetic conversions
4087 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004088 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4089 UsualArithmeticConversions(LHS, RHS);
4090 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004091 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004092
Chris Lattnere2949f42008-01-06 22:42:25 +00004093 // If both operands are the same structure or union type, the result is that
4094 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004095 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4096 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004097 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004098 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004099 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004100 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004101 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004102 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004103
Chris Lattnere2949f42008-01-06 22:42:25 +00004104 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004105 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004106 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4107 if (!LHSTy->isVoidType())
4108 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4109 << RHS->getSourceRange();
4110 if (!RHSTy->isVoidType())
4111 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4112 << LHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004113 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4114 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004115 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004116 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004117 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4118 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004119 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004120 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004121 // promote the null to a pointer.
4122 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004123 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004124 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004125 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004126 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004127 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004128 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004129 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004130
4131 // All objective-c pointer type analysis is done here.
4132 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4133 QuestionLoc);
4134 if (!compositeType.isNull())
4135 return compositeType;
4136
4137
Steve Naroff05efa972009-07-01 14:36:47 +00004138 // Handle block pointer types.
4139 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4140 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4141 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4142 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004143 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4144 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004145 return destType;
4146 }
4147 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004148 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004149 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004150 }
Steve Naroff05efa972009-07-01 14:36:47 +00004151 // We have 2 block pointer types.
4152 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4153 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004154 return LHSTy;
4155 }
Steve Naroff05efa972009-07-01 14:36:47 +00004156 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004157 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4158 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004159
Steve Naroff05efa972009-07-01 14:36:47 +00004160 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4161 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004162 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004163 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004164 // In this situation, we assume void* type. No especially good
4165 // reason, but this is what gcc does, and we do have to pick
4166 // to get a consistent AST.
4167 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004168 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4169 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004170 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004171 }
Steve Naroff05efa972009-07-01 14:36:47 +00004172 // The block pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004173 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4174 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004175 return LHSTy;
4176 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004177
Steve Naroff05efa972009-07-01 14:36:47 +00004178 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4179 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4180 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004181 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4182 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004183
4184 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4185 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4186 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004187 QualType destPointee
4188 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004189 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004190 // Add qualifiers if necessary.
4191 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4192 // Promote to void*.
4193 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004194 return destType;
4195 }
4196 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004197 QualType destPointee
4198 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004199 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004200 // Add qualifiers if necessary.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004201 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004202 // Promote to void*.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004203 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004204 return destType;
4205 }
4206
4207 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4208 // Two identical pointer types are always compatible.
4209 return LHSTy;
4210 }
4211 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4212 rhptee.getUnqualifiedType())) {
4213 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4214 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4215 // In this situation, we assume void* type. No especially good
4216 // reason, but this is what gcc does, and we do have to pick
4217 // to get a consistent AST.
4218 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004219 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4220 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004221 return incompatTy;
4222 }
4223 // The pointer types are compatible.
4224 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4225 // differently qualified versions of compatible types, the result type is
4226 // a pointer to an appropriately qualified version of the *composite*
4227 // type.
4228 // FIXME: Need to calculate the composite type.
4229 // FIXME: Need to add qualifiers
Eli Friedman06ed2a52009-10-20 08:27:19 +00004230 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4231 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004232 return LHSTy;
4233 }
Mike Stump11289f42009-09-09 15:08:12 +00004234
Steve Naroff05efa972009-07-01 14:36:47 +00004235 // GCC compatibility: soften pointer/integer mismatch.
4236 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4237 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4238 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004239 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004240 return RHSTy;
4241 }
4242 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4243 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4244 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004245 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004246 return LHSTy;
4247 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004248
Chris Lattnere2949f42008-01-06 22:42:25 +00004249 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004250 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4251 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004252 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004253}
4254
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004255/// FindCompositeObjCPointerType - Helper method to find composite type of
4256/// two objective-c pointer types of the two input expressions.
4257QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4258 SourceLocation QuestionLoc) {
4259 QualType LHSTy = LHS->getType();
4260 QualType RHSTy = RHS->getType();
4261
4262 // Handle things like Class and struct objc_class*. Here we case the result
4263 // to the pseudo-builtin, because that will be implicitly cast back to the
4264 // redefinition type if an attempt is made to access its fields.
4265 if (LHSTy->isObjCClassType() &&
4266 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4267 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4268 return LHSTy;
4269 }
4270 if (RHSTy->isObjCClassType() &&
4271 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4272 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4273 return RHSTy;
4274 }
4275 // And the same for struct objc_object* / id
4276 if (LHSTy->isObjCIdType() &&
4277 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4278 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4279 return LHSTy;
4280 }
4281 if (RHSTy->isObjCIdType() &&
4282 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4283 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4284 return RHSTy;
4285 }
4286 // And the same for struct objc_selector* / SEL
4287 if (Context.isObjCSelType(LHSTy) &&
4288 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4289 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4290 return LHSTy;
4291 }
4292 if (Context.isObjCSelType(RHSTy) &&
4293 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4294 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4295 return RHSTy;
4296 }
4297 // Check constraints for Objective-C object pointers types.
4298 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4299
4300 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4301 // Two identical object pointer types are always compatible.
4302 return LHSTy;
4303 }
4304 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4305 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4306 QualType compositeType = LHSTy;
4307
4308 // If both operands are interfaces and either operand can be
4309 // assigned to the other, use that type as the composite
4310 // type. This allows
4311 // xxx ? (A*) a : (B*) b
4312 // where B is a subclass of A.
4313 //
4314 // Additionally, as for assignment, if either type is 'id'
4315 // allow silent coercion. Finally, if the types are
4316 // incompatible then make sure to use 'id' as the composite
4317 // type so the result is acceptable for sending messages to.
4318
4319 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4320 // It could return the composite type.
4321 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4322 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4323 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4324 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4325 } else if ((LHSTy->isObjCQualifiedIdType() ||
4326 RHSTy->isObjCQualifiedIdType()) &&
4327 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4328 // Need to handle "id<xx>" explicitly.
4329 // GCC allows qualified id and any Objective-C type to devolve to
4330 // id. Currently localizing to here until clear this should be
4331 // part of ObjCQualifiedIdTypesAreCompatible.
4332 compositeType = Context.getObjCIdType();
4333 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4334 compositeType = Context.getObjCIdType();
4335 } else if (!(compositeType =
4336 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4337 ;
4338 else {
4339 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4340 << LHSTy << RHSTy
4341 << LHS->getSourceRange() << RHS->getSourceRange();
4342 QualType incompatTy = Context.getObjCIdType();
4343 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4344 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4345 return incompatTy;
4346 }
4347 // The object pointer types are compatible.
4348 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4349 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4350 return compositeType;
4351 }
4352 // Check Objective-C object pointer types and 'void *'
4353 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4354 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4355 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4356 QualType destPointee
4357 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4358 QualType destType = Context.getPointerType(destPointee);
4359 // Add qualifiers if necessary.
4360 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4361 // Promote to void*.
4362 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4363 return destType;
4364 }
4365 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4366 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4367 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4368 QualType destPointee
4369 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4370 QualType destType = Context.getPointerType(destPointee);
4371 // Add qualifiers if necessary.
4372 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4373 // Promote to void*.
4374 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4375 return destType;
4376 }
4377 return QualType();
4378}
4379
Steve Naroff83895f72007-09-16 03:34:24 +00004380/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004381/// in the case of a the GNU conditional expr extension.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004382Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4383 SourceLocation ColonLoc,
4384 ExprArg Cond, ExprArg LHS,
4385 ExprArg RHS) {
4386 Expr *CondExpr = (Expr *) Cond.get();
4387 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner2ab40a62007-11-26 01:40:58 +00004388
4389 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4390 // was the condition.
4391 bool isLHSNull = LHSExpr == 0;
4392 if (isLHSNull)
4393 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00004394
4395 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00004396 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00004397 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004398 return ExprError();
4399
4400 Cond.release();
4401 LHS.release();
4402 RHS.release();
Douglas Gregor7e112b02009-08-26 14:37:04 +00004403 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00004404 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00004405 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00004406}
4407
Steve Naroff3f597292007-05-11 22:18:03 +00004408// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004409// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004410// routine is it effectively iqnores the qualifiers on the top level pointee.
4411// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4412// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004413Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004414Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00004415 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004416
David Chisnall9f57c292009-08-17 16:35:33 +00004417 if ((lhsType->isObjCClassType() &&
4418 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4419 (rhsType->isObjCClassType() &&
4420 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4421 return Compatible;
4422 }
4423
Steve Naroff1f4d7272007-05-11 04:00:31 +00004424 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004425 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4426 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004427
Steve Naroff1f4d7272007-05-11 04:00:31 +00004428 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00004429 lhptee = Context.getCanonicalType(lhptee);
4430 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00004431
Chris Lattner9bad62c2008-01-04 18:04:52 +00004432 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004433
4434 // C99 6.5.16.1p1: This following citation is common to constraints
4435 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4436 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00004437 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00004438 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004439 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00004440
Mike Stump4e1f26a2009-02-19 03:04:26 +00004441 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4442 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004443 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004444 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004445 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004446 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004447
Chris Lattner0a788432008-01-03 22:56:36 +00004448 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004449 assert(rhptee->isFunctionType());
4450 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004451 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004452
Chris Lattner0a788432008-01-03 22:56:36 +00004453 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004454 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004455 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004456
4457 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004458 assert(lhptee->isFunctionType());
4459 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004460 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004461 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00004462 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00004463 lhptee = lhptee.getUnqualifiedType();
4464 rhptee = rhptee.getUnqualifiedType();
4465 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4466 // Check if the pointee types are compatible ignoring the sign.
4467 // We explicitly check for char so that we catch "char" vs
4468 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00004469 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004470 lhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004471 else if (lhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004472 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004473
4474 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004475 rhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004476 else if (rhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004477 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004478
Eli Friedman80160bd2009-03-22 23:59:44 +00004479 if (lhptee == rhptee) {
4480 // Types are compatible ignoring the sign. Qualifier incompatibility
4481 // takes priority over sign incompatibility because the sign
4482 // warning can be disabled.
4483 if (ConvTy != Compatible)
4484 return ConvTy;
4485 return IncompatiblePointerSign;
4486 }
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004487
4488 // If we are a multi-level pointer, it's possible that our issue is simply
4489 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4490 // the eventual target type is the same and the pointers have the same
4491 // level of indirection, this must be the issue.
4492 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4493 do {
4494 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4495 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4496
4497 lhptee = Context.getCanonicalType(lhptee);
4498 rhptee = Context.getCanonicalType(rhptee);
4499 } while (lhptee->isPointerType() && rhptee->isPointerType());
4500
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004501 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00004502 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004503 }
4504
Eli Friedman80160bd2009-03-22 23:59:44 +00004505 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00004506 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00004507 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004508 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00004509}
4510
Steve Naroff081c7422008-09-04 15:10:53 +00004511/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4512/// block pointer types are compatible or whether a block and normal pointer
4513/// are compatible. It is more restrict than comparing two function pointer
4514// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004515Sema::AssignConvertType
4516Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00004517 QualType rhsType) {
4518 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004519
Steve Naroff081c7422008-09-04 15:10:53 +00004520 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004521 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4522 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004523
Steve Naroff081c7422008-09-04 15:10:53 +00004524 // make sure we operate on the canonical type
4525 lhptee = Context.getCanonicalType(lhptee);
4526 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004527
Steve Naroff081c7422008-09-04 15:10:53 +00004528 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004529
Steve Naroff081c7422008-09-04 15:10:53 +00004530 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004531 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00004532 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004533
Eli Friedmana6638ca2009-06-08 05:08:54 +00004534 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004535 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00004536 return ConvTy;
4537}
4538
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004539/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4540/// for assignment compatibility.
4541Sema::AssignConvertType
4542Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4543 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4544 return Compatible;
4545 QualType lhptee =
4546 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4547 QualType rhptee =
4548 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4549 // make sure we operate on the canonical type
4550 lhptee = Context.getCanonicalType(lhptee);
4551 rhptee = Context.getCanonicalType(rhptee);
4552 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4553 return CompatiblePointerDiscardsQualifiers;
4554
4555 if (Context.typesAreCompatible(lhsType, rhsType))
4556 return Compatible;
4557 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4558 return IncompatibleObjCQualifiedId;
4559 return IncompatiblePointer;
4560}
4561
Mike Stump4e1f26a2009-02-19 03:04:26 +00004562/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4563/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00004564/// pointers. Here are some objectionable examples that GCC considers warnings:
4565///
4566/// int a, *pint;
4567/// short *pshort;
4568/// struct foo *pfoo;
4569///
4570/// pint = pshort; // warning: assignment from incompatible pointer type
4571/// a = pint; // warning: assignment makes integer from pointer without a cast
4572/// pint = a; // warning: assignment makes pointer from integer without a cast
4573/// pint = pfoo; // warning: assignment from incompatible pointer type
4574///
4575/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00004576/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00004577///
Chris Lattner9bad62c2008-01-04 18:04:52 +00004578Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004579Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00004580 // Get canonical types. We're not formatting these types, just comparing
4581 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00004582 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4583 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00004584
4585 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00004586 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00004587
David Chisnall9f57c292009-08-17 16:35:33 +00004588 if ((lhsType->isObjCClassType() &&
4589 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4590 (rhsType->isObjCClassType() &&
4591 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4592 return Compatible;
4593 }
4594
Douglas Gregor6b754842008-10-28 00:22:11 +00004595 // If the left-hand side is a reference type, then we are in a
4596 // (rare!) case where we've allowed the use of references in C,
4597 // e.g., as a parameter type in a built-in function. In this case,
4598 // just make sure that the type referenced is compatible with the
4599 // right-hand side type. The caller is responsible for adjusting
4600 // lhsType so that the resulting expression does not have reference
4601 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004602 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00004603 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00004604 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004605 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00004606 }
Nate Begemanbd956c42009-06-28 02:36:38 +00004607 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4608 // to the same ExtVector type.
4609 if (lhsType->isExtVectorType()) {
4610 if (rhsType->isExtVectorType())
4611 return lhsType == rhsType ? Compatible : Incompatible;
4612 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4613 return Compatible;
4614 }
Mike Stump11289f42009-09-09 15:08:12 +00004615
Nate Begeman191a6b12008-07-14 18:02:46 +00004616 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004617 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump4e1f26a2009-02-19 03:04:26 +00004618 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begeman191a6b12008-07-14 18:02:46 +00004619 // no bits are changed but the result type is different.
Chris Lattner881a2122008-01-04 23:32:24 +00004620 if (getLangOptions().LaxVectorConversions &&
4621 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004622 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004623 return IncompatibleVectors;
Chris Lattner881a2122008-01-04 23:32:24 +00004624 }
4625 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004626 }
Eli Friedman3360d892008-05-30 18:07:22 +00004627
Chris Lattner881a2122008-01-04 23:32:24 +00004628 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Steve Naroff98cf3e92007-06-06 18:38:38 +00004629 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00004630
Chris Lattnerec646832008-04-07 06:49:41 +00004631 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004632 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004633 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00004634
Chris Lattnerec646832008-04-07 06:49:41 +00004635 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004636 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004637
Steve Naroffaccc4882009-07-20 17:56:53 +00004638 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004639 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004640 if (lhsType->isVoidPointerType()) // an exception to the rule.
4641 return Compatible;
4642 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004643 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004644 if (rhsType->getAs<BlockPointerType>()) {
4645 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004646 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00004647
4648 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004649 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004650 return Compatible;
4651 }
Steve Naroff081c7422008-09-04 15:10:53 +00004652 return Incompatible;
4653 }
4654
4655 if (isa<BlockPointerType>(lhsType)) {
4656 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00004657 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004658
Steve Naroff32d072c2008-09-29 18:10:17 +00004659 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004660 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004661 return Compatible;
4662
Steve Naroff081c7422008-09-04 15:10:53 +00004663 if (rhsType->isBlockPointerType())
4664 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004665
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004666 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00004667 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004668 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00004669 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00004670 return Incompatible;
4671 }
4672
Steve Naroff7cae42b2009-07-10 23:34:53 +00004673 if (isa<ObjCObjectPointerType>(lhsType)) {
4674 if (rhsType->isIntegerType())
4675 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00004676
Steve Naroffaccc4882009-07-20 17:56:53 +00004677 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004678 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004679 if (rhsType->isVoidPointerType()) // an exception to the rule.
4680 return Compatible;
4681 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004682 }
4683 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004684 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004685 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004686 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004687 if (RHSPT->getPointeeType()->isVoidType())
4688 return Compatible;
4689 }
4690 // Treat block pointers as objects.
4691 if (rhsType->isBlockPointerType())
4692 return Compatible;
4693 return Incompatible;
4694 }
Chris Lattnerec646832008-04-07 06:49:41 +00004695 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004696 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00004697 if (lhsType == Context.BoolTy)
4698 return Compatible;
4699
4700 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004701 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00004702
Mike Stump4e1f26a2009-02-19 03:04:26 +00004703 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004704 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004705
4706 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004707 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004708 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004709 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004710 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004711 if (isa<ObjCObjectPointerType>(rhsType)) {
4712 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4713 if (lhsType == Context.BoolTy)
4714 return Compatible;
4715
4716 if (lhsType->isIntegerType())
4717 return PointerToInt;
4718
Steve Naroffaccc4882009-07-20 17:56:53 +00004719 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004720 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004721 if (lhsType->isVoidPointerType()) // an exception to the rule.
4722 return Compatible;
4723 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004724 }
4725 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004726 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004727 return Compatible;
4728 return Incompatible;
4729 }
Eli Friedman3360d892008-05-30 18:07:22 +00004730
Chris Lattnera52c2f22008-01-04 23:18:45 +00004731 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00004732 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004733 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00004734 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00004735 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00004736}
4737
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004738/// \brief Constructs a transparent union from an expression that is
4739/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00004740static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004741 QualType UnionType, FieldDecl *Field) {
4742 // Build an initializer list that designates the appropriate member
4743 // of the transparent union.
4744 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4745 &E, 1,
4746 SourceLocation());
4747 Initializer->setType(UnionType);
4748 Initializer->setInitializedFieldInUnion(Field);
4749
4750 // Build a compound literal constructing a value of the transparent
4751 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00004752 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00004753 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCalle15bbff2010-01-18 19:35:47 +00004754 Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004755}
4756
4757Sema::AssignConvertType
4758Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4759 QualType FromType = rExpr->getType();
4760
Mike Stump11289f42009-09-09 15:08:12 +00004761 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004762 // transparent_union GCC extension.
4763 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004764 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004765 return Incompatible;
4766
4767 // The field to initialize within the transparent union.
4768 RecordDecl *UD = UT->getDecl();
4769 FieldDecl *InitField = 0;
4770 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004771 for (RecordDecl::field_iterator it = UD->field_begin(),
4772 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004773 it != itend; ++it) {
4774 if (it->getType()->isPointerType()) {
4775 // If the transparent union contains a pointer type, we allow:
4776 // 1) void pointer
4777 // 2) null pointer constant
4778 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004779 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004780 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004781 InitField = *it;
4782 break;
4783 }
Mike Stump11289f42009-09-09 15:08:12 +00004784
Douglas Gregor56751b52009-09-25 04:25:58 +00004785 if (rExpr->isNullPointerConstant(Context,
4786 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004787 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004788 InitField = *it;
4789 break;
4790 }
4791 }
4792
4793 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4794 == Compatible) {
4795 InitField = *it;
4796 break;
4797 }
4798 }
4799
4800 if (!InitField)
4801 return Incompatible;
4802
4803 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4804 return Compatible;
4805}
4806
Chris Lattner9bad62c2008-01-04 18:04:52 +00004807Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004808Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00004809 if (getLangOptions().CPlusPlus) {
4810 if (!lhsType->isRecordType()) {
4811 // C++ 5.17p3: If the left operand is not of class type, the
4812 // expression is implicitly converted (C++ 4) to the
4813 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00004814 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004815 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00004816 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00004817 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00004818 }
4819
4820 // FIXME: Currently, we fall through and treat C++ classes like C
4821 // structures.
4822 }
4823
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004824 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4825 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00004826 if ((lhsType->isPointerType() ||
4827 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00004828 lhsType->isBlockPointerType())
Douglas Gregor56751b52009-09-25 04:25:58 +00004829 && rExpr->isNullPointerConstant(Context,
4830 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004831 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004832 return Compatible;
4833 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004834
Chris Lattnere6dcd502007-10-16 02:55:40 +00004835 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004836 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00004837 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004838 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00004839 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00004840 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00004841 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00004842 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004843
Chris Lattner9bad62c2008-01-04 18:04:52 +00004844 Sema::AssignConvertType result =
4845 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004846
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004847 // C99 6.5.16.1p2: The value of the right operand is converted to the
4848 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00004849 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4850 // so that we can use references in built-in functions even in C.
4851 // The getNonReferenceType() call makes sure that the resulting expression
4852 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004853 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004854 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4855 CastExpr::CK_Unknown);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004856 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004857}
4858
Chris Lattner326f7572008-11-18 01:30:42 +00004859QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004860 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00004861 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004862 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00004863 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00004864}
4865
Chris Lattnerfaa54172010-01-12 21:23:57 +00004866QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004867 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004868 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00004869 QualType lhsType =
4870 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4871 QualType rhsType =
4872 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004873
Nate Begeman191a6b12008-07-14 18:02:46 +00004874 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004875 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00004876 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004877
Nate Begeman191a6b12008-07-14 18:02:46 +00004878 // Handle the case of a vector & extvector type of the same size and element
4879 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004880 if (getLangOptions().LaxVectorConversions) {
4881 // FIXME: Should we warn here?
John McCall9dd450b2009-09-21 23:43:11 +00004882 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4883 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begeman191a6b12008-07-14 18:02:46 +00004884 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004885 LV->getNumElements() == RV->getNumElements()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004886 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004887 }
4888 }
4889 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004890
Nate Begemanbd956c42009-06-28 02:36:38 +00004891 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4892 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4893 bool swapped = false;
4894 if (rhsType->isExtVectorType()) {
4895 swapped = true;
4896 std::swap(rex, lex);
4897 std::swap(rhsType, lhsType);
4898 }
Mike Stump11289f42009-09-09 15:08:12 +00004899
Nate Begeman886448d2009-06-28 19:12:57 +00004900 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00004901 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00004902 QualType EltTy = LV->getElementType();
4903 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4904 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004905 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004906 if (swapped) std::swap(rex, lex);
4907 return lhsType;
4908 }
4909 }
4910 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4911 rhsType->isRealFloatingType()) {
4912 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004913 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004914 if (swapped) std::swap(rex, lex);
4915 return lhsType;
4916 }
Nate Begeman330aaa72007-12-30 02:59:45 +00004917 }
4918 }
Mike Stump11289f42009-09-09 15:08:12 +00004919
Nate Begeman886448d2009-06-28 19:12:57 +00004920 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00004921 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004922 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004923 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00004924 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00004925}
4926
Chris Lattnerfaa54172010-01-12 21:23:57 +00004927QualType Sema::CheckMultiplyDivideOperands(
4928 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00004929 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004930 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004931
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004932 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004933
Chris Lattnerfaa54172010-01-12 21:23:57 +00004934 if (!lex->getType()->isArithmeticType() ||
4935 !rex->getType()->isArithmeticType())
4936 return InvalidOperands(Loc, lex, rex);
4937
4938 // Check for division by zero.
4939 if (isDiv &&
4940 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00004941 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
4942 << rex->getSourceRange());
Chris Lattnerfaa54172010-01-12 21:23:57 +00004943
4944 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00004945}
4946
Chris Lattnerfaa54172010-01-12 21:23:57 +00004947QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004948 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00004949 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4950 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4951 return CheckVectorOperands(Loc, lex, rex);
4952 return InvalidOperands(Loc, lex, rex);
4953 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004954
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004955 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004956
Chris Lattnerfaa54172010-01-12 21:23:57 +00004957 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4958 return InvalidOperands(Loc, lex, rex);
4959
4960 // Check for remainder by zero.
4961 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00004962 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
4963 << rex->getSourceRange());
Chris Lattnerfaa54172010-01-12 21:23:57 +00004964
4965 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00004966}
4967
Chris Lattnerfaa54172010-01-12 21:23:57 +00004968QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00004969 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004970 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4971 QualType compType = CheckVectorOperands(Loc, lex, rex);
4972 if (CompLHSTy) *CompLHSTy = compType;
4973 return compType;
4974 }
Steve Naroff7a5af782007-07-13 16:58:59 +00004975
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004976 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00004977
Steve Naroffe4718892007-04-27 18:30:00 +00004978 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004979 if (lex->getType()->isArithmeticType() &&
4980 rex->getType()->isArithmeticType()) {
4981 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004982 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004983 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00004984
Eli Friedman8e122982008-05-18 18:08:51 +00004985 // Put any potential pointer into PExp
4986 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00004987 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00004988 std::swap(PExp, IExp);
4989
Steve Naroff6b712a72009-07-14 18:25:06 +00004990 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004991
Eli Friedman8e122982008-05-18 18:08:51 +00004992 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004993 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004994
Chris Lattner12bdebb2009-04-24 23:50:08 +00004995 // Check for arithmetic on pointers to incomplete types.
4996 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004997 if (getLangOptions().CPlusPlus) {
4998 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00004999 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00005000 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005001 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005002
5003 // GNU extension: arithmetic on pointer to void
5004 Diag(Loc, diag::ext_gnu_void_ptr)
5005 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00005006 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00005007 if (getLangOptions().CPlusPlus) {
5008 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5009 << lex->getType() << lex->getSourceRange();
5010 return QualType();
5011 }
5012
5013 // GNU extension: arithmetic on pointer to function
5014 Diag(Loc, diag::ext_gnu_ptr_func_arith)
5015 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00005016 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005017 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00005018 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00005019 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005020 PExp->getType()->isObjCObjectPointerType()) &&
5021 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00005022 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5023 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005024 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005025 return QualType();
5026 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00005027 // Diagnose bad cases where we step over interface counts.
5028 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5029 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5030 << PointeeTy << PExp->getSourceRange();
5031 return QualType();
5032 }
Mike Stump11289f42009-09-09 15:08:12 +00005033
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005034 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00005035 QualType LHSTy = Context.isPromotableBitField(lex);
5036 if (LHSTy.isNull()) {
5037 LHSTy = lex->getType();
5038 if (LHSTy->isPromotableIntegerType())
5039 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005040 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005041 *CompLHSTy = LHSTy;
5042 }
Eli Friedman8e122982008-05-18 18:08:51 +00005043 return PExp->getType();
5044 }
5045 }
5046
Chris Lattner326f7572008-11-18 01:30:42 +00005047 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005048}
5049
Chris Lattner2a3569b2008-04-07 05:30:13 +00005050// C99 6.5.6
5051QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005052 SourceLocation Loc, QualType* CompLHSTy) {
5053 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5054 QualType compType = CheckVectorOperands(Loc, lex, rex);
5055 if (CompLHSTy) *CompLHSTy = compType;
5056 return compType;
5057 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005058
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005059 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005060
Chris Lattner4d62f422007-12-09 21:53:25 +00005061 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005062
Chris Lattner4d62f422007-12-09 21:53:25 +00005063 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00005064 if (lex->getType()->isArithmeticType()
5065 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005066 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005067 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005068 }
Mike Stump11289f42009-09-09 15:08:12 +00005069
Chris Lattner4d62f422007-12-09 21:53:25 +00005070 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00005071 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00005072 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005073
Douglas Gregorac1fb652009-03-24 19:52:54 +00005074 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005075
Douglas Gregorac1fb652009-03-24 19:52:54 +00005076 bool ComplainAboutVoid = false;
5077 Expr *ComplainAboutFunc = 0;
5078 if (lpointee->isVoidType()) {
5079 if (getLangOptions().CPlusPlus) {
5080 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5081 << lex->getSourceRange() << rex->getSourceRange();
5082 return QualType();
5083 }
5084
5085 // GNU C extension: arithmetic on pointer to void
5086 ComplainAboutVoid = true;
5087 } else if (lpointee->isFunctionType()) {
5088 if (getLangOptions().CPlusPlus) {
5089 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005090 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005091 return QualType();
5092 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005093
5094 // GNU C extension: arithmetic on pointer to function
5095 ComplainAboutFunc = lex;
5096 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00005097 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005098 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00005099 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005100 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005101 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005102
Chris Lattner12bdebb2009-04-24 23:50:08 +00005103 // Diagnose bad cases where we step over interface counts.
5104 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5105 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5106 << lpointee << lex->getSourceRange();
5107 return QualType();
5108 }
Mike Stump11289f42009-09-09 15:08:12 +00005109
Chris Lattner4d62f422007-12-09 21:53:25 +00005110 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00005111 if (rex->getType()->isIntegerType()) {
5112 if (ComplainAboutVoid)
5113 Diag(Loc, diag::ext_gnu_void_ptr)
5114 << lex->getSourceRange() << rex->getSourceRange();
5115 if (ComplainAboutFunc)
5116 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005117 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005118 << ComplainAboutFunc->getSourceRange();
5119
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005120 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005121 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005122 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005123
Chris Lattner4d62f422007-12-09 21:53:25 +00005124 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005125 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00005126 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005127
Douglas Gregorac1fb652009-03-24 19:52:54 +00005128 // RHS must be a completely-type object type.
5129 // Handle the GNU void* extension.
5130 if (rpointee->isVoidType()) {
5131 if (getLangOptions().CPlusPlus) {
5132 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5133 << lex->getSourceRange() << rex->getSourceRange();
5134 return QualType();
5135 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005136
Douglas Gregorac1fb652009-03-24 19:52:54 +00005137 ComplainAboutVoid = true;
5138 } else if (rpointee->isFunctionType()) {
5139 if (getLangOptions().CPlusPlus) {
5140 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005141 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005142 return QualType();
5143 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005144
5145 // GNU extension: arithmetic on pointer to function
5146 if (!ComplainAboutFunc)
5147 ComplainAboutFunc = rex;
5148 } else if (!rpointee->isDependentType() &&
5149 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005150 PDiag(diag::err_typecheck_sub_ptr_object)
5151 << rex->getSourceRange()
5152 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005153 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005154
Eli Friedman168fe152009-05-16 13:54:38 +00005155 if (getLangOptions().CPlusPlus) {
5156 // Pointee types must be the same: C++ [expr.add]
5157 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5158 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5159 << lex->getType() << rex->getType()
5160 << lex->getSourceRange() << rex->getSourceRange();
5161 return QualType();
5162 }
5163 } else {
5164 // Pointee types must be compatible C99 6.5.6p3
5165 if (!Context.typesAreCompatible(
5166 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5167 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5168 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5169 << lex->getType() << rex->getType()
5170 << lex->getSourceRange() << rex->getSourceRange();
5171 return QualType();
5172 }
Chris Lattner4d62f422007-12-09 21:53:25 +00005173 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005174
Douglas Gregorac1fb652009-03-24 19:52:54 +00005175 if (ComplainAboutVoid)
5176 Diag(Loc, diag::ext_gnu_void_ptr)
5177 << lex->getSourceRange() << rex->getSourceRange();
5178 if (ComplainAboutFunc)
5179 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005180 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005181 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005182
5183 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005184 return Context.getPointerDiffType();
5185 }
5186 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005187
Chris Lattner326f7572008-11-18 01:30:42 +00005188 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005189}
5190
Chris Lattner2a3569b2008-04-07 05:30:13 +00005191// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00005192QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00005193 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00005194 // C99 6.5.7p2: Each of the operands shall have integer type.
5195 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner326f7572008-11-18 01:30:42 +00005196 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005197
Nate Begemane46ee9a2009-10-25 02:26:48 +00005198 // Vector shifts promote their scalar inputs to vector type.
5199 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5200 return CheckVectorOperands(Loc, lex, rex);
5201
Chris Lattner5c11c412007-12-12 05:47:28 +00005202 // Shifts don't perform usual arithmetic conversions, they just do integer
5203 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00005204 QualType LHSTy = Context.isPromotableBitField(lex);
5205 if (LHSTy.isNull()) {
5206 LHSTy = lex->getType();
5207 if (LHSTy->isPromotableIntegerType())
5208 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005209 }
Chris Lattner3c133402007-12-13 07:28:16 +00005210 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005211 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005212
Chris Lattner5c11c412007-12-12 05:47:28 +00005213 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005214
Ryan Flynnf53fab82009-08-07 16:20:20 +00005215 // Sanity-check shift operands
5216 llvm::APSInt Right;
5217 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00005218 if (!rex->isValueDependent() &&
5219 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00005220 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00005221 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5222 else {
5223 llvm::APInt LeftBits(Right.getBitWidth(),
5224 Context.getTypeSize(lex->getType()));
5225 if (Right.uge(LeftBits))
5226 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5227 }
5228 }
5229
Chris Lattner5c11c412007-12-12 05:47:28 +00005230 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005231 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005232}
5233
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005234// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00005235QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005236 unsigned OpaqueOpc, bool isRelational) {
5237 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5238
Chris Lattner9a152e22009-12-05 05:40:13 +00005239 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00005240 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005241 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005242
John McCall99ce6bf2009-11-06 08:49:08 +00005243 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5244 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall644a4182009-11-05 00:40:04 +00005245
Chris Lattnerb620c342007-08-26 01:18:55 +00005246 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff47fea352007-08-10 18:26:40 +00005247 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5248 UsualArithmeticConversions(lex, rex);
5249 else {
5250 UsualUnaryConversions(lex);
5251 UsualUnaryConversions(rex);
5252 }
Steve Naroff31090012007-07-16 21:54:35 +00005253 QualType lType = lex->getType();
5254 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005255
Mike Stumpf70bcf72009-05-07 18:43:07 +00005256 if (!lType->isFloatingType()
5257 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00005258 // For non-floating point types, check for self-comparisons of the form
5259 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5260 // often indicate logic errors in the program.
Mike Stump11289f42009-09-09 15:08:12 +00005261 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenekde9e9682009-03-20 19:57:37 +00005262 // from macro expansions, and are usually quite deliberate.
Chris Lattner222b8bd2009-03-08 19:39:53 +00005263 Expr *LHSStripped = lex->IgnoreParens();
5264 Expr *RHSStripped = rex->IgnoreParens();
5265 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5266 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenek9ffbe412009-03-20 18:35:45 +00005267 if (DRL->getDecl() == DRR->getDecl() &&
5268 !isa<EnumConstantDecl>(DRL->getDecl()))
Douglas Gregor49862b82010-01-12 23:18:54 +00005269 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Mike Stump11289f42009-09-09 15:08:12 +00005270
Chris Lattner222b8bd2009-03-08 19:39:53 +00005271 if (isa<CastExpr>(LHSStripped))
5272 LHSStripped = LHSStripped->IgnoreParenCasts();
5273 if (isa<CastExpr>(RHSStripped))
5274 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005275
Chris Lattner222b8bd2009-03-08 19:39:53 +00005276 // Warn about comparisons against a string constant (unless the other
5277 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005278 Expr *literalString = 0;
5279 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00005280 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005281 !RHSStripped->isNullPointerConstant(Context,
5282 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005283 literalString = lex;
5284 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00005285 } else if ((isa<StringLiteral>(RHSStripped) ||
5286 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005287 !LHSStripped->isNullPointerConstant(Context,
5288 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005289 literalString = rex;
5290 literalStringStripped = RHSStripped;
5291 }
5292
5293 if (literalString) {
5294 std::string resultComparison;
5295 switch (Opc) {
5296 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5297 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5298 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5299 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5300 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5301 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5302 default: assert(false && "Invalid comparison operator");
5303 }
Douglas Gregor49862b82010-01-12 23:18:54 +00005304
5305 DiagRuntimeBehavior(Loc,
5306 PDiag(diag::warn_stringcompare)
5307 << isa<ObjCEncodeExpr>(literalStringStripped)
5308 << literalString->getSourceRange()
5309 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5310 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5311 "strcmp(")
5312 << CodeModificationHint::CreateInsertion(
5313 PP.getLocForEndOfToken(rex->getLocEnd()),
5314 resultComparison));
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005315 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00005316 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005317
Douglas Gregorca63811b2008-11-19 03:25:36 +00005318 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00005319 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00005320
Chris Lattnerb620c342007-08-26 01:18:55 +00005321 if (isRelational) {
5322 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005323 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005324 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00005325 // Check for comparisons of floating point operands using != and ==.
Chris Lattner9a152e22009-12-05 05:40:13 +00005326 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner326f7572008-11-18 01:30:42 +00005327 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005328
Chris Lattnerb620c342007-08-26 01:18:55 +00005329 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005330 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005331 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005332
Douglas Gregor56751b52009-09-25 04:25:58 +00005333 bool LHSIsNull = lex->isNullPointerConstant(Context,
5334 Expr::NPC_ValueDependentIsNull);
5335 bool RHSIsNull = rex->isNullPointerConstant(Context,
5336 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005337
Chris Lattnerb620c342007-08-26 01:18:55 +00005338 // All of the following pointer related warnings are GCC extensions, except
5339 // when handling null pointer constants. One day, we can consider making them
5340 // errors (when -pedantic-errors is enabled).
Steve Naroff808eb8f2007-08-27 04:08:11 +00005341 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00005342 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005343 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00005344 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005345 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005346
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005347 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00005348 if (LCanPointeeTy == RCanPointeeTy)
5349 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005350 if (!isRelational &&
5351 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5352 // Valid unless comparison between non-null pointer and function pointer
5353 // This is a gcc extension compatibility comparison.
5354 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5355 && !LHSIsNull && !RHSIsNull) {
5356 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5357 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5358 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5359 return ResultTy;
5360 }
5361 }
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005362 // C++ [expr.rel]p2:
5363 // [...] Pointer conversions (4.10) and qualification
5364 // conversions (4.4) are performed on pointer operands (or on
5365 // a pointer operand and a null pointer constant) to bring
5366 // them to their composite pointer type. [...]
5367 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005368 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005369 // comparisons of pointers.
Douglas Gregorb8420462009-05-05 04:50:50 +00005370 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005371 if (T.isNull()) {
5372 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5373 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5374 return QualType();
5375 }
5376
Eli Friedman06ed2a52009-10-20 08:27:19 +00005377 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5378 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005379 return ResultTy;
5380 }
Eli Friedman16c209612009-08-23 00:27:47 +00005381 // C99 6.5.9p2 and C99 6.5.8p2
5382 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5383 RCanPointeeTy.getUnqualifiedType())) {
5384 // Valid unless a relational comparison of function pointers
5385 if (isRelational && LCanPointeeTy->isFunctionType()) {
5386 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5387 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5388 }
5389 } else if (!isRelational &&
5390 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5391 // Valid unless comparison between non-null pointer and function pointer
5392 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5393 && !LHSIsNull && !RHSIsNull) {
5394 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5395 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5396 }
5397 } else {
5398 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00005399 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005400 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00005401 }
Eli Friedman16c209612009-08-23 00:27:47 +00005402 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005403 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005404 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005405 }
Mike Stump11289f42009-09-09 15:08:12 +00005406
Sebastian Redl576fd422009-05-10 18:38:11 +00005407 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00005408 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005409 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00005410 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005411 (lType->isPointerType() ||
5412 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005413 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005414 return ResultTy;
5415 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005416 if (LHSIsNull &&
5417 (rType->isPointerType() ||
5418 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005419 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005420 return ResultTy;
5421 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005422
5423 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00005424 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005425 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5426 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005427 // In addition, pointers to members can be compared, or a pointer to
5428 // member and a null pointer constant. Pointer to member conversions
5429 // (4.11) and qualification conversions (4.4) are performed to bring
5430 // them to a common type. If one operand is a null pointer constant,
5431 // the common type is the type of the other operand. Otherwise, the
5432 // common type is a pointer to member type similar (4.4) to the type
5433 // of one of the operands, with a cv-qualification signature (4.4)
5434 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005435 // types.
5436 QualType T = FindCompositePointerType(lex, rex);
5437 if (T.isNull()) {
5438 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5439 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5440 return QualType();
5441 }
Mike Stump11289f42009-09-09 15:08:12 +00005442
Eli Friedman06ed2a52009-10-20 08:27:19 +00005443 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5444 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005445 return ResultTy;
5446 }
Mike Stump11289f42009-09-09 15:08:12 +00005447
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005448 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00005449 if (lType->isNullPtrType() && rType->isNullPtrType())
5450 return ResultTy;
5451 }
Mike Stump11289f42009-09-09 15:08:12 +00005452
Steve Naroff081c7422008-09-04 15:10:53 +00005453 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00005454 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005455 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5456 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005457
Steve Naroff081c7422008-09-04 15:10:53 +00005458 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00005459 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005460 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005461 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00005462 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005463 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005464 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00005465 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00005466 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00005467 if (!isRelational
5468 && ((lType->isBlockPointerType() && rType->isPointerType())
5469 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00005470 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005471 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005472 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005473 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005474 ->getPointeeType()->isVoidType())))
5475 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5476 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00005477 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005478 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005479 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00005480 }
Steve Naroff081c7422008-09-04 15:10:53 +00005481
Steve Naroff7cae42b2009-07-10 23:34:53 +00005482 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005483 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005484 const PointerType *LPT = lType->getAs<PointerType>();
5485 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005486 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005487 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005488 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005489 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005490
Steve Naroff753567f2008-11-17 19:49:16 +00005491 if (!LPtrToVoid && !RPtrToVoid &&
5492 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005493 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005494 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005495 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005496 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005497 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00005498 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005499 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005500 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005501 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5502 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005503 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005504 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00005505 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00005506 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005507 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005508 unsigned DiagID = 0;
5509 if (RHSIsNull) {
5510 if (isRelational)
5511 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5512 } else if (isRelational)
5513 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5514 else
5515 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005516
Chris Lattnerd99bd522009-08-23 00:03:44 +00005517 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005518 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005519 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005520 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005521 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005522 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005523 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005524 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005525 unsigned DiagID = 0;
5526 if (LHSIsNull) {
5527 if (isRelational)
5528 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5529 } else if (isRelational)
5530 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5531 else
5532 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005533
Chris Lattnerd99bd522009-08-23 00:03:44 +00005534 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005535 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005536 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005537 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005538 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005539 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00005540 }
Steve Naroff4b191572008-09-04 16:56:14 +00005541 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00005542 if (!isRelational && RHSIsNull
5543 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005544 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005545 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005546 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00005547 if (!isRelational && LHSIsNull
5548 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005549 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005550 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005551 }
Chris Lattner326f7572008-11-18 01:30:42 +00005552 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005553}
5554
Nate Begeman191a6b12008-07-14 18:02:46 +00005555/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00005556/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00005557/// like a scalar comparison, a vector comparison produces a vector of integer
5558/// types.
5559QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00005560 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00005561 bool isRelational) {
5562 // Check to make sure we're operating on vectors of the same type and width,
5563 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00005564 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005565 if (vType.isNull())
5566 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005567
Nate Begeman191a6b12008-07-14 18:02:46 +00005568 QualType lType = lex->getType();
5569 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005570
Nate Begeman191a6b12008-07-14 18:02:46 +00005571 // For non-floating point types, check for self-comparisons of the form
5572 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5573 // often indicate logic errors in the program.
5574 if (!lType->isFloatingType()) {
5575 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5576 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5577 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregor49862b82010-01-12 23:18:54 +00005578 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Nate Begeman191a6b12008-07-14 18:02:46 +00005579 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005580
Nate Begeman191a6b12008-07-14 18:02:46 +00005581 // Check for comparisons of floating point operands using != and ==.
5582 if (!isRelational && lType->isFloatingType()) {
5583 assert (rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00005584 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005585 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005586
Nate Begeman191a6b12008-07-14 18:02:46 +00005587 // Return the type for the comparison, which is the same as vector type for
5588 // integer vectors, or an integer type of identical size and number of
5589 // elements for floating point vectors.
5590 if (lType->isIntegerType())
5591 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005592
John McCall9dd450b2009-09-21 23:43:11 +00005593 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00005594 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005595 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00005596 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00005597 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005598 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5599
Mike Stump4e1f26a2009-02-19 03:04:26 +00005600 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005601 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00005602 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5603}
5604
Steve Naroff218bc2b2007-05-04 21:54:46 +00005605inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005606 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff94a5aca2007-07-16 22:23:01 +00005607 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005608 return CheckVectorOperands(Loc, lex, rex);
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005609
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005610 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005611
Steve Naroffdbd9e892007-07-17 00:58:39 +00005612 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005613 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00005614 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005615}
5616
Steve Naroff218bc2b2007-05-04 21:54:46 +00005617inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump11289f42009-09-09 15:08:12 +00005618 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005619 if (!Context.getLangOptions().CPlusPlus) {
5620 UsualUnaryConversions(lex);
5621 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005622
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005623 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5624 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005625
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005626 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00005627 }
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005628
5629 // C++ [expr.log.and]p1
5630 // C++ [expr.log.or]p1
5631 // The operands are both implicitly converted to type bool (clause 4).
5632 StandardConversionSequence LHS;
5633 if (!IsStandardConversion(lex, Context.BoolTy,
5634 /*InOverloadResolution=*/false, LHS))
5635 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005636
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005637 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005638 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005639 return InvalidOperands(Loc, lex, rex);
5640
5641 StandardConversionSequence RHS;
5642 if (!IsStandardConversion(rex, Context.BoolTy,
5643 /*InOverloadResolution=*/false, RHS))
5644 return InvalidOperands(Loc, lex, rex);
5645
5646 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005647 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005648 return InvalidOperands(Loc, lex, rex);
5649
5650 // C++ [expr.log.and]p2
5651 // C++ [expr.log.or]p2
5652 // The result is a bool.
5653 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00005654}
5655
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005656/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5657/// is a read-only property; return true if so. A readonly property expression
5658/// depends on various declarations and thus must be treated specially.
5659///
Mike Stump11289f42009-09-09 15:08:12 +00005660static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005661 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5662 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5663 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5664 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005665 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00005666 BaseType->getAsObjCInterfacePointerType())
5667 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5668 if (S.isPropertyReadonly(PDecl, IFace))
5669 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005670 }
5671 }
5672 return false;
5673}
5674
Chris Lattner30bd3272008-11-18 01:22:49 +00005675/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5676/// emit an error and return true. If so, return false.
5677static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005678 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00005679 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005680 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005681 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5682 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00005683 if (IsLV == Expr::MLV_Valid)
5684 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005685
Chris Lattner30bd3272008-11-18 01:22:49 +00005686 unsigned Diag = 0;
5687 bool NeedType = false;
5688 switch (IsLV) { // C99 6.5.16p2
5689 default: assert(0 && "Unknown result from isModifiableLvalue!");
5690 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005691 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005692 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5693 NeedType = true;
5694 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005695 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005696 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5697 NeedType = true;
5698 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00005699 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00005700 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5701 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005702 case Expr::MLV_InvalidExpression:
Chris Lattner30bd3272008-11-18 01:22:49 +00005703 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5704 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005705 case Expr::MLV_IncompleteType:
5706 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00005707 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00005708 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5709 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00005710 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00005711 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5712 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00005713 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00005714 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5715 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00005716 case Expr::MLV_ReadonlyProperty:
5717 Diag = diag::error_readonly_property_assignment;
5718 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00005719 case Expr::MLV_NoSetterProperty:
5720 Diag = diag::error_nosetter_property_assignment;
5721 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00005722 case Expr::MLV_SubObjCPropertySetting:
5723 Diag = diag::error_no_subobject_property_setting;
5724 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005725 }
Steve Naroffad373bd2007-07-31 12:34:36 +00005726
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005727 SourceRange Assign;
5728 if (Loc != OrigLoc)
5729 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00005730 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005731 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005732 else
Mike Stump11289f42009-09-09 15:08:12 +00005733 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005734 return true;
5735}
5736
5737
5738
5739// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00005740QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5741 SourceLocation Loc,
5742 QualType CompoundType) {
5743 // Verify that LHS is a modifiable lvalue, and emit error if not.
5744 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00005745 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00005746
5747 QualType LHSType = LHS->getType();
5748 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005749
Chris Lattner9bad62c2008-01-04 18:04:52 +00005750 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00005751 if (CompoundType.isNull()) {
Chris Lattnerea714382008-08-21 18:04:13 +00005752 // Simple assignment "x = y".
Chris Lattner326f7572008-11-18 01:30:42 +00005753 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005754 // Special case of NSObject attributes on c-style pointer types.
5755 if (ConvTy == IncompatiblePointer &&
5756 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005757 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005758 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005759 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005760 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005761
Chris Lattnerea714382008-08-21 18:04:13 +00005762 // If the RHS is a unary plus or minus, check to see if they = and + are
5763 // right next to each other. If so, the user may have typo'd "x =+ 4"
5764 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00005765 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00005766 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5767 RHSCheck = ICE->getSubExpr();
5768 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5769 if ((UO->getOpcode() == UnaryOperator::Plus ||
5770 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00005771 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00005772 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00005773 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5774 // And there is a space or other character before the subexpr of the
5775 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00005776 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5777 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005778 Diag(Loc, diag::warn_not_compound_assign)
5779 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5780 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00005781 }
Chris Lattnerea714382008-08-21 18:04:13 +00005782 }
5783 } else {
5784 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00005785 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00005786 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005787
Chris Lattner326f7572008-11-18 01:30:42 +00005788 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005789 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005790 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005791
Steve Naroff98cf3e92007-06-06 18:38:38 +00005792 // C99 6.5.16p3: The type of an assignment expression is the type of the
5793 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00005794 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00005795 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5796 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00005797 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00005798 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00005799 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00005800}
5801
Chris Lattner326f7572008-11-18 01:30:42 +00005802// C99 6.5.17
5803QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattnerf6e1e302008-07-25 20:54:07 +00005804 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00005805 // C++ does not perform this conversion (C++ [expr.comma]p1).
5806 if (!getLangOptions().CPlusPlus)
5807 DefaultFunctionArrayLvalueConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00005808
5809 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5810 // incomplete in C++).
5811
Chris Lattner326f7572008-11-18 01:30:42 +00005812 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00005813}
5814
Steve Naroff7a5af782007-07-13 16:58:59 +00005815/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5816/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00005817QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5818 bool isInc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005819 if (Op->isTypeDependent())
5820 return Context.DependentTy;
5821
Chris Lattner6b0cf142008-11-21 07:05:48 +00005822 QualType ResType = Op->getType();
5823 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00005824
Sebastian Redle10c2c32008-12-20 09:35:34 +00005825 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5826 // Decrement of bool is not allowed.
5827 if (!isInc) {
5828 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5829 return QualType();
5830 }
5831 // Increment of bool sets it to true, but is deprecated.
5832 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5833 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005834 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00005835 } else if (ResType->isAnyPointerType()) {
5836 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005837
Chris Lattner6b0cf142008-11-21 07:05:48 +00005838 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00005839 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005840 if (getLangOptions().CPlusPlus) {
5841 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5842 << Op->getSourceRange();
5843 return QualType();
5844 }
5845
5846 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005847 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005848 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005849 if (getLangOptions().CPlusPlus) {
5850 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5851 << Op->getType() << Op->getSourceRange();
5852 return QualType();
5853 }
5854
5855 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005856 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005857 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00005858 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005859 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005860 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00005861 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00005862 // Diagnose bad cases where we step over interface counts.
5863 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5864 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5865 << PointeeTy << Op->getSourceRange();
5866 return QualType();
5867 }
Eli Friedman090addd2010-01-03 00:20:48 +00005868 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005869 // C99 does not support ++/-- on complex types, we allow as an extension.
5870 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005871 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005872 } else {
5873 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00005874 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005875 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00005876 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005877 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00005878 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005879 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00005880 return QualType();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005881 return ResType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005882}
5883
Anders Carlsson806700f2008-02-01 07:15:58 +00005884/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00005885/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005886/// where the declaration is needed for type checking. We only need to
5887/// handle cases when the expression references a function designator
5888/// or is an lvalue. Here are some examples:
5889/// - &(x) => x
5890/// - &*****f => f for f a function designator.
5891/// - &s.xx => s
5892/// - &s.zz[1].yy -> s, if zz is an array
5893/// - *(x + 1) -> x, if x is an array
5894/// - &"123"[2] -> 0
5895/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005896static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005897 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00005898 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005899 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00005900 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005901 // If this is an arrow operator, the address is an offset from
5902 // the base's value, so the object the base refers to is
5903 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005904 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00005905 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00005906 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005907 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00005908 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00005909 // FIXME: This code shouldn't be necessary! We should catch the implicit
5910 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00005911 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5912 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5913 if (ICE->getSubExpr()->getType()->isArrayType())
5914 return getPrimaryDecl(ICE->getSubExpr());
5915 }
5916 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00005917 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005918 case Stmt::UnaryOperatorClass: {
5919 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005920
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005921 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005922 case UnaryOperator::Real:
5923 case UnaryOperator::Imag:
5924 case UnaryOperator::Extension:
5925 return getPrimaryDecl(UO->getSubExpr());
5926 default:
5927 return 0;
5928 }
5929 }
Steve Naroff47500512007-04-19 23:00:49 +00005930 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005931 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00005932 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005933 // If the result of an implicit cast is an l-value, we care about
5934 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005935 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00005936 default:
5937 return 0;
5938 }
5939}
5940
5941/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00005942/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00005943/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005944/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005945/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005946/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00005947/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00005948QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005949 // Make sure to ignore parentheses in subsequent checks
5950 op = op->IgnoreParens();
5951
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00005952 if (op->isTypeDependent())
5953 return Context.DependentTy;
5954
Steve Naroff826e91a2008-01-13 17:10:08 +00005955 if (getLangOptions().C99) {
5956 // Implement C99-only parts of addressof rules.
5957 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5958 if (uOp->getOpcode() == UnaryOperator::Deref)
5959 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5960 // (assuming the deref expression is valid).
5961 return uOp->getSubExpr()->getType();
5962 }
5963 // Technically, there should be a check for array subscript
5964 // expressions here, but the result of one is always an lvalue anyway.
5965 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005966 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00005967 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00005968
Sebastian Redl9a8dd0d2010-01-11 15:56:56 +00005969 MemberExpr *ME = dyn_cast<MemberExpr>(op);
5970 if (lval == Expr::LV_MemberFunction && ME &&
5971 isa<CXXMethodDecl>(ME->getMemberDecl())) {
5972 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
5973 // &f where f is a member of the current object, or &o.f, or &p->f
5974 // All these are not allowed, and we need to catch them before the dcl
5975 // branch of the if, below.
5976 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
5977 << dcl;
5978 // FIXME: Improve this diagnostic and provide a fixit.
5979
5980 // Now recover by acting as if the function had been accessed qualified.
5981 return Context.getMemberPointerType(op->getType(),
5982 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
5983 .getTypePtr());
5984 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00005985 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005986 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00005987 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00005988 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00005989 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5990 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005991 return QualType();
5992 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00005993 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005994 // The operand cannot be a bit-field
5995 Diag(OpLoc, diag::err_typecheck_address_of)
5996 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00005997 return QualType();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00005998 } else if (op->refersToVectorElement()) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005999 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00006000 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00006001 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00006002 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00006003 } else if (isa<ObjCPropertyRefExpr>(op)) {
6004 // cannot take address of a property expression.
6005 Diag(OpLoc, diag::err_typecheck_address_of)
6006 << "property expression" << op->getSourceRange();
6007 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00006008 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
6009 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00006010 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
6011 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00006012 } else if (isa<UnresolvedLookupExpr>(op)) {
6013 return Context.OverloadTy;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00006014 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00006015 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00006016 // with the register storage-class specifier.
6017 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00006018 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006019 Diag(OpLoc, diag::err_typecheck_address_of)
6020 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00006021 return QualType();
6022 }
John McCalld14a8642009-11-21 08:51:07 +00006023 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006024 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00006025 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00006026 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006027 // Could be a pointer to member, though, if there is an explicit
6028 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006029 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006030 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00006031 if (Ctx && Ctx->isRecord()) {
6032 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006033 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00006034 diag::err_cannot_form_pointer_to_member_of_reference_type)
6035 << FD->getDeclName() << FD->getType();
6036 return QualType();
6037 }
Mike Stump11289f42009-09-09 15:08:12 +00006038
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006039 return Context.getMemberPointerType(op->getType(),
6040 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00006041 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006042 }
Anders Carlsson5b535762009-05-16 21:43:42 +00006043 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00006044 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006045 // As above.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006046 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
6047 MD->isInstance())
Anders Carlsson5b535762009-05-16 21:43:42 +00006048 return Context.getMemberPointerType(op->getType(),
6049 Context.getTypeDeclType(MD->getParent()).getTypePtr());
6050 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00006051 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00006052 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006053
Eli Friedmance7f9002009-05-16 23:27:50 +00006054 if (lval == Expr::LV_IncompleteVoidType) {
6055 // Taking the address of a void variable is technically illegal, but we
6056 // allow it in cases which are otherwise valid.
6057 // Example: "extern void x; void* y = &x;".
6058 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6059 }
6060
Steve Naroff47500512007-04-19 23:00:49 +00006061 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +00006062 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00006063}
6064
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006065QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006066 if (Op->isTypeDependent())
6067 return Context.DependentTy;
6068
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006069 UsualUnaryConversions(Op);
6070 QualType Ty = Op->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006071
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006072 // Note that per both C89 and C99, this is always legal, even if ptype is an
6073 // incomplete type or void. It would be possible to warn about dereferencing
6074 // a void pointer, but it's completely well-defined, and such a warning is
6075 // unlikely to catch any mistakes.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006076 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff826e91a2008-01-13 17:10:08 +00006077 return PT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006078
John McCall9dd450b2009-09-21 23:43:11 +00006079 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +00006080 return OPT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006081
Chris Lattner29e812b2008-11-20 06:06:08 +00006082 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006083 << Ty << Op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00006084 return QualType();
Steve Naroff1926c832007-04-24 00:23:05 +00006085}
Steve Naroff218bc2b2007-05-04 21:54:46 +00006086
6087static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6088 tok::TokenKind Kind) {
6089 BinaryOperator::Opcode Opc;
6090 switch (Kind) {
6091 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00006092 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
6093 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006094 case tok::star: Opc = BinaryOperator::Mul; break;
6095 case tok::slash: Opc = BinaryOperator::Div; break;
6096 case tok::percent: Opc = BinaryOperator::Rem; break;
6097 case tok::plus: Opc = BinaryOperator::Add; break;
6098 case tok::minus: Opc = BinaryOperator::Sub; break;
6099 case tok::lessless: Opc = BinaryOperator::Shl; break;
6100 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
6101 case tok::lessequal: Opc = BinaryOperator::LE; break;
6102 case tok::less: Opc = BinaryOperator::LT; break;
6103 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6104 case tok::greater: Opc = BinaryOperator::GT; break;
6105 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6106 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6107 case tok::amp: Opc = BinaryOperator::And; break;
6108 case tok::caret: Opc = BinaryOperator::Xor; break;
6109 case tok::pipe: Opc = BinaryOperator::Or; break;
6110 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6111 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6112 case tok::equal: Opc = BinaryOperator::Assign; break;
6113 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6114 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6115 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6116 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6117 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6118 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6119 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6120 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6121 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6122 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6123 case tok::comma: Opc = BinaryOperator::Comma; break;
6124 }
6125 return Opc;
6126}
6127
Steve Naroff35d85152007-05-07 00:24:15 +00006128static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6129 tok::TokenKind Kind) {
6130 UnaryOperator::Opcode Opc;
6131 switch (Kind) {
6132 default: assert(0 && "Unknown unary op!");
6133 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6134 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6135 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6136 case tok::star: Opc = UnaryOperator::Deref; break;
6137 case tok::plus: Opc = UnaryOperator::Plus; break;
6138 case tok::minus: Opc = UnaryOperator::Minus; break;
6139 case tok::tilde: Opc = UnaryOperator::Not; break;
6140 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006141 case tok::kw___real: Opc = UnaryOperator::Real; break;
6142 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00006143 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006144 }
6145 return Opc;
6146}
6147
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006148/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6149/// operator @p Opc at location @c TokLoc. This routine only supports
6150/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006151Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6152 unsigned Op,
6153 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006154 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006155 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006156 // The following two variables are used for compound assignment operators
6157 QualType CompLHSTy; // Type of LHS after promotions for computation
6158 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006159
6160 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006161 case BinaryOperator::Assign:
6162 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6163 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006164 case BinaryOperator::PtrMemD:
6165 case BinaryOperator::PtrMemI:
6166 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6167 Opc == BinaryOperator::PtrMemI);
6168 break;
6169 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006170 case BinaryOperator::Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00006171 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6172 Opc == BinaryOperator::Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006173 break;
6174 case BinaryOperator::Rem:
6175 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6176 break;
6177 case BinaryOperator::Add:
6178 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6179 break;
6180 case BinaryOperator::Sub:
6181 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6182 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006183 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006184 case BinaryOperator::Shr:
6185 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6186 break;
6187 case BinaryOperator::LE:
6188 case BinaryOperator::LT:
6189 case BinaryOperator::GE:
6190 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006191 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006192 break;
6193 case BinaryOperator::EQ:
6194 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006195 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006196 break;
6197 case BinaryOperator::And:
6198 case BinaryOperator::Xor:
6199 case BinaryOperator::Or:
6200 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6201 break;
6202 case BinaryOperator::LAnd:
6203 case BinaryOperator::LOr:
6204 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6205 break;
6206 case BinaryOperator::MulAssign:
6207 case BinaryOperator::DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00006208 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6209 Opc == BinaryOperator::DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006210 CompLHSTy = CompResultTy;
6211 if (!CompResultTy.isNull())
6212 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006213 break;
6214 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006215 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6216 CompLHSTy = CompResultTy;
6217 if (!CompResultTy.isNull())
6218 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006219 break;
6220 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006221 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6222 if (!CompResultTy.isNull())
6223 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006224 break;
6225 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006226 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6227 if (!CompResultTy.isNull())
6228 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006229 break;
6230 case BinaryOperator::ShlAssign:
6231 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006232 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6233 CompLHSTy = CompResultTy;
6234 if (!CompResultTy.isNull())
6235 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006236 break;
6237 case BinaryOperator::AndAssign:
6238 case BinaryOperator::XorAssign:
6239 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006240 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6241 CompLHSTy = CompResultTy;
6242 if (!CompResultTy.isNull())
6243 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006244 break;
6245 case BinaryOperator::Comma:
6246 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6247 break;
6248 }
6249 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006250 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006251 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00006252 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6253 else
6254 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006255 CompLHSTy, CompResultTy,
6256 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006257}
6258
Sebastian Redl44615072009-10-27 12:10:02 +00006259/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6260/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006261static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6262 const PartialDiagnostic &PD,
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006263 SourceRange ParenRange,
6264 const PartialDiagnostic &SecondPD = PartialDiagnostic(0),
6265 SourceRange SecondParenRange = SourceRange()) {
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006266 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6267 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6268 // We can't display the parentheses, so just dig the
6269 // warning/error and return.
6270 Self.Diag(Loc, PD);
6271 return;
6272 }
6273
6274 Self.Diag(Loc, PD)
6275 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6276 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006277
6278 if (!SecondPD.getDiagID())
6279 return;
6280
6281 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6282 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6283 // We can't display the parentheses, so just dig the
6284 // warning/error and return.
6285 Self.Diag(Loc, SecondPD);
6286 return;
6287 }
6288
6289 Self.Diag(Loc, SecondPD)
6290 << CodeModificationHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6291 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006292}
6293
Sebastian Redl44615072009-10-27 12:10:02 +00006294/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6295/// operators are mixed in a way that suggests that the programmer forgot that
6296/// comparison operators have higher precedence. The most typical example of
6297/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl43028242009-10-26 15:24:15 +00006298static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6299 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006300 typedef BinaryOperator BinOp;
6301 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6302 rhsopc = static_cast<BinOp::Opcode>(-1);
6303 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006304 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00006305 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006306 rhsopc = BO->getOpcode();
6307
6308 // Subs are not binary operators.
6309 if (lhsopc == -1 && rhsopc == -1)
6310 return;
6311
6312 // Bitwise operations are sometimes used as eager logical ops.
6313 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00006314 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6315 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00006316 return;
6317
Sebastian Redl44615072009-10-27 12:10:02 +00006318 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006319 SuggestParentheses(Self, OpLoc,
6320 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006321 << SourceRange(lhs->getLocStart(), OpLoc)
6322 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006323 lhs->getSourceRange(),
6324 PDiag(diag::note_precedence_bitwise_first)
6325 << BinOp::getOpcodeStr(Opc),
Sebastian Redl44615072009-10-27 12:10:02 +00006326 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6327 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006328 SuggestParentheses(Self, OpLoc,
6329 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006330 << SourceRange(OpLoc, rhs->getLocEnd())
6331 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006332 rhs->getSourceRange(),
6333 PDiag(diag::note_precedence_bitwise_first)
6334 << BinOp::getOpcodeStr(Opc),
Sebastian Redl44615072009-10-27 12:10:02 +00006335 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl43028242009-10-26 15:24:15 +00006336}
6337
6338/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6339/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6340/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6341static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6342 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006343 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl43028242009-10-26 15:24:15 +00006344 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6345}
6346
Steve Naroff218bc2b2007-05-04 21:54:46 +00006347// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006348Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6349 tok::TokenKind Kind,
6350 ExprArg LHS, ExprArg RHS) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00006351 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006352 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Steve Naroff218bc2b2007-05-04 21:54:46 +00006353
Steve Naroff83895f72007-09-16 03:34:24 +00006354 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6355 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00006356
Sebastian Redl43028242009-10-26 15:24:15 +00006357 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6358 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6359
Douglas Gregor5287f092009-11-05 00:51:44 +00006360 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6361}
6362
6363Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6364 BinaryOperator::Opcode Opc,
6365 Expr *lhs, Expr *rhs) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006366 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00006367 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006368 rhs->getType()->isOverloadableType())) {
6369 // Find all of the overloaded operators visible from this
6370 // point. We perform both an operator-name lookup from the local
6371 // scope and an argument-dependent lookup based on the types of
6372 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00006373 UnresolvedSet<16> Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006374 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00006375 if (S && OverOp != OO_None)
6376 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6377 Functions);
Douglas Gregor5287f092009-11-05 00:51:44 +00006378
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006379 // Build the (potentially-overloaded, potentially-dependent)
6380 // binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006381 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00006382 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006383
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006384 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006385 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006386}
6387
Douglas Gregor084d8552009-03-13 23:49:33 +00006388Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006389 unsigned OpcIn,
Douglas Gregor084d8552009-03-13 23:49:33 +00006390 ExprArg InputArg) {
6391 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00006392
Mike Stump87c57ac2009-05-16 07:39:55 +00006393 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregor084d8552009-03-13 23:49:33 +00006394 Expr *Input = (Expr *)InputArg.get();
Steve Naroff35d85152007-05-07 00:24:15 +00006395 QualType resultType;
6396 switch (Opc) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006397 case UnaryOperator::OffsetOf:
6398 assert(false && "Invalid unary operator");
6399 break;
6400
Steve Naroff35d85152007-05-07 00:24:15 +00006401 case UnaryOperator::PreInc:
6402 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00006403 case UnaryOperator::PostInc:
6404 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00006405 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00006406 Opc == UnaryOperator::PreInc ||
6407 Opc == UnaryOperator::PostInc);
Steve Naroff35d85152007-05-07 00:24:15 +00006408 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006409 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00006410 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006411 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006412 case UnaryOperator::Deref:
Douglas Gregorb92a1562010-02-03 00:27:59 +00006413 DefaultFunctionArrayLvalueConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00006414 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006415 break;
6416 case UnaryOperator::Plus:
6417 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00006418 UsualUnaryConversions(Input);
6419 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006420 if (resultType->isDependentType())
6421 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006422 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6423 break;
6424 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6425 resultType->isEnumeralType())
6426 break;
6427 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6428 Opc == UnaryOperator::Plus &&
6429 resultType->isPointerType())
6430 break;
6431
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006432 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6433 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006434 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00006435 UsualUnaryConversions(Input);
6436 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006437 if (resultType->isDependentType())
6438 break;
Chris Lattner0d707612008-07-25 23:52:49 +00006439 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6440 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6441 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00006442 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006443 << resultType << Input->getSourceRange();
Chris Lattner0d707612008-07-25 23:52:49 +00006444 else if (!resultType->isIntegerType())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006445 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6446 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006447 break;
6448 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00006449 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00006450 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00006451 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006452 if (resultType->isDependentType())
6453 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006454 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006455 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6456 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00006457 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006458 // In C++, it's bool. C++ 5.3.1p8
6459 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00006460 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00006461 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00006462 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00006463 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00006464 break;
Chris Lattner86554282007-06-08 22:32:33 +00006465 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00006466 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00006467 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006468 }
6469 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006470 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00006471
6472 InputArg.release();
Steve Narofff6009ed2009-01-21 00:14:39 +00006473 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00006474}
Chris Lattnereefa10e2007-05-28 06:56:27 +00006475
Douglas Gregor5287f092009-11-05 00:51:44 +00006476Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6477 UnaryOperator::Opcode Opc,
6478 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006479 Expr *Input = (Expr*)input.get();
Anders Carlsson461a2c02009-11-14 21:26:41 +00006480 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6481 Opc != UnaryOperator::Extension) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006482 // Find all of the overloaded operators visible from this
6483 // point. We perform both an operator-name lookup from the local
6484 // scope and an argument-dependent lookup based on the types of
6485 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00006486 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00006487 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00006488 if (S && OverOp != OO_None)
6489 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6490 Functions);
Douglas Gregor5287f092009-11-05 00:51:44 +00006491
Douglas Gregor084d8552009-03-13 23:49:33 +00006492 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6493 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006494
Douglas Gregor084d8552009-03-13 23:49:33 +00006495 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6496}
6497
Douglas Gregor5287f092009-11-05 00:51:44 +00006498// Unary Operators. 'Tok' is the token for the operator.
6499Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6500 tok::TokenKind Op, ExprArg input) {
6501 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6502}
6503
Steve Naroff66356bd2007-09-16 14:56:35 +00006504/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006505Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6506 SourceLocation LabLoc,
6507 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00006508 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00006509 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00006510
Daniel Dunbar88402ce2008-08-04 16:51:22 +00006511 // If we haven't seen this label yet, create a forward reference. It
6512 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00006513 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00006514 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006515
Chris Lattnereefa10e2007-05-28 06:56:27 +00006516 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006517 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6518 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00006519}
6520
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006521Sema::OwningExprResult
6522Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6523 SourceLocation RPLoc) { // "({..})"
6524 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner366727f2007-07-24 16:58:17 +00006525 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6526 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6527
Eli Friedman52cc0162009-01-24 23:09:00 +00006528 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattnera69b0762009-04-25 19:11:05 +00006529 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006530 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00006531
Chris Lattner366727f2007-07-24 16:58:17 +00006532 // FIXME: there are a variety of strange constraints to enforce here, for
6533 // example, it is not possible to goto into a stmt expression apparently.
6534 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006535
Chris Lattner366727f2007-07-24 16:58:17 +00006536 // If there are sub stmts in the compound stmt, take the type of the last one
6537 // as the type of the stmtexpr.
6538 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006539
Chris Lattner944d3062008-07-26 19:51:01 +00006540 if (!Compound->body_empty()) {
6541 Stmt *LastStmt = Compound->body_back();
6542 // If LastStmt is a label, skip down through into the body.
6543 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6544 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006545
Chris Lattner944d3062008-07-26 19:51:01 +00006546 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00006547 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00006548 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006549
Eli Friedmanba961a92009-03-23 00:24:07 +00006550 // FIXME: Check that expression type is complete/non-abstract; statement
6551 // expressions are not lvalues.
6552
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006553 substmt.release();
6554 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00006555}
Steve Naroff78864672007-08-01 22:05:33 +00006556
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006557Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6558 SourceLocation BuiltinLoc,
6559 SourceLocation TypeLoc,
6560 TypeTy *argty,
6561 OffsetOfComponent *CompPtr,
6562 unsigned NumComponents,
6563 SourceLocation RPLoc) {
6564 // FIXME: This function leaks all expressions in the offset components on
6565 // error.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006566 // FIXME: Preserve type source info.
6567 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattnerf17bd422007-08-30 17:45:32 +00006568 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006569
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006570 bool Dependent = ArgTy->isDependentType();
6571
Chris Lattnerf17bd422007-08-30 17:45:32 +00006572 // We must have at least one component that refers to the type, and the first
6573 // one is known to be a field designator. Verify that the ArgTy represents
6574 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006575 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006576 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006577
Eli Friedmanba961a92009-03-23 00:24:07 +00006578 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6579 // with an incomplete type would be illegal.
Douglas Gregor26897462009-03-11 16:48:53 +00006580
Eli Friedman988a16b2009-02-27 06:44:11 +00006581 // Otherwise, create a null pointer as the base, and iteratively process
6582 // the offsetof designators.
6583 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6584 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006585 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman988a16b2009-02-27 06:44:11 +00006586 ArgTy, SourceLocation());
Eli Friedman16c88df2009-01-26 01:33:06 +00006587
Chris Lattner78502cf2007-08-31 21:49:13 +00006588 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6589 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00006590 // FIXME: This diagnostic isn't actually visible because the location is in
6591 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00006592 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00006593 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6594 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006595
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006596 if (!Dependent) {
Eli Friedman8469bc72009-05-03 21:22:18 +00006597 bool DidWarnAboutNonPOD = false;
Mike Stump11289f42009-09-09 15:08:12 +00006598
John McCall9eff4e62009-11-04 03:03:43 +00006599 if (RequireCompleteType(TypeLoc, Res->getType(),
6600 diag::err_offsetof_incomplete_type))
6601 return ExprError();
6602
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006603 // FIXME: Dependent case loses a lot of information here. And probably
6604 // leaks like a sieve.
6605 for (unsigned i = 0; i != NumComponents; ++i) {
6606 const OffsetOfComponent &OC = CompPtr[i];
6607 if (OC.isBrackets) {
6608 // Offset of an array sub-field. TODO: Should we allow vector elements?
6609 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6610 if (!AT) {
6611 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006612 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6613 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006614 }
6615
6616 // FIXME: C++: Verify that operator[] isn't overloaded.
6617
Eli Friedman988a16b2009-02-27 06:44:11 +00006618 // Promote the array so it looks more like a normal array subscript
6619 // expression.
Douglas Gregorb92a1562010-02-03 00:27:59 +00006620 DefaultFunctionArrayLvalueConversion(Res);
Eli Friedman988a16b2009-02-27 06:44:11 +00006621
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006622 // C99 6.5.2.1p1
6623 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006624 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006625 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006626 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner003af242009-04-25 22:50:55 +00006627 diag::err_typecheck_subscript_not_integer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006628 << Idx->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006629
6630 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6631 OC.LocEnd);
6632 continue;
Chris Lattnerf17bd422007-08-30 17:45:32 +00006633 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006634
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006635 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006636 if (!RC) {
6637 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006638 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6639 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006640 }
Chris Lattner98dbf0a2007-08-30 17:59:59 +00006641
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006642 // Get the decl corresponding to this.
6643 RecordDecl *RD = RC->getDecl();
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006644 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00006645 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6646 DiagRuntimeBehavior(BuiltinLoc,
6647 PDiag(diag::warn_offsetof_non_pod_type)
6648 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6649 << Res->getType()))
6650 DidWarnAboutNonPOD = true;
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006651 }
Mike Stump11289f42009-09-09 15:08:12 +00006652
John McCall27b18f82009-11-17 02:14:36 +00006653 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6654 LookupQualifiedName(R, RD);
John McCall9f3059a2009-10-09 21:13:30 +00006655
John McCall67c00872009-12-02 08:25:40 +00006656 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006657 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006658 if (!MemberDecl)
Douglas Gregore40876a2009-10-13 21:16:44 +00006659 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6660 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump4e1f26a2009-02-19 03:04:26 +00006661
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006662 // FIXME: C++: Verify that MemberDecl isn't a static field.
6663 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman64fc3c62009-04-26 20:50:44 +00006664 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00006665 Res = BuildAnonymousStructUnionMemberReference(
John McCall7e1d6d72009-11-11 03:23:23 +00006666 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedman64fc3c62009-04-26 20:50:44 +00006667 } else {
Eli Friedman78cde142009-12-04 07:18:51 +00006668 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedman64fc3c62009-04-26 20:50:44 +00006669 // MemberDecl->getType() doesn't get the right qualifiers, but it
6670 // doesn't matter here.
6671 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6672 MemberDecl->getType().getNonReferenceType());
6673 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006674 }
Chris Lattnerf17bd422007-08-30 17:45:32 +00006675 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006676
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006677 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6678 Context.getSizeType(), BuiltinLoc));
Chris Lattnerf17bd422007-08-30 17:45:32 +00006679}
6680
6681
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006682Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6683 TypeTy *arg1,TypeTy *arg2,
6684 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006685 // FIXME: Preserve type source info.
6686 QualType argT1 = GetTypeFromParser(arg1);
6687 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006688
Steve Naroff78864672007-08-01 22:05:33 +00006689 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006690
Douglas Gregorf907cbf2009-05-19 22:28:02 +00006691 if (getLangOptions().CPlusPlus) {
6692 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6693 << SourceRange(BuiltinLoc, RPLoc);
6694 return ExprError();
6695 }
6696
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006697 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6698 argT1, argT2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00006699}
6700
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006701Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6702 ExprArg cond,
6703 ExprArg expr1, ExprArg expr2,
6704 SourceLocation RPLoc) {
6705 Expr *CondExpr = static_cast<Expr*>(cond.get());
6706 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6707 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006708
Steve Naroff9efdabc2007-08-03 21:21:27 +00006709 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6710
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006711 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00006712 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00006713 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006714 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00006715 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006716 } else {
6717 // The conditional expression is required to be a constant expression.
6718 llvm::APSInt condEval(32);
6719 SourceLocation ExpLoc;
6720 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006721 return ExprError(Diag(ExpLoc,
6722 diag::err_typecheck_choose_expr_requires_constant)
6723 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00006724
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006725 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6726 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregor56751b52009-09-25 04:25:58 +00006727 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6728 : RHSExpr->isValueDependent();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006729 }
6730
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006731 cond.release(); expr1.release(); expr2.release();
6732 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregor56751b52009-09-25 04:25:58 +00006733 resType, RPLoc,
6734 resType->isDependentType(),
6735 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00006736}
6737
Steve Naroffc540d662008-09-03 18:15:37 +00006738//===----------------------------------------------------------------------===//
6739// Clang Extensions.
6740//===----------------------------------------------------------------------===//
6741
6742/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006743void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00006744 // Analyze block parameters.
6745 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006746
Steve Naroffc540d662008-09-03 18:15:37 +00006747 // Add BSI to CurBlock.
6748 BSI->PrevBlockInfo = CurBlock;
6749 CurBlock = BSI;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006750
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006751 BSI->ReturnType = QualType();
Steve Naroffc540d662008-09-03 18:15:37 +00006752 BSI->TheScope = BlockScope;
Mike Stumpa6703322009-02-19 22:01:56 +00006753 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarb9a68612009-07-29 01:59:17 +00006754 BSI->hasPrototype = false;
Chris Lattner45542ea2009-04-19 05:28:12 +00006755 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6756 CurFunctionNeedsScopeChecking = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006757
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006758 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek54ad1ab2009-12-07 22:01:30 +00006759 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor91f84212008-12-11 16:49:14 +00006760 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006761}
6762
Mike Stump82f071f2009-02-04 22:31:32 +00006763void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00006764 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump82f071f2009-02-04 22:31:32 +00006765
6766 if (ParamInfo.getNumTypeObjects() == 0
6767 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor758a8692009-06-17 21:51:59 +00006768 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump82f071f2009-02-04 22:31:32 +00006769 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6770
Mike Stumpd456c482009-04-28 01:10:27 +00006771 if (T->isArrayType()) {
6772 Diag(ParamInfo.getSourceRange().getBegin(),
6773 diag::err_block_returns_array);
6774 return;
6775 }
6776
Mike Stump82f071f2009-02-04 22:31:32 +00006777 // The parameter list is optional, if there was none, assume ().
6778 if (!T->isFunctionType())
6779 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6780
6781 CurBlock->hasPrototype = true;
6782 CurBlock->isVariadic = false;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006783 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006784 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006785 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006786 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006787 // FIXME: remove the attribute.
6788 }
John McCall9dd450b2009-09-21 23:43:11 +00006789 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006790
Chris Lattner6de05082009-04-11 19:27:54 +00006791 // Do not allow returning a objc interface by-value.
6792 if (RetTy->isObjCInterfaceType()) {
6793 Diag(ParamInfo.getSourceRange().getBegin(),
6794 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6795 return;
6796 }
Douglas Gregorb92a1562010-02-03 00:27:59 +00006797
6798 CurBlock->ReturnType = RetTy;
Mike Stump82f071f2009-02-04 22:31:32 +00006799 return;
6800 }
6801
Steve Naroffc540d662008-09-03 18:15:37 +00006802 // Analyze arguments to block.
6803 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6804 "Not a function declarator!");
6805 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006806
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006807 CurBlock->hasPrototype = FTI.hasPrototype;
6808 CurBlock->isVariadic = true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006809
Steve Naroffc540d662008-09-03 18:15:37 +00006810 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6811 // no arguments, not a function that takes a single void argument.
6812 if (FTI.hasPrototype &&
6813 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner83f095c2009-03-28 19:18:32 +00006814 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6815 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00006816 // empty arg list, don't push any params.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006817 CurBlock->isVariadic = false;
Steve Naroffc540d662008-09-03 18:15:37 +00006818 } else if (FTI.hasPrototype) {
6819 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner83f095c2009-03-28 19:18:32 +00006820 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006821 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroffc540d662008-09-03 18:15:37 +00006822 }
Jay Foad7d0479f2009-05-21 09:52:38 +00006823 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner6de05082009-04-11 19:27:54 +00006824 CurBlock->Params.size());
Fariborz Jahanian960910a2009-05-19 17:08:59 +00006825 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor758a8692009-06-17 21:51:59 +00006826 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006827 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00006828 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
6829 (*AI)->setOwningFunction(CurBlock->TheDecl);
6830
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006831 // If this has an identifier, add it to the scope stack.
6832 if ((*AI)->getIdentifier())
6833 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCallf7b2fb52010-01-22 00:28:27 +00006834 }
Chris Lattner6de05082009-04-11 19:27:54 +00006835
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006836 // Check for a valid sentinel attribute on this block.
Mike Stump11289f42009-09-09 15:08:12 +00006837 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006838 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006839 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006840 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006841 // FIXME: remove the attribute.
6842 }
Mike Stump11289f42009-09-09 15:08:12 +00006843
Chris Lattner6de05082009-04-11 19:27:54 +00006844 // Analyze the return type.
6845 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall9dd450b2009-09-21 23:43:11 +00006846 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006847
Chris Lattner6de05082009-04-11 19:27:54 +00006848 // Do not allow returning a objc interface by-value.
6849 if (RetTy->isObjCInterfaceType()) {
6850 Diag(ParamInfo.getSourceRange().getBegin(),
6851 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6852 } else if (!RetTy->isDependentType())
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006853 CurBlock->ReturnType = RetTy;
Steve Naroffc540d662008-09-03 18:15:37 +00006854}
6855
6856/// ActOnBlockError - If there is an error parsing a block, this callback
6857/// is invoked to pop the information about the block from the action impl.
6858void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6859 // Ensure that CurBlock is deleted.
6860 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006861
Chris Lattner45542ea2009-04-19 05:28:12 +00006862 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6863
Steve Naroffc540d662008-09-03 18:15:37 +00006864 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00006865 PopDeclContext();
Steve Naroffc540d662008-09-03 18:15:37 +00006866 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroffc540d662008-09-03 18:15:37 +00006867 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00006868}
6869
6870/// ActOnBlockStmtExpr - This is called when the body of a block statement
6871/// literal was successfully completed. ^(int x){...}
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006872Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6873 StmtArg body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00006874 // If blocks are disabled, emit an error.
6875 if (!LangOpts.Blocks)
6876 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00006877
Steve Naroffc540d662008-09-03 18:15:37 +00006878 // Ensure that CurBlock is deleted.
6879 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroffc540d662008-09-03 18:15:37 +00006880
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006881 PopDeclContext();
6882
Steve Naroffc540d662008-09-03 18:15:37 +00006883 // Pop off CurBlock, handle nested blocks.
6884 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006885
Steve Naroffc540d662008-09-03 18:15:37 +00006886 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006887 if (!BSI->ReturnType.isNull())
6888 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006889
Steve Naroffc540d662008-09-03 18:15:37 +00006890 llvm::SmallVector<QualType, 8> ArgTypes;
6891 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6892 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006893
Mike Stump3bf1ab42009-07-28 22:04:01 +00006894 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00006895 QualType BlockTy;
6896 if (!BSI->hasPrototype)
Mike Stump3bf1ab42009-07-28 22:04:01 +00006897 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6898 NoReturn);
Steve Naroffc540d662008-09-03 18:15:37 +00006899 else
Jay Foad7d0479f2009-05-21 09:52:38 +00006900 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump3bf1ab42009-07-28 22:04:01 +00006901 BSI->isVariadic, 0, false, false, 0, 0,
6902 NoReturn);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006903
Eli Friedmanba961a92009-03-23 00:24:07 +00006904 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006905 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroffc540d662008-09-03 18:15:37 +00006906 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006907
Chris Lattner45542ea2009-04-19 05:28:12 +00006908 // If needed, diagnose invalid gotos and switches in the block.
6909 if (CurFunctionNeedsScopeChecking)
6910 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6911 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump11289f42009-09-09 15:08:12 +00006912
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006913 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump314825b2010-01-19 23:08:01 +00006914
6915 bool Good = true;
6916 // Check goto/label use.
6917 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
6918 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
6919 LabelStmt *L = I->second;
6920
6921 // Verify that we have no forward references left. If so, there was a goto
6922 // or address of a label taken, but no definition of it.
6923 if (L->getSubStmt() != 0)
6924 continue;
6925
6926 // Emit error.
6927 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
6928 Good = false;
6929 }
6930 BSI->LabelMap.clear();
6931 if (!Good)
6932 return ExprError();
6933
Mike Stump1bacb812010-01-13 02:59:54 +00006934 AnalysisContext AC(BSI->TheDecl);
6935 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody(), AC);
6936 CheckUnreachable(AC);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006937 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6938 BSI->hasBlockDeclRefExprs));
Steve Naroffc540d662008-09-03 18:15:37 +00006939}
6940
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006941Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6942 ExprArg expr, TypeTy *type,
6943 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006944 QualType T = GetTypeFromParser(type);
Chris Lattner56382aa2009-04-05 15:49:53 +00006945 Expr *E = static_cast<Expr*>(expr.get());
6946 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00006947
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006948 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00006949
6950 // Get the va_list type
6951 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00006952 if (VaListType->isArrayType()) {
6953 // Deal with implicit array decay; for example, on x86-64,
6954 // va_list is an array, but it's supposed to decay to
6955 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00006956 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00006957 // Make sure the input expression also decays appropriately.
6958 UsualUnaryConversions(E);
6959 } else {
6960 // Otherwise, the va_list argument must be an l-value because
6961 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00006962 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00006963 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00006964 return ExprError();
6965 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00006966
Douglas Gregorad3150c2009-05-19 23:10:31 +00006967 if (!E->isTypeDependent() &&
6968 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006969 return ExprError(Diag(E->getLocStart(),
6970 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00006971 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00006972 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006973
Eli Friedmanba961a92009-03-23 00:24:07 +00006974 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006975 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006976
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006977 expr.release();
6978 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6979 RPLoc));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006980}
6981
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006982Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00006983 // The type of __null will be int or long, depending on the size of
6984 // pointers on the target.
6985 QualType Ty;
6986 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6987 Ty = Context.IntTy;
6988 else
6989 Ty = Context.LongTy;
6990
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006991 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00006992}
6993
Anders Carlssonace5d072009-11-10 04:46:30 +00006994static void
6995MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6996 QualType DstType,
6997 Expr *SrcExpr,
6998 CodeModificationHint &Hint) {
6999 if (!SemaRef.getLangOptions().ObjC1)
7000 return;
7001
7002 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
7003 if (!PT)
7004 return;
7005
7006 // Check if the destination is of type 'id'.
7007 if (!PT->isObjCIdType()) {
7008 // Check if the destination is the 'NSString' interface.
7009 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
7010 if (!ID || !ID->getIdentifier()->isStr("NSString"))
7011 return;
7012 }
7013
7014 // Strip off any parens and casts.
7015 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
7016 if (!SL || SL->isWide())
7017 return;
7018
7019 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
7020}
7021
Chris Lattner9bad62c2008-01-04 18:04:52 +00007022bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
7023 SourceLocation Loc,
7024 QualType DstType, QualType SrcType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007025 Expr *SrcExpr, AssignmentAction Action) {
Chris Lattner9bad62c2008-01-04 18:04:52 +00007026 // Decode the result (notice that AST's are still created for extensions).
7027 bool isInvalid = false;
7028 unsigned DiagKind;
Anders Carlssonace5d072009-11-10 04:46:30 +00007029 CodeModificationHint Hint;
7030
Chris Lattner9bad62c2008-01-04 18:04:52 +00007031 switch (ConvTy) {
7032 default: assert(0 && "Unknown conversion type");
7033 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00007034 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00007035 DiagKind = diag::ext_typecheck_convert_pointer_int;
7036 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00007037 case IntToPointer:
7038 DiagKind = diag::ext_typecheck_convert_int_pointer;
7039 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007040 case IncompatiblePointer:
Anders Carlssonace5d072009-11-10 04:46:30 +00007041 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007042 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
7043 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00007044 case IncompatiblePointerSign:
7045 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
7046 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007047 case FunctionVoidPointer:
7048 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
7049 break;
7050 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00007051 // If the qualifiers lost were because we were applying the
7052 // (deprecated) C++ conversion from a string literal to a char*
7053 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
7054 // Ideally, this check would be performed in
7055 // CheckPointerTypesForAssignment. However, that would require a
7056 // bit of refactoring (so that the second argument is an
7057 // expression, rather than a type), which should be done as part
7058 // of a larger effort to fix CheckPointerTypesForAssignment for
7059 // C++ semantics.
7060 if (getLangOptions().CPlusPlus &&
7061 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
7062 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007063 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
7064 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00007065 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00007066 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00007067 break;
Steve Naroff081c7422008-09-04 15:10:53 +00007068 case IntToBlockPointer:
7069 DiagKind = diag::err_int_to_block_pointer;
7070 break;
7071 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00007072 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00007073 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00007074 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00007075 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00007076 // it can give a more specific diagnostic.
7077 DiagKind = diag::warn_incompatible_qualified_id;
7078 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007079 case IncompatibleVectors:
7080 DiagKind = diag::warn_incompatible_vectors;
7081 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007082 case Incompatible:
7083 DiagKind = diag::err_typecheck_convert_incompatible;
7084 isInvalid = true;
7085 break;
7086 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007087
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007088 Diag(Loc, DiagKind) << DstType << SrcType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00007089 << SrcExpr->getSourceRange() << Hint;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007090 return isInvalid;
7091}
Anders Carlssone54e8a12008-11-30 19:50:32 +00007092
Chris Lattnerc71d08b2009-04-25 21:59:05 +00007093bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007094 llvm::APSInt ICEResult;
7095 if (E->isIntegerConstantExpr(ICEResult, Context)) {
7096 if (Result)
7097 *Result = ICEResult;
7098 return false;
7099 }
7100
Anders Carlssone54e8a12008-11-30 19:50:32 +00007101 Expr::EvalResult EvalResult;
7102
Mike Stump4e1f26a2009-02-19 03:04:26 +00007103 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00007104 EvalResult.HasSideEffects) {
7105 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7106
7107 if (EvalResult.Diag) {
7108 // We only show the note if it's not the usual "invalid subexpression"
7109 // or if it's actually in a subexpression.
7110 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7111 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7112 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7113 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007114
Anders Carlssone54e8a12008-11-30 19:50:32 +00007115 return true;
7116 }
7117
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007118 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7119 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00007120
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007121 if (EvalResult.Diag &&
7122 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7123 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007124
Anders Carlssone54e8a12008-11-30 19:50:32 +00007125 if (Result)
7126 *Result = EvalResult.Val.getInt();
7127 return false;
7128}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007129
Douglas Gregorff790f12009-11-26 00:44:06 +00007130void
Mike Stump11289f42009-09-09 15:08:12 +00007131Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00007132 ExprEvalContexts.push_back(
7133 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007134}
7135
Mike Stump11289f42009-09-09 15:08:12 +00007136void
Douglas Gregorff790f12009-11-26 00:44:06 +00007137Sema::PopExpressionEvaluationContext() {
7138 // Pop the current expression evaluation context off the stack.
7139 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7140 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007141
Douglas Gregorfab31f42009-12-12 07:57:52 +00007142 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7143 if (Rec.PotentiallyReferenced) {
7144 // Mark any remaining declarations in the current position of the stack
7145 // as "referenced". If they were not meant to be referenced, semantic
7146 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
7147 for (PotentiallyReferencedDecls::iterator
7148 I = Rec.PotentiallyReferenced->begin(),
7149 IEnd = Rec.PotentiallyReferenced->end();
7150 I != IEnd; ++I)
7151 MarkDeclarationReferenced(I->first, I->second);
7152 }
7153
7154 if (Rec.PotentiallyDiagnosed) {
7155 // Emit any pending diagnostics.
7156 for (PotentiallyEmittedDiagnostics::iterator
7157 I = Rec.PotentiallyDiagnosed->begin(),
7158 IEnd = Rec.PotentiallyDiagnosed->end();
7159 I != IEnd; ++I)
7160 Diag(I->first, I->second);
7161 }
Douglas Gregorff790f12009-11-26 00:44:06 +00007162 }
7163
7164 // When are coming out of an unevaluated context, clear out any
7165 // temporaries that we may have created as part of the evaluation of
7166 // the expression in that context: they aren't relevant because they
7167 // will never be constructed.
7168 if (Rec.Context == Unevaluated &&
7169 ExprTemporaries.size() > Rec.NumTemporaries)
7170 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7171 ExprTemporaries.end());
7172
7173 // Destroy the popped expression evaluation record.
7174 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007175}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007176
7177/// \brief Note that the given declaration was referenced in the source code.
7178///
7179/// This routine should be invoke whenever a given declaration is referenced
7180/// in the source code, and where that reference occurred. If this declaration
7181/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7182/// C99 6.9p3), then the declaration will be marked as used.
7183///
7184/// \param Loc the location where the declaration was referenced.
7185///
7186/// \param D the declaration that has been referenced by the source code.
7187void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7188 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00007189
Douglas Gregor77b50e12009-06-22 23:06:13 +00007190 if (D->isUsed())
7191 return;
Mike Stump11289f42009-09-09 15:08:12 +00007192
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00007193 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7194 // template or not. The reason for this is that unevaluated expressions
7195 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7196 // -Wunused-parameters)
7197 if (isa<ParmVarDecl>(D) ||
7198 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007199 D->setUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +00007200
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007201 // Do not mark anything as "used" within a dependent context; wait for
7202 // an instantiation.
7203 if (CurContext->isDependentContext())
7204 return;
Mike Stump11289f42009-09-09 15:08:12 +00007205
Douglas Gregorff790f12009-11-26 00:44:06 +00007206 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007207 case Unevaluated:
7208 // We are in an expression that is not potentially evaluated; do nothing.
7209 return;
Mike Stump11289f42009-09-09 15:08:12 +00007210
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007211 case PotentiallyEvaluated:
7212 // We are in a potentially-evaluated expression, so this declaration is
7213 // "used"; handle this below.
7214 break;
Mike Stump11289f42009-09-09 15:08:12 +00007215
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007216 case PotentiallyPotentiallyEvaluated:
7217 // We are in an expression that may be potentially evaluated; queue this
7218 // declaration reference until we know whether the expression is
7219 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00007220 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007221 return;
7222 }
Mike Stump11289f42009-09-09 15:08:12 +00007223
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007224 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00007225 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007226 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007227 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7228 if (!Constructor->isUsed())
7229 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00007230 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00007231 Constructor->isCopyConstructor(TypeQuals)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007232 if (!Constructor->isUsed())
7233 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7234 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007235
7236 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007237 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7238 if (Destructor->isImplicit() && !Destructor->isUsed())
7239 DefineImplicitDestructor(Loc, Destructor);
Mike Stump11289f42009-09-09 15:08:12 +00007240
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007241 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7242 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7243 MethodDecl->getOverloadedOperator() == OO_Equal) {
7244 if (!MethodDecl->isUsed())
7245 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7246 }
7247 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00007248 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00007249 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00007250 // class templates.
Douglas Gregorafca3b42009-10-27 20:53:28 +00007251 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00007252 bool AlreadyInstantiated = false;
7253 if (FunctionTemplateSpecializationInfo *SpecInfo
7254 = Function->getTemplateSpecializationInfo()) {
7255 if (SpecInfo->getPointOfInstantiation().isInvalid())
7256 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007257 else if (SpecInfo->getTemplateSpecializationKind()
7258 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007259 AlreadyInstantiated = true;
7260 } else if (MemberSpecializationInfo *MSInfo
7261 = Function->getMemberSpecializationInfo()) {
7262 if (MSInfo->getPointOfInstantiation().isInvalid())
7263 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007264 else if (MSInfo->getTemplateSpecializationKind()
7265 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007266 AlreadyInstantiated = true;
7267 }
7268
Douglas Gregor7f792cf2010-01-16 22:29:39 +00007269 if (!AlreadyInstantiated) {
7270 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
7271 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
7272 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
7273 Loc));
7274 else
7275 PendingImplicitInstantiations.push_back(std::make_pair(Function,
7276 Loc));
7277 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007278 }
7279
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007280 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007281 Function->setUsed(true);
7282 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00007283 }
Mike Stump11289f42009-09-09 15:08:12 +00007284
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007285 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007286 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00007287 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00007288 Var->getInstantiatedFromStaticDataMember()) {
7289 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7290 assert(MSInfo && "Missing member specialization information?");
7291 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7292 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7293 MSInfo->setPointOfInstantiation(Loc);
7294 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7295 }
7296 }
Mike Stump11289f42009-09-09 15:08:12 +00007297
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007298 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007299
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007300 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007301 return;
Sam Weinigbae69142009-09-11 03:29:30 +00007302 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007303}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007304
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007305/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7306/// of the program being compiled.
7307///
7308/// This routine emits the given diagnostic when the code currently being
7309/// type-checked is "potentially evaluated", meaning that there is a
7310/// possibility that the code will actually be executable. Code in sizeof()
7311/// expressions, code used only during overload resolution, etc., are not
7312/// potentially evaluated. This routine will suppress such diagnostics or,
7313/// in the absolutely nutty case of potentially potentially evaluated
7314/// expressions (C++ typeid), queue the diagnostic to potentially emit it
7315/// later.
7316///
7317/// This routine should be used for all diagnostics that describe the run-time
7318/// behavior of a program, such as passing a non-POD value through an ellipsis.
7319/// Failure to do so will likely result in spurious diagnostics or failures
7320/// during overload resolution or within sizeof/alignof/typeof/typeid.
7321bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
7322 const PartialDiagnostic &PD) {
7323 switch (ExprEvalContexts.back().Context ) {
7324 case Unevaluated:
7325 // The argument will never be evaluated, so don't complain.
7326 break;
7327
7328 case PotentiallyEvaluated:
7329 Diag(Loc, PD);
7330 return true;
7331
7332 case PotentiallyPotentiallyEvaluated:
7333 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7334 break;
7335 }
7336
7337 return false;
7338}
7339
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007340bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7341 CallExpr *CE, FunctionDecl *FD) {
7342 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7343 return false;
7344
7345 PartialDiagnostic Note =
7346 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7347 << FD->getDeclName() : PDiag();
7348 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7349
7350 if (RequireCompleteType(Loc, ReturnType,
7351 FD ?
7352 PDiag(diag::err_call_function_incomplete_return)
7353 << CE->getSourceRange() << FD->getDeclName() :
7354 PDiag(diag::err_call_incomplete_return)
7355 << CE->getSourceRange(),
7356 std::make_pair(NoteLoc, Note)))
7357 return true;
7358
7359 return false;
7360}
7361
John McCalld5707ab2009-10-12 21:59:07 +00007362// Diagnose the common s/=/==/ typo. Note that adding parentheses
7363// will prevent this condition from triggering, which is what we want.
7364void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7365 SourceLocation Loc;
7366
John McCall0506e4a2009-11-11 02:41:58 +00007367 unsigned diagnostic = diag::warn_condition_is_assignment;
7368
John McCalld5707ab2009-10-12 21:59:07 +00007369 if (isa<BinaryOperator>(E)) {
7370 BinaryOperator *Op = cast<BinaryOperator>(E);
7371 if (Op->getOpcode() != BinaryOperator::Assign)
7372 return;
7373
John McCallb0e419e2009-11-12 00:06:05 +00007374 // Greylist some idioms by putting them into a warning subcategory.
7375 if (ObjCMessageExpr *ME
7376 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7377 Selector Sel = ME->getSelector();
7378
John McCallb0e419e2009-11-12 00:06:05 +00007379 // self = [<foo> init...]
7380 if (isSelfExpr(Op->getLHS())
7381 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7382 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7383
7384 // <foo> = [<bar> nextObject]
7385 else if (Sel.isUnarySelector() &&
7386 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7387 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7388 }
John McCall0506e4a2009-11-11 02:41:58 +00007389
John McCalld5707ab2009-10-12 21:59:07 +00007390 Loc = Op->getOperatorLoc();
7391 } else if (isa<CXXOperatorCallExpr>(E)) {
7392 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7393 if (Op->getOperator() != OO_Equal)
7394 return;
7395
7396 Loc = Op->getOperatorLoc();
7397 } else {
7398 // Not an assignment.
7399 return;
7400 }
7401
John McCalld5707ab2009-10-12 21:59:07 +00007402 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00007403 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCalld5707ab2009-10-12 21:59:07 +00007404
John McCall0506e4a2009-11-11 02:41:58 +00007405 Diag(Loc, diagnostic)
John McCalld5707ab2009-10-12 21:59:07 +00007406 << E->getSourceRange()
7407 << CodeModificationHint::CreateInsertion(Open, "(")
7408 << CodeModificationHint::CreateInsertion(Close, ")");
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007409 Diag(Loc, diag::note_condition_assign_to_comparison)
7410 << CodeModificationHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00007411}
7412
7413bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7414 DiagnoseAssignmentAsCondition(E);
7415
7416 if (!E->isTypeDependent()) {
Douglas Gregorb92a1562010-02-03 00:27:59 +00007417 DefaultFunctionArrayLvalueConversion(E);
John McCalld5707ab2009-10-12 21:59:07 +00007418
7419 QualType T = E->getType();
7420
7421 if (getLangOptions().CPlusPlus) {
7422 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7423 return true;
7424 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7425 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7426 << T << E->getSourceRange();
7427 return true;
7428 }
7429 }
7430
7431 return false;
7432}